MX 2 лет назад
Родитель
Сommit
ad9e7b7905
100 измененных файлов с 9053 добавлено и 1 удалено
  1. 3 1
      ReadMe.md
  2. BIN
      apps/GPIO/esp_flasher.fap
  3. BIN
      apps/GPIO/flipperscope.fap
  4. BIN
      apps/GPIO/scope.fap
  5. BIN
      apps/NFC/seader.fap
  6. BIN
      apps/Sub-GHz/esubghz_chat.fap
  7. BIN
      apps/Sub-GHz/tpms.fap
  8. 4 0
      main_apps_sources/doom/.gitignore
  9. 10 0
      main_apps_sources/doom/README.md
  10. 18 0
      main_apps_sources/doom/application.fam
  11. 331 0
      main_apps_sources/doom/assets.c
  12. 108 0
      main_apps_sources/doom/assets.h
  13. BIN
      main_apps_sources/doom/assets/door2.png
  14. BIN
      main_apps_sources/doom/assets/door_inv.png
  15. BIN
      main_apps_sources/doom/assets/fire_inv.png
  16. BIN
      main_apps_sources/doom/assets/fireball_inv.png
  17. BIN
      main_apps_sources/doom/assets/fireball_mask_inv.png
  18. BIN
      main_apps_sources/doom/assets/gradient_inv.png
  19. BIN
      main_apps_sources/doom/assets/gun_inv.png
  20. BIN
      main_apps_sources/doom/assets/gun_mask_inv.png
  21. BIN
      main_apps_sources/doom/assets/imp_inv.png
  22. BIN
      main_apps_sources/doom/assets/imp_mask_inv.png
  23. BIN
      main_apps_sources/doom/assets/item_inv.png
  24. BIN
      main_apps_sources/doom/assets/item_mask_inv.png
  25. BIN
      main_apps_sources/doom/assets/logo_inv.png
  26. 91 0
      main_apps_sources/doom/constants.h
  27. 280 0
      main_apps_sources/doom/display.h
  28. 1104 0
      main_apps_sources/doom/doom.c
  29. BIN
      main_apps_sources/doom/doom_10px.png
  30. 504 0
      main_apps_sources/doom/doom_music_player_worker.c
  31. 44 0
      main_apps_sources/doom/doom_music_player_worker.h
  32. 42 0
      main_apps_sources/doom/entities.c
  33. 56 0
      main_apps_sources/doom/entities.h
  34. BIN
      main_apps_sources/doom/img/1.png
  35. BIN
      main_apps_sources/doom/img/2.png
  36. BIN
      main_apps_sources/doom/img/3.png
  37. 188 0
      main_apps_sources/doom/level.h
  38. 34 0
      main_apps_sources/doom/sound.h
  39. 33 0
      main_apps_sources/doom/types.c
  40. 36 0
      main_apps_sources/doom/types.h
  41. 674 0
      main_apps_sources/gps_nmea_uart/LICENSE
  42. 46 0
      main_apps_sources/gps_nmea_uart/README.md
  43. 14 0
      main_apps_sources/gps_nmea_uart/application.fam
  44. 190 0
      main_apps_sources/gps_nmea_uart/gps.c
  45. BIN
      main_apps_sources/gps_nmea_uart/gps_10px.png
  46. 217 0
      main_apps_sources/gps_nmea_uart/gps_uart.c
  47. 46 0
      main_apps_sources/gps_nmea_uart/gps_uart.h
  48. BIN
      main_apps_sources/gps_nmea_uart/img/1.png
  49. BIN
      main_apps_sources/gps_nmea_uart/img/2.png
  50. BIN
      main_apps_sources/gps_nmea_uart/img/3.png
  51. 640 0
      main_apps_sources/gps_nmea_uart/minmea.c
  52. 295 0
      main_apps_sources/gps_nmea_uart/minmea.h
  53. BIN
      main_apps_sources/gps_nmea_uart/ui.png
  54. BIN
      main_apps_sources/gps_nmea_uart/wiring.png
  55. 18 0
      main_apps_sources/pocsag_pager/README.md
  56. 15 0
      main_apps_sources/pocsag_pager/application.fam
  57. 14 0
      main_apps_sources/pocsag_pager/helpers/pocsag_pager_event.h
  58. 49 0
      main_apps_sources/pocsag_pager/helpers/pocsag_pager_types.h
  59. 66 0
      main_apps_sources/pocsag_pager/helpers/radio_device_loader.c
  60. 17 0
      main_apps_sources/pocsag_pager/helpers/radio_device_loader.h
  61. BIN
      main_apps_sources/pocsag_pager/images/Fishing_123x52.png
  62. BIN
      main_apps_sources/pocsag_pager/images/Lock_7x8.png
  63. BIN
      main_apps_sources/pocsag_pager/images/Message_8x7.png
  64. BIN
      main_apps_sources/pocsag_pager/images/Pin_back_arrow_10x8.png
  65. BIN
      main_apps_sources/pocsag_pager/images/Quest_7x8.png
  66. BIN
      main_apps_sources/pocsag_pager/images/Scanning_123x52.png
  67. BIN
      main_apps_sources/pocsag_pager/images/Unlock_7x8.png
  68. BIN
      main_apps_sources/pocsag_pager/images/WarningDolphin_45x42.png
  69. BIN
      main_apps_sources/pocsag_pager/img/1.png
  70. BIN
      main_apps_sources/pocsag_pager/img/2.png
  71. BIN
      main_apps_sources/pocsag_pager/img/3.png
  72. BIN
      main_apps_sources/pocsag_pager/pocsag_pager_10px.png
  73. 206 0
      main_apps_sources/pocsag_pager/pocsag_pager_app.c
  74. 146 0
      main_apps_sources/pocsag_pager/pocsag_pager_app_i.c
  75. 76 0
      main_apps_sources/pocsag_pager/pocsag_pager_app_i.h
  76. 223 0
      main_apps_sources/pocsag_pager/pocsag_pager_history.c
  77. 112 0
      main_apps_sources/pocsag_pager/pocsag_pager_history.h
  78. 124 0
      main_apps_sources/pocsag_pager/protocols/pcsg_generic.c
  79. 56 0
      main_apps_sources/pocsag_pager/protocols/pcsg_generic.h
  80. 374 0
      main_apps_sources/pocsag_pager/protocols/pocsag.c
  81. 13 0
      main_apps_sources/pocsag_pager/protocols/pocsag.h
  82. 9 0
      main_apps_sources/pocsag_pager/protocols/protocol_items.c
  83. 6 0
      main_apps_sources/pocsag_pager/protocols/protocol_items.h
  84. 214 0
      main_apps_sources/pocsag_pager/scenes/pocsag_pager_receiver.c
  85. 30 0
      main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene.c
  86. 29 0
      main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene.h
  87. 74 0
      main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_about.c
  88. 5 0
      main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_config.h
  89. 221 0
      main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_receiver_config.c
  90. 50 0
      main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_receiver_info.c
  91. 58 0
      main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_start.c
  92. 478 0
      main_apps_sources/pocsag_pager/views/pocsag_pager_receiver.c
  93. 43 0
      main_apps_sources/pocsag_pager/views/pocsag_pager_receiver.h
  94. 137 0
      main_apps_sources/pocsag_pager/views/pocsag_pager_receiver_info.c
  95. 16 0
      main_apps_sources/pocsag_pager/views/pocsag_pager_receiver_info.h
  96. 24 0
      main_apps_sources/protoview/LICENSE
  97. 159 0
      main_apps_sources/protoview/README.md
  98. 400 0
      main_apps_sources/protoview/app.c
  99. 377 0
      main_apps_sources/protoview/app.h
  100. 206 0
      main_apps_sources/protoview/app_subghz.c

+ 3 - 1
ReadMe.md

@@ -20,7 +20,7 @@ Sources of "integrated/bundled" apps are added now in this repo too, to allow pu
 
 
 The Flipper and its community wouldn't be as rich as it is without your contributions and support. Thank you for all you have done.
 The Flipper and its community wouldn't be as rich as it is without your contributions and support. Thank you for all you have done.
 
 
-### Apps checked & updated at `18 Jul 02:22 GMT +3`
+### Apps checked & updated at `24 Jul 01:07 GMT +3`
 
 
 ## Games
 ## Games
 - [Pong (By nmrr)](https://github.com/nmrr/flipperzero-pong) - Modified by [SimplyMinimal](https://github.com/SimplyMinimal/FlipperZero-Pong)
 - [Pong (By nmrr)](https://github.com/nmrr/flipperzero-pong) - Modified by [SimplyMinimal](https://github.com/SimplyMinimal/FlipperZero-Pong)
@@ -129,6 +129,8 @@ The Flipper and its community wouldn't be as rich as it is without your contribu
 - [CLI-GUI Bridge (By ranchordo)](https://github.com/ranchordo/flipperzero-cli-bridge) -> (Fixed by @Willy-JL)
 - [CLI-GUI Bridge (By ranchordo)](https://github.com/ranchordo/flipperzero-cli-bridge) -> (Fixed by @Willy-JL)
 - [Seader (By bettse)](https://github.com/bettse/seader/tree/main) - `Interface with a SAM from the Flipper Zero over UART`
 - [Seader (By bettse)](https://github.com/bettse/seader/tree/main) - `Interface with a SAM from the Flipper Zero over UART`
 - [RFID Beacon (By nmrr)](https://github.com/nmrr/flipperzero-rfidbeacon) - `A letter/number Morse beacon on 125 kHz`
 - [RFID Beacon (By nmrr)](https://github.com/nmrr/flipperzero-rfidbeacon) - `A letter/number Morse beacon on 125 kHz`
+- [Enhanced Sub-GHz Chat (By twisted-pear)](https://github.com/twisted-pear/esubghz_chat)
+- [TPMS Reader (By wosk)](https://github.com/wosk/flipperzero-tpms/tree/main)
 
 
 --- 
 --- 
 
 

BIN
apps/GPIO/esp_flasher.fap


BIN
apps/GPIO/flipperscope.fap


BIN
apps/GPIO/scope.fap


BIN
apps/NFC/seader.fap


BIN
apps/Sub-GHz/esubghz_chat.fap


BIN
apps/Sub-GHz/tpms.fap


+ 4 - 0
main_apps_sources/doom/.gitignore

@@ -0,0 +1,4 @@
+dist/*
+.vscode
+.clang-format
+.editorconfig

+ 10 - 0
main_apps_sources/doom/README.md

@@ -0,0 +1,10 @@
+# Doom Flipper Zero edition
+## Will it run Doom?
+As tradition goes, Doom is being ported to almost every possible embedded electronic device. Therefore I did an attempt to come up with something close to Doom and still compatible on the Flipper Zero's hardware. This is not the actual Doom game but a port made from yet another Doom port to the Arduino Nano - https://github.com/daveruiz/doom-nano/. This port is basically a raycasting engine, using Doom sprites.
+This version is very basic and might be improved over time.
+
+## Credits
+@xMasterX - Porting to latest firmware using new plugins system, fixing many issues, adding sound
+@Svaarich - New logo screen and cool icon
+@hedger - uFBT fixes and some bugfixes
+@p4nic4ttack - First raw implementation based on doom-nano

+ 18 - 0
main_apps_sources/doom/application.fam

@@ -0,0 +1,18 @@
+App(
+    appid="doom",
+    name="DOOM",
+    apptype=FlipperAppType.EXTERNAL,
+    entry_point="doom_app",
+    requires=[
+        "gui",
+        "music_player",
+    ],
+    stack_size=4 * 1024,
+    order=75,
+    fap_icon="doom_10px.png",
+    fap_category="Games",
+    fap_icon_assets="assets",
+    fap_author="@xMasterX & @Svarich & @hedger (original code by @p4nic4ttack)",
+    fap_version="1.0",
+    fap_description="Will it run Doom?",
+)

+ 331 - 0
main_apps_sources/doom/assets.c

@@ -0,0 +1,331 @@
+#include "assets.h"
+
+const uint8_t space[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t zero[] = {0x00, 0x60, 0x90, 0x90, 0x90, 0x60};
+const uint8_t one[] = {0x00, 0x20, 0x20, 0x20, 0x20, 0x70};
+const uint8_t two[] = {0x00, 0x60, 0x90, 0x20, 0x40, 0xf0};
+const uint8_t three[] = {0x00, 0x60, 0x90, 0x20, 0x90, 0x60};
+const uint8_t four[] = {0x00, 0x90, 0x90, 0xf0, 0x10, 0x10};
+const uint8_t five[] = {0x00, 0xf0, 0x80, 0xe0, 0x10, 0xe0};
+const uint8_t six[] = {0x00, 0x60, 0x80, 0xe0, 0x90, 0x60};
+const uint8_t seven[] = {0x00, 0xf0, 0x10, 0x10, 0x10, 0x10};
+const uint8_t eight[] = {0x00, 0x60, 0x90, 0x60, 0x90, 0x60};
+const uint8_t nine[] = {0x00, 0x60, 0x90, 0x70, 0x10, 0x60};
+const uint8_t A[] = {0x00, 0x60, 0x90, 0xf0, 0x90, 0x90};
+const uint8_t B[] = {0x00, 0xe0, 0x90, 0xe0, 0x90, 0xe0};
+const uint8_t C[] = {0x00, 0x60, 0x90, 0x80, 0x90, 0x60};
+const uint8_t D[] = {0x00, 0xe0, 0x90, 0x90, 0x90, 0xe0};
+const uint8_t E[] = {0x00, 0xf0, 0x80, 0xe0, 0x80, 0xf0};
+const uint8_t F[] = {0x00, 0xf0, 0x80, 0xe0, 0x80, 0x80};
+const uint8_t G[] = {0x00, 0x60, 0x80, 0x80, 0x90, 0x60};
+const uint8_t H[] = {0x00, 0x90, 0x90, 0xf0, 0x90, 0x90};
+const uint8_t I[] = {0x00, 0x20, 0x20, 0x20, 0x20, 0x20};
+const uint8_t J[] = {0x00, 0x10, 0x10, 0x10, 0x90, 0x60};
+const uint8_t K[] = {0x00, 0x90, 0xa0, 0xc0, 0xa0, 0x90};
+const uint8_t L[] = {0x00, 0x80, 0x80, 0x80, 0x80, 0xf0};
+const uint8_t M[] = {0x00, 0x90, 0xf0, 0x90, 0x90, 0x90};
+const uint8_t N[] = {0x00, 0x90, 0xd0, 0xb0, 0x90, 0x90};
+const uint8_t O[] = {0x00, 0x60, 0x90, 0x90, 0x90, 0x60};
+const uint8_t P[] = {0x00, 0xe0, 0x90, 0xe0, 0x80, 0x80};
+const uint8_t Q[] = {0x00, 0x60, 0x90, 0x90, 0xb0, 0x70};
+const uint8_t R[] = {0x00, 0xe0, 0x90, 0xe0, 0x90, 0x90};
+const uint8_t S[] = {0x00, 0x60, 0x80, 0x60, 0x10, 0xe0};
+const uint8_t T[] = {0x00, 0xe0, 0x40, 0x40, 0x40, 0x40};
+const uint8_t U[] = {0x00, 0x90, 0x90, 0x90, 0x90, 0x60};
+const uint8_t V[] = {0x00, 0x90, 0x90, 0x90, 0x60, 0x60};
+const uint8_t W[] = {0x00, 0x90, 0x90, 0x90, 0xf0, 0x90};
+const uint8_t X[] = {0x00, 0x90, 0x90, 0x60, 0x90, 0x90};
+const uint8_t Y[] = {0x00, 0x90, 0x90, 0x60, 0x60, 0x60};
+const uint8_t Z[] = {0x00, 0xf0, 0x10, 0x60, 0x80, 0xf0};
+const uint8_t dot[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x40};
+const uint8_t comma[] = {0x00, 0x00, 0x00, 0x00, 0x20, 0x40};
+const uint8_t dash[] = {0x00, 0x00, 0x00, 0x60, 0x00, 0x00};
+const uint8_t underscore[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0xf0};
+const uint8_t bracket_open[] = {0x00, 0x20, 0x40, 0x40, 0x40, 0x20};
+const uint8_t bracket_close[] = {0x00, 0x40, 0x20, 0x20, 0x20, 0x40};
+const uint8_t cross_left[] = {0x10, 0x10, 0x70, 0x70, 0x10, 0x10};
+const uint8_t cross_right[] = {0x80, 0x80, 0xe0, 0xe0, 0x80, 0x80};
+const uint8_t pacman_left[] = {0x00, 0x30, 0x50, 0x70, 0x70, 0x00};
+const uint8_t pacman_right[] = {0x00, 0xc0, 0x60, 0xe0, 0xe0, 0xe0};
+const uint8_t box[] = {0x00, 0xf0, 0xf0, 0xf0, 0xf0, 0x00};
+const uint8_t* char_arr[48] = {
+    space,
+    zero,
+    one,
+    two,
+    three,
+    four,
+    five,
+    six,
+    seven,
+    eight,
+    nine,
+    A,
+    B,
+    C,
+    D,
+    E,
+    F,
+    G,
+    H,
+    I,
+    J,
+    K,
+    L,
+    M,
+    N,
+    O,
+    P,
+    Q,
+    R,
+    S,
+    T,
+    U,
+    V,
+    W,
+    X,
+    Y,
+    Z,
+    dot,
+    comma,
+    dash,
+    underscore,
+    bracket_open,
+    bracket_close,
+    cross_left,
+    cross_right,
+    pacman_left,
+    pacman_right,
+    box};
+const uint8_t gradient[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88, 0x00, 0x00, 0x22, 0x22,
+                            0x00, 0x00, 0x8a, 0x8a, 0x00, 0x00, 0x22, 0x22, 0x00, 0x00, 0xaa, 0xaa,
+                            0x10, 0x10, 0xaa, 0xaa, 0x00, 0x00, 0xaa, 0xaa, 0x01, 0x01, 0xaa, 0xaa,
+                            0x44, 0x44, 0xaa, 0xaa, 0x55, 0x55, 0xaa, 0xaa, 0x44, 0x44, 0xaa, 0xaa,
+                            0x15, 0x55, 0xaa, 0xaa, 0x55, 0x55, 0xaa, 0xaa, 0x55, 0x55, 0xbb, 0xbb,
+                            0x55, 0x55, 0xaa, 0xea, 0x55, 0x55, 0xbb, 0xbb, 0x55, 0x55, 0xff, 0xff,
+                            0x55, 0x55, 0xfb, 0xfb, 0x55, 0x55, 0xff, 0xff, 0x55, 0x55, 0xbb, 0xbf,
+                            0x57, 0x57, 0xff, 0xff, 0xdd, 0xdd, 0xff, 0xff, 0x77, 0x75, 0xff, 0xff,
+                            0xdd, 0xdd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+                            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+//const uint8_t gun[] = {0xff, 0xff, 0xdf, 0xff, 0xff, 0xff, 0x27, 0xff, 0xff, 0xfe, 0x3b, 0xff, 0xff, 0xfd, 0xfb, 0xff, 0xff, 0xfd, 0xfd, 0xff, 0xff, 0xfd, 0x15, 0xff, 0xff, 0xfb, 0x2e, 0xff, 0xff, 0xf6, 0x77, 0x7f, 0xff, 0xe6, 0xff, 0xff, 0xff, 0xf2, 0x3d, 0x7f, 0xff, 0xd6, 0x7e, 0x3f, 0xff, 0xf4, 0x5d, 0xdf, 0xff, 0xce, 0xbf, 0xbf, 0xff, 0xdc, 0xff, 0x3f, 0xff, 0xec, 0xff, 0xbf, 0xff, 0x8d, 0xfd, 0xff, 0xff, 0xb6, 0xff, 0xbf, 0xfe, 0x1f, 0x57, 0xdf, 0xf8, 0x0e, 0xff, 0xcf, 0xf4, 0x46, 0x1f, 0x17, 0xf8, 0xa3, 0xfc, 0x03, 0xf8, 0x10, 0x00, 0x11, 0xf8, 0x8a, 0x80, 0x2d, 0xe4, 0x44, 0x00, 0x4d, 0xee, 0xa8, 0x82, 0x9b, 0xcd, 0x50, 0x00, 0x17, 0xec, 0xa0, 0x8a, 0x2f, 0xcc, 0x00, 0x04, 0x67, 0xe8, 0x28, 0x1a, 0xff, 0xe4, 0x70, 0x4d, 0xcf, 0xfc, 0x82, 0xa7, 0xef, 0x90, 0x40, 0x13, 0xdf};
+// const uint8_t gun_mask[] = {0xff, 0xff, 0x8f, 0xff, 0xff, 0xfe, 0x03, 0xff, 0xff, 0xfc, 0x01, 0xff, 0xff, 0xf8, 0x01, 0xff, 0xff, 0xf8, 0x00, 0xff, 0xff, 0xf8, 0x00, 0xff, 0xff, 0xf0, 0x00, 0x7f, 0xff, 0xe0, 0x00, 0x3f, 0xff, 0xc0, 0x00, 0x7f, 0xff, 0xc0, 0x00, 0x3f, 0xff, 0x80, 0x00, 0x1f, 0xff, 0x80, 0x00, 0x0f, 0xff, 0x80, 0x00, 0x1f, 0xff, 0x80, 0x00, 0x1f, 0xff, 0x80, 0x00, 0x1f, 0xff, 0x00, 0x00, 0x3f, 0xff, 0x00, 0x00, 0x1f, 0xfc, 0x00, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x07, 0xe0, 0x00, 0x00, 0x03, 0xe0, 0x00, 0x00, 0x01, 0xe0, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0x07, 0x80, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0x07, 0x80, 0x00, 0x00, 0x07, 0x80, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0f};
+const uint8_t gun[] = {0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xd8, 0x00, 0x00, 0x01, 0xc4, 0x00,
+                       0x00, 0x02, 0x04, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x02, 0xea, 0x00,
+                       0x00, 0x04, 0xd1, 0x00, 0x00, 0x09, 0x88, 0x80, 0x00, 0x19, 0x00, 0x00,
+                       0x00, 0x0d, 0xc2, 0x80, 0x00, 0x29, 0x81, 0xc0, 0x00, 0x0b, 0xa2, 0x20,
+                       0x00, 0x31, 0x40, 0x40, 0x00, 0x23, 0x00, 0xc0, 0x00, 0x13, 0x00, 0x40,
+                       0x00, 0x72, 0x02, 0x00, 0x00, 0x49, 0x00, 0x40, 0x01, 0xe0, 0xa8, 0x20,
+                       0x07, 0xf1, 0x00, 0x30, 0x0b, 0xb9, 0xe0, 0xe8, 0x07, 0x5c, 0x03, 0xfc,
+                       0x07, 0xef, 0xff, 0xee, 0x07, 0x75, 0x7f, 0xd2, 0x1b, 0xbb, 0xff, 0xb2,
+                       0x11, 0x57, 0x7d, 0x64, 0x32, 0xaf, 0xff, 0xe8, 0x13, 0x5f, 0x75, 0xd0,
+                       0x33, 0xff, 0xfb, 0x98, 0x17, 0xd7, 0xe5, 0x00, 0x1b, 0x8f, 0xb2, 0x30,
+                       0x03, 0x7d, 0x58, 0x10, 0x6f, 0xbf, 0xec, 0x20};
+const uint8_t gun_mask[] = {0x00, 0x00, 0x70, 0x00, 0x00, 0x01, 0xfc, 0x00, 0x00, 0x03, 0xfe, 0x00,
+                            0x00, 0x07, 0xfe, 0x00, 0x00, 0x07, 0xff, 0x00, 0x00, 0x07, 0xff, 0x00,
+                            0x00, 0x0f, 0xff, 0x80, 0x00, 0x1f, 0xff, 0xc0, 0x00, 0x3f, 0xff, 0x80,
+                            0x00, 0x3f, 0xff, 0xc0, 0x00, 0x7f, 0xff, 0xe0, 0x00, 0x7f, 0xff, 0xf0,
+                            0x00, 0x7f, 0xff, 0xe0, 0x00, 0x7f, 0xff, 0xe0, 0x00, 0x7f, 0xff, 0xe0,
+                            0x00, 0xff, 0xff, 0xc0, 0x00, 0xff, 0xff, 0xe0, 0x03, 0xff, 0xff, 0xf0,
+                            0x0f, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xfc, 0x1f, 0xff, 0xff, 0xfe,
+                            0x1f, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0x3f, 0xff, 0xff, 0xff,
+                            0x3f, 0xff, 0xff, 0xfe, 0x7f, 0xff, 0xff, 0xfc, 0x7f, 0xff, 0xff, 0xf8,
+                            0x7f, 0xff, 0xff, 0xfc, 0x7f, 0xff, 0xff, 0xf8, 0x7f, 0xff, 0xff, 0xf8,
+                            0x7f, 0xff, 0xff, 0xf8, 0xff, 0xff, 0xff, 0xf0};
+
+const uint8_t
+    imp_inv[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00,
+                 0x02, 0x80, 0x00, 0x00, 0x07, 0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01,
+                 0x00, 0x00, 0x01, 0x0f, 0xb3, 0x00, 0x00, 0xd0, 0x4e, 0x00, 0x00, 0x79, 0x8c,
+                 0x00, 0x00, 0x1c, 0x19, 0x00, 0x01, 0x8a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x40, 0x02, 0x08, 0x00, 0x80, 0x00, 0x00, 0x01, 0x00, 0x01, 0x8e,
+                 0x30, 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x0c, 0x20, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x06, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+                 0x02, 0x20, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x02, 0x40, 0x00, 0x00, 0x03, 0xe0,
+                 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0xa1, 0x80, 0x01, 0x80, 0x13, 0x00,
+                 0x00, 0xf3, 0x8a, 0x00, 0x00, 0x09, 0x94, 0x00, 0x00, 0x88, 0x38, 0x80, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x02, 0x23, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x80,
+                 0x00, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00, 0xe2, 0x80, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x0c, 0x20, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x02, 0x20, 0x00,
+                 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+                 0x02, 0x20, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa0,
+                 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00,
+                 0x00, 0x1f, 0x00, 0x00, 0x02, 0x2a, 0x80, 0x00, 0x01, 0x05, 0x00, 0x00, 0x01,
+                 0xae, 0x20, 0x00, 0x01, 0x24, 0x40, 0x00, 0x02, 0xac, 0x80, 0x00, 0x02, 0x86,
+                 0x00, 0x00, 0x03, 0x20, 0x20, 0x00, 0x04, 0x30, 0x40, 0x00, 0x0c, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x08, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x1a, 0x00, 0x00, 0x00,
+                 0x1c, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, 0x98,
+                 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0a, 0x00,
+                 0x00, 0x00, 0x08, 0x40, 0x00, 0x00, 0x00, 0x80, 0x00, 0x01, 0xd6, 0x80, 0x00,
+                 0x02, 0xbf, 0x80, 0x00, 0x06, 0x61, 0xa0, 0x00, 0x0c, 0xe8, 0x80, 0x00, 0x0c,
+                 0x10, 0x00, 0x00, 0x1a, 0x22, 0x00, 0x00, 0x12, 0x40, 0x00, 0x00, 0x06, 0x0c,
+                 0x00, 0x00, 0x04, 0x0d, 0x00, 0x00, 0x3a, 0x03, 0x00, 0x00, 0x10, 0x02, 0x00,
+                 0x00, 0x60, 0x0a, 0x00, 0x00, 0x50, 0x04, 0x00, 0x00, 0x20, 0x03, 0x00, 0x00,
+                 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00, 0x00, 0x02, 0x24, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x01,
+                 0x18, 0x00, 0x00, 0x01, 0x41, 0x40, 0x02, 0x33, 0xb6, 0x80, 0x01, 0x9c, 0x04,
+                 0x00, 0x08, 0xfa, 0x02, 0x08, 0x05, 0x00, 0x01, 0x0c, 0x27, 0x83, 0xa2, 0x2a,
+                 0x00, 0x04, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                 0x00, 0x00, 0x00}; //{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x07, 0x40, 0x00, 0x00, 0x02, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x0f, 0xb3, 0x00, 0x00, 0xd0, 0x4e, 0x00, 0x00, 0x79, 0x8c, 0x00, 0x00, 0x1c, 0x19, 0x00, 0x01, 0x8a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x02, 0x08, 0x00, 0x80, 0x00, 0x00, 0x01, 0x00, 0x01, 0x8e, 0x30, 0x00, 0x00, 0x04, 0x10, 0x00, 0x00, 0x0c, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x20, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t imp_mask_inv[] = {
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x03, 0xc0, 0x00,
+    0x00, 0x07, 0xe0, 0x00, 0x00, 0x07, 0xe0, 0x00, 0x00, 0x03, 0xe0, 0x00, 0x01, 0x07, 0xf1, 0x80,
+    0x00, 0xdf, 0xfe, 0x00, 0x00, 0x3f, 0xfe, 0x00, 0x00, 0x7f, 0xff, 0x00, 0x01, 0xff, 0xff, 0x80,
+    0x00, 0xff, 0xff, 0x80, 0x01, 0xff, 0xff, 0x80, 0x03, 0xcf, 0xf1, 0xc0, 0x01, 0xc7, 0xf1, 0xc0,
+    0x01, 0x87, 0xf1, 0xc0, 0x03, 0x0f, 0xf9, 0x80, 0x03, 0x0f, 0xfb, 0x80, 0x01, 0x8f, 0xff, 0x80,
+    0x03, 0x9f, 0x79, 0x00, 0x00, 0x1f, 0x7c, 0x00, 0x00, 0x0f, 0x78, 0x00, 0x00, 0x0f, 0x78, 0x00,
+    0x00, 0x07, 0x30, 0x00, 0x00, 0x07, 0x38, 0x00, 0x00, 0x07, 0x30, 0x00, 0x00, 0x07, 0x30, 0x00,
+    0x00, 0x03, 0x78, 0x00, 0x00, 0x07, 0x30, 0x00, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x07, 0xc0, 0x00, 0x00, 0x07, 0xe0, 0x00,
+    0x00, 0x07, 0xc0, 0x00, 0x01, 0x07, 0xe1, 0x00, 0x00, 0x8f, 0xfa, 0x00, 0x00, 0xff, 0xfe, 0x00,
+    0x00, 0x3f, 0xfe, 0x00, 0x01, 0x7f, 0xff, 0x80, 0x00, 0xff, 0xff, 0x00, 0x01, 0xff, 0xff, 0x80,
+    0x03, 0xcf, 0xfb, 0xc0, 0x03, 0x87, 0xf1, 0xc0, 0x03, 0xcf, 0xf3, 0xc0, 0x01, 0xcf, 0xf1, 0x80,
+    0x00, 0xcf, 0xf1, 0x00, 0x00, 0x0f, 0xfb, 0x80, 0x00, 0x1e, 0x78, 0x00, 0x00, 0x0e, 0x78, 0x00,
+    0x00, 0x1e, 0x78, 0x00, 0x00, 0x0f, 0x70, 0x00, 0x00, 0x0f, 0x78, 0x00, 0x00, 0x07, 0x70, 0x00,
+    0x00, 0x07, 0x70, 0x00, 0x00, 0x07, 0x38, 0x00, 0x00, 0x03, 0x30, 0x00, 0x00, 0x03, 0x20, 0x00,
+    0x00, 0x07, 0x30, 0x00, 0x00, 0x05, 0x70, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x1f, 0x00,
+    0x00, 0x00, 0x1f, 0x00, 0x00, 0x03, 0x3f, 0x80, 0x00, 0x01, 0x3f, 0x00, 0x00, 0x01, 0xff, 0x30,
+    0x00, 0x03, 0xff, 0xc0, 0x00, 0x03, 0xff, 0xc0, 0x00, 0x03, 0xff, 0x80, 0x00, 0x07, 0xff, 0xe0,
+    0x00, 0x07, 0xff, 0xc0, 0x00, 0x05, 0xff, 0xe0, 0x00, 0x00, 0xfc, 0xe0, 0x00, 0x01, 0xfc, 0xe0,
+    0x00, 0x01, 0xfc, 0x70, 0x00, 0x03, 0xfc, 0x38, 0x00, 0x03, 0xfe, 0x70, 0x00, 0x07, 0xfc, 0x00,
+    0x00, 0x07, 0x9e, 0x00, 0x00, 0x0f, 0xbc, 0x00, 0x00, 0x0f, 0x3e, 0x00, 0x00, 0x07, 0x9c, 0x00,
+    0x00, 0x03, 0x9c, 0x00, 0x00, 0x03, 0xb8, 0x00, 0x00, 0x03, 0x98, 0x00, 0x00, 0x01, 0x98, 0x00,
+    0x00, 0x02, 0x1c, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x1f, 0x00,
+    0x00, 0x00, 0x1f, 0x40, 0x00, 0x00, 0x3e, 0x80, 0x00, 0x01, 0xff, 0x80, 0x00, 0x03, 0xff, 0x80,
+    0x00, 0x07, 0xff, 0xe0, 0x00, 0x0e, 0xff, 0xc0, 0x00, 0x0c, 0xff, 0x80, 0x00, 0x1f, 0xfe, 0x00,
+    0x00, 0x13, 0xfc, 0x00, 0x00, 0x07, 0xfe, 0x00, 0x00, 0x1f, 0xff, 0x00, 0x00, 0x3f, 0x9f, 0x00,
+    0x00, 0x3e, 0x0f, 0x00, 0x00, 0x7c, 0x0f, 0x00, 0x00, 0x78, 0x0f, 0x00, 0x00, 0x78, 0x07, 0x80,
+    0x00, 0x78, 0x07, 0x40, 0x00, 0x38, 0x07, 0x80, 0x00, 0x30, 0x07, 0x00, 0x00, 0x30, 0x01, 0x00,
+    0x01, 0xf0, 0x00, 0x00, 0x01, 0xb0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1c, 0x00,
+    0x00, 0x01, 0x3e, 0x00, 0x00, 0x03, 0xff, 0x00, 0x00, 0x0f, 0xff, 0xe0, 0x01, 0x3f, 0xff, 0xc0,
+    0x01, 0xff, 0xff, 0xc0, 0x19, 0xff, 0xff, 0xe8, 0x7f, 0xff, 0xff, 0xfe, 0x3f, 0xff, 0xff, 0xfe,
+    0x1f, 0xc2, 0x07, 0xe0, 0x1f, 0x00, 0x01, 0xe0, 0x0e, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00,
+}; //{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x07, 0xe0, 0x00, 0x00, 0x07, 0xe0, 0x00, 0x00, 0x03, 0xe0, 0x00, 0x01, 0x07, 0xf1, 0x80, 0x00, 0xdf, 0xfe, 0x00, 0x00, 0x3f, 0xfe, 0x00, 0x00, 0x7f, 0xff, 0x00, 0x01, 0xff, 0xff, 0x80, 0x00, 0xff, 0xff, 0x80, 0x01, 0xff, 0xff, 0x80, 0x03, 0xcf, 0xf1, 0xc0, 0x01, 0xc7, 0xf1, 0xc0, 0x01, 0x87, 0xf1, 0xc0, 0x03, 0x0f, 0xf9, 0x80, 0x03, 0x0f, 0xfb, 0x80, 0x01, 0x8f, 0xff, 0x80, 0x03, 0x9f, 0x79, 0x00, 0x00, 0x1f, 0x7c, 0x00, 0x00, 0x0f, 0x78, 0x00, 0x00, 0x0f, 0x78, 0x00, 0x00, 0x07, 0x30, 0x00, 0x00, 0x07, 0x38, 0x00, 0x00, 0x07, 0x30, 0x00, 0x00, 0x07, 0x30, 0x00, 0x00, 0x03, 0x78, 0x00, 0x00, 0x07, 0x30, 0x00, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00};
+const uint8_t fireball[] = {0x00, 0x00, 0x01, 0x40, 0x0a, 0xb0, 0x0e, 0xd0, 0x00, 0x68, 0x53,
+                            0xb4, 0x0f, 0x48, 0x27, 0x78, 0x17, 0xa8, 0x27, 0xf0, 0x21, 0xd6,
+                            0x02, 0xf8, 0x20, 0x48, 0x06, 0x20, 0x01, 0x00, 0x00, 0x00};
+const uint8_t fireball_mask[] = {0x1f, 0x40, 0x0f, 0xf0, 0x3f, 0xf8, 0x1f, 0xfc, 0x7f, 0xfd, 0x7f,
+                                 0xfc, 0x7f, 0xfd, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
+                                 0xff, 0xfe, 0x3f, 0xfe, 0x17, 0xf8, 0x07, 0xf4, 0x01, 0xe0};
+const uint8_t item[] = {0x1f, 0xf8, 0x3f, 0xfc, 0x7f, 0xfe, 0x7f, 0xfe, 0x77, 0xee, 0x3f,
+                        0xfc, 0x5f, 0xfa, 0x2f, 0xf6, 0x53, 0xcc, 0x3e, 0x7e, 0x5e, 0x7c,
+                        0x38, 0x1e, 0x58, 0x1c, 0x3e, 0x7e, 0x5e, 0x7e, 0x2e, 0xfc, 0x00,
+                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xfc,
+                        0x17, 0xfc, 0x22, 0x6c, 0x36, 0x44, 0x3f, 0xfc, 0x1f, 0xfc, 0x2b,
+                        0xfc, 0x05, 0x54, 0x02, 0xa8, 0x00, 0x00, 0x00, 0x00};
+const uint8_t item_mask[] = {0x1f, 0xf8, 0x3f, 0xfc, 0x7f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfe, 0x7f,
+                             0xfe, 0x7f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfe,
+                             0x7f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfe, 0x7f, 0xfe, 0x3f, 0xfc, 0x00,
+                             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xfc,
+                             0x1f, 0xfc, 0x3f, 0xfc, 0x3f, 0xfc, 0x3f, 0xfc, 0x3f, 0xfc, 0x3f,
+                             0xfc, 0x07, 0xfc, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x00};
+
+//const uint8_t door[] = {0xff, 0xff, 0xff, 0xff,0xb2, 0xbd, 0xcd, 0x5b,0x9a, 0xf4, 0x6d, 0x71,0xff, 0xff, 0xff, 0xff,0x00, 0x00, 0x00, 0x00,0xbf, 0xff, 0xff, 0xfd,0x3f, 0x00, 0xfe, 0xfc,0x3e, 0x00, 0xc6, 0xfc,0xbc, 0xaa, 0xfe, 0xbd,0x39, 0x54, 0xc6, 0xbc,0x32, 0x8e, 0xfe, 0xac,0xb5, 0xfe, 0xc6, 0xad,0x3f, 0xe0, 0xfe, 0xac,0x31, 0xe0, 0xc6, 0xac,0xb3, 0xf4, 0xfe, 0xad,0x3f, 0xe8, 0xc6, 0xac,0x3c, 0xf4, 0xd6, 0xac,0xb8, 0xff, 0xfe, 0xad,0x34, 0xc7, 0xfe, 0xfc,0x38, 0xd6, 0x0e, 0x0c,0xb0, 0xd6, 0x4e, 0x0d,0x3f, 0xd6, 0xaf, 0x5c,0x30, 0x47, 0xff, 0xac,0xb7, 0x57, 0xff, 0xfd,0x3f, 0xc6, 0x0e, 0x0c,0x35, 0x56, 0x40, 0x4c,0xb5, 0x46, 0xaa, 0xad,0x35, 0x56, 0x55, 0x4c,0xff, 0xff, 0xff, 0xff,0xb0, 0x1f, 0xf8, 0x0d,0xd9, 0x30, 0x0c, 0x9b,0xff, 0xe0, 0x07, 0xff};
+const uint8_t door[] = {
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x07, 0xe1, 0x8c, 0x00, 0x04,
+    0x00, 0x7c, 0x03, 0x18, 0x60, 0x08, 0x00, 0x3e, 0x0f, 0xf7, 0xdf, 0x00, 0x1f, 0x00, 0xfe, 0x0f,
+    0xbe, 0xf8, 0x3e, 0x00, 0x3f, 0x1f, 0xff, 0xdf, 0x00, 0x1f, 0x81, 0xff, 0x0f, 0xff, 0xf8, 0x7e,
+    0x00, 0x3f, 0x8f, 0xff, 0xdf, 0x00, 0xff, 0xf9, 0xff, 0x1f, 0xff, 0xf8, 0xff, 0x80, 0x3f, 0xc7,
+    0xff, 0xcc, 0x07, 0xff, 0xfc, 0xff, 0x1f, 0xff, 0xe3, 0xff, 0x80, 0x3f, 0xc7, 0xff, 0xc0, 0x07,
+    0xff, 0xfc, 0x7f, 0x0f, 0xfe, 0x03, 0xff, 0xc0, 0x3f, 0xc3, 0xf7, 0xc0, 0x07, 0xdf, 0xf8, 0x3e,
+    0x0f, 0xbe, 0x01, 0xff, 0x80, 0x1f, 0x80, 0xe3, 0x80, 0x07, 0x8f, 0xf8, 0x1e, 0x07, 0x1c, 0x01,
+    0xff, 0x80, 0x3f, 0xc1, 0xff, 0xc0, 0x0f, 0xff, 0xfc, 0x3f, 0x0f, 0xbe, 0x03, 0xff, 0xc0, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xff, 0x80, 0x00,
+    0x7f, 0xff, 0xff, 0xc0, 0x00, 0x00, 0xe0, 0x00, 0x1f, 0xf0, 0xff, 0x00, 0x00, 0x7f, 0xff, 0xff,
+    0xc0, 0x00, 0x00, 0xe0, 0x00, 0x0f, 0xf0, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x01,
+    0xe0, 0x00, 0x0f, 0xf0, 0xff, 0x00, 0x01, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x01, 0xf0, 0x00, 0x0f,
+    0xf0, 0xff, 0x00, 0x03, 0xff, 0xff, 0xff, 0xe0, 0x7f, 0x81, 0xf0, 0x00, 0x0f, 0xf0, 0xff, 0x00,
+    0x07, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xc1, 0xf0, 0x00, 0x0f, 0xf0, 0xff, 0x00, 0x0f, 0xff, 0xff,
+    0xff, 0xe1, 0xff, 0xe1, 0xf0, 0x00, 0x0f, 0xf0, 0xff, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xe0, 0xff,
+    0xc1, 0xf3, 0x00, 0x0f, 0xf0, 0xff, 0x00, 0x3f, 0xff, 0xff, 0xff, 0xe0, 0xff, 0x81, 0xff, 0xc0,
+    0x0f, 0xf0, 0xff, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xe0, 0x3f, 0x01, 0xff, 0xc0, 0x0f, 0xf0, 0xff,
+    0x00, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xe0, 0x0f, 0xf0, 0xff, 0x01, 0xff, 0xff,
+    0xff, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xe0, 0x0f, 0xf0, 0xff, 0x03, 0xff, 0xff, 0xff, 0xff, 0xe1,
+    0xff, 0xe1, 0xff, 0xe0, 0x0f, 0xf0, 0xff, 0x07, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xc1, 0xff,
+    0xf0, 0x0f, 0xf0, 0xff, 0x0f, 0xff, 0xff, 0xff, 0x8f, 0xe0, 0xff, 0x81, 0xff, 0xff, 0x0f, 0xf0,
+    0xff, 0x1f, 0xff, 0xff, 0xfe, 0x07, 0xe0, 0x7f, 0x81, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff,
+    0xff, 0xfc, 0x07, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff, 0x8f, 0xfc, 0x03,
+    0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff, 0x07, 0xfc, 0x07, 0xe0, 0xff, 0xc1,
+    0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xfe, 0x00, 0x7f, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f,
+    0xf0, 0xff, 0x0f, 0x9c, 0x00, 0x3f, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x07,
+    0xfc, 0x00, 0x7f, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x07, 0xfc, 0x00, 0x7f,
+    0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x0f, 0xfc, 0x00, 0x7f, 0xff, 0xe0, 0xff,
+    0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x0f, 0xfc, 0x00, 0x7f, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff,
+    0x8f, 0xf0, 0xff, 0x1f, 0xfe, 0x00, 0x7f, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff,
+    0x1f, 0xfc, 0x00, 0x3f, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xfc, 0x00,
+    0x3f, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xf0, 0x00, 0x1f, 0xff, 0xe0,
+    0x7f, 0x81, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x0f, 0xf0, 0x00, 0x1f, 0xff, 0xe0, 0xff, 0x81, 0xff,
+    0xff, 0x8f, 0xf0, 0xff, 0x07, 0xe0, 0x00, 0x3f, 0xff, 0xe0, 0xff, 0xc1, 0xff, 0xff, 0x8f, 0xf0,
+    0xff, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xe1, 0xff, 0xe1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x00, 0x1f,
+    0x80, 0x3f, 0xff, 0xe1, 0xff, 0xe1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x00, 0x3f, 0xc0, 0x1f, 0xff,
+    0xe1, 0xff, 0xe1, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x00, 0x7f, 0xc0, 0x0f, 0xff, 0xe1, 0xff, 0xe1,
+    0xff, 0xff, 0x8f, 0xf0, 0xff, 0x00, 0xff, 0xc0, 0x07, 0xff, 0xe1, 0xff, 0xe1, 0xff, 0xff, 0x8f,
+    0xf0, 0xff, 0x01, 0xff, 0xc0, 0x03, 0x8f, 0xc0, 0xc1, 0x81, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x03,
+    0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x07, 0xff, 0xc0, 0xff,
+    0x80, 0x00, 0x00, 0x01, 0xff, 0xff, 0x0f, 0xf0, 0xff, 0x0f, 0xff, 0xc1, 0xff, 0x80, 0x00, 0x00,
+    0x01, 0xf3, 0x8e, 0x0f, 0xf0, 0xff, 0x0f, 0xff, 0xc3, 0xff, 0xc0, 0x00, 0x00, 0x01, 0xff, 0x9c,
+    0x0f, 0xf0, 0xff, 0x0f, 0xff, 0xc3, 0xff, 0xc0, 0xff, 0xfc, 0x01, 0xff, 0xfe, 0x0f, 0xf0, 0xff,
+    0x0f, 0xff, 0xc3, 0xff, 0xc1, 0xff, 0xfe, 0x01, 0xff, 0xff, 0x0f, 0xf0, 0xff, 0x07, 0xff, 0xc3,
+    0xff, 0xc3, 0xff, 0xff, 0x01, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x0f, 0xff, 0xc3, 0xff, 0xc3, 0xff,
+    0xff, 0x01, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x0f, 0xff, 0xc3, 0xff, 0xc3, 0xff, 0xff, 0x01, 0xff,
+    0xff, 0x8f, 0xf0, 0xff, 0x0f, 0xff, 0xc3, 0xff, 0xc3, 0xff, 0xff, 0x01, 0xff, 0xff, 0x8f, 0xf0,
+    0xff, 0x0f, 0xff, 0xc3, 0xff, 0xc3, 0xff, 0xff, 0x01, 0xff, 0xff, 0x0f, 0xf0, 0xff, 0x0f, 0xff,
+    0xc3, 0xff, 0xc3, 0xff, 0xff, 0x00, 0xff, 0xff, 0x0f, 0xf0, 0xff, 0x0f, 0xff, 0xc3, 0xff, 0xc3,
+    0xff, 0xff, 0x00, 0xff, 0xff, 0x0f, 0xf0, 0xff, 0x07, 0xff, 0xe3, 0xff, 0xc3, 0xff, 0xff, 0x00,
+    0x3f, 0xfe, 0x0f, 0xf0, 0xff, 0x07, 0xff, 0xf3, 0xff, 0xc1, 0xef, 0xfe, 0x00, 0x3f, 0xfe, 0x0f,
+    0xf0, 0xff, 0x0f, 0xff, 0xff, 0xff, 0xc0, 0x82, 0x00, 0x00, 0x1f, 0xff, 0x0f, 0xf0, 0xff, 0x1f,
+    0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x07, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff, 0xff, 0xff,
+    0xc0, 0x00, 0x00, 0x00, 0x07, 0xff, 0x0f, 0xf0, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00,
+    0x00, 0x03, 0x8e, 0x0f, 0xf0, 0xff, 0x1f, 0xc1, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x03, 0x88,
+    0x0f, 0xf0, 0xff, 0x0f, 0x80, 0xff, 0xff, 0xc1, 0xff, 0xfc, 0x00, 0xff, 0xfe, 0x0f, 0xf0, 0xff,
+    0x06, 0x00, 0x73, 0xff, 0xc3, 0xff, 0xfe, 0x01, 0xff, 0xff, 0x0f, 0xf0, 0xff, 0x00, 0x00, 0x03,
+    0xff, 0xc3, 0xff, 0xff, 0x83, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x07, 0x0c, 0x73, 0xff, 0xc3, 0xff,
+    0xff, 0xff, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x0f, 0xfe, 0xff, 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff,
+    0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0x8f, 0xf0,
+    0xff, 0x1f, 0xff, 0xff, 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff,
+    0xff, 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xc3,
+    0xff, 0xff, 0xff, 0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xc3, 0xff, 0xff, 0xff,
+    0xff, 0xff, 0x8f, 0xf0, 0xff, 0x1f, 0xff, 0xff, 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0x8f,
+    0xf0, 0xfe, 0x1f, 0xff, 0xff, 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0x87, 0xf0, 0xfe, 0x1f,
+    0xfe, 0xfb, 0xff, 0xc3, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0xf0, 0xfc, 0x0f, 0x9e, 0x73, 0xff,
+    0x81, 0xf9, 0xf7, 0xe7, 0x9c, 0xff, 0x03, 0xf0, 0xfc, 0x07, 0xfe, 0xfb, 0xc0, 0x00, 0xf0, 0x00,
+    0x6f, 0xbe, 0xfe, 0x03, 0xf0, 0x3c, 0x07, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xfe,
+    0x03, 0xc0, 0x1c, 0x0f, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xff, 0x03, 0x80, 0x1e,
+    0x0f, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0x07, 0x80, 0x3f, 0x0f, 0xff, 0xff,
+    0xe0, 0xff, 0xff, 0xf0, 0x7f, 0xff, 0xff, 0x0f, 0xc0, 0x1f, 0x8f, 0xff, 0xff, 0xe7, 0xff, 0xff,
+    0xfe, 0x7f, 0xff, 0xff, 0x1f, 0x80, 0x1f, 0xc7, 0xff, 0xff, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff,
+    0xfe, 0x3f, 0x80, 0x07, 0xc3, 0xff, 0xff, 0x9f, 0xff, 0xff, 0xff, 0x9f, 0xff, 0xfc, 0x3e, 0x00,
+    0x07, 0xc1, 0xfe, 0xff, 0x3f, 0xff, 0xff, 0xff, 0xcf, 0xf7, 0xf8, 0x3e, 0x00, 0x01, 0x00, 0xfc,
+    0x7e, 0x7f, 0xff, 0xff, 0xff, 0xe7, 0xe3, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff,
+    0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xe0,
+    0x00, 0x00, 0x00, 0x00};

+ 108 - 0
main_apps_sources/doom/assets.h

@@ -0,0 +1,108 @@
+#pragma once
+#include <gui/icon.h>
+
+#ifndef _sprites_h
+#define _sprites_h
+
+#define bmp_font_width 24 // in bytes
+#define bmp_font_height 6
+#define bmp_font_width_pxs 192
+#define bmp_font_height_pxs 48
+#define CHAR_MAP " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,-_(){}[]#"
+#define CHAR_WIDTH 4
+#define CHAR_HEIGHT 6
+
+#define BMP_GUN_WIDTH 32
+#define BMP_GUN_HEIGHT 32
+
+#define BMP_FIRE_WIDTH 24
+#define BMP_FIRE_HEIGHT 20
+
+#define BMP_IMP_WIDTH 32
+#define BMP_IMP_HEIGHT 32
+#define BMP_IMP_COUNT 5
+
+#define BMP_FIREBALL_WIDTH 16
+#define BMP_FIREBALL_HEIGHT 16
+
+#define BMP_DOOR_WIDTH 100
+#define BMP_DOOR_HEIGHT 100
+
+#define BMP_ITEMS_WIDTH 16
+#define BMP_ITEMS_HEIGHT 16
+#define BMP_ITEMS_COUNT 2
+
+#define BMP_LOGO_WIDTH 128
+#define BMP_LOGO_HEIGHT 64
+
+#define GRADIENT_WIDTH 2
+#define GRADIENT_HEIGHT 8
+#define GRADIENT_COUNT 8
+#define GRADIENT_WHITE 7
+#define GRADIENT_BLACK 0
+
+// Fonts
+extern const uint8_t zero[];
+extern const uint8_t one[];
+extern const uint8_t two[];
+extern const uint8_t three[];
+extern const uint8_t four[];
+extern const uint8_t five[];
+extern const uint8_t six[];
+extern const uint8_t seven[];
+extern const uint8_t eight[];
+extern const uint8_t nine[];
+extern const uint8_t A[];
+extern const uint8_t B[];
+extern const uint8_t C[];
+extern const uint8_t D[];
+extern const uint8_t E[];
+extern const uint8_t F[];
+extern const uint8_t G[];
+extern const uint8_t H[];
+extern const uint8_t I[];
+extern const uint8_t J[];
+extern const uint8_t K[];
+extern const uint8_t L[];
+extern const uint8_t M[];
+extern const uint8_t N[];
+extern const uint8_t O[];
+extern const uint8_t P[];
+extern const uint8_t Q[];
+extern const uint8_t R[];
+extern const uint8_t S[];
+extern const uint8_t T[];
+extern const uint8_t U[];
+extern const uint8_t V[];
+extern const uint8_t W[];
+extern const uint8_t X[];
+extern const uint8_t Y[];
+extern const uint8_t Z[];
+extern const uint8_t dot[];
+extern const uint8_t comma[];
+extern const uint8_t dash[];
+extern const uint8_t underscore[];
+extern const uint8_t bracket_open[];
+extern const uint8_t bracket_close[];
+extern const uint8_t cross_left[];
+extern const uint8_t cross_right[];
+extern const uint8_t pacman_left[];
+extern const uint8_t pacman_right[];
+extern const uint8_t box[];
+extern const uint8_t* char_arr[48];
+extern const uint8_t gradient[];
+//extern const uint8_t gun[]
+//extern const uint8_t gun_mask[]
+extern const uint8_t gun[];
+extern const uint8_t gun_mask[];
+
+extern const uint8_t imp_inv[];
+extern const uint8_t imp_mask_inv[];
+extern const uint8_t fireball[];
+extern const uint8_t fireball_mask[];
+extern const uint8_t item[];
+extern const uint8_t item_mask[];
+
+extern const uint8_t door[];
+
+#endif

BIN
main_apps_sources/doom/assets/door2.png


BIN
main_apps_sources/doom/assets/door_inv.png


BIN
main_apps_sources/doom/assets/fire_inv.png


BIN
main_apps_sources/doom/assets/fireball_inv.png


BIN
main_apps_sources/doom/assets/fireball_mask_inv.png


BIN
main_apps_sources/doom/assets/gradient_inv.png


BIN
main_apps_sources/doom/assets/gun_inv.png


BIN
main_apps_sources/doom/assets/gun_mask_inv.png


BIN
main_apps_sources/doom/assets/imp_inv.png


BIN
main_apps_sources/doom/assets/imp_mask_inv.png


BIN
main_apps_sources/doom/assets/item_inv.png


BIN
main_apps_sources/doom/assets/item_mask_inv.png


BIN
main_apps_sources/doom/assets/logo_inv.png


+ 91 - 0
main_apps_sources/doom/constants.h

@@ -0,0 +1,91 @@
+#ifndef _constants_h
+#define _constants_h
+#define PB_CONSTEXPR constexpr
+
+#define PI 3.14159265358979323846
+
+// Key pinout
+#define USE_INPUT_PULLUP
+#define K_LEFT 6
+#define K_RIGHT 7
+#define K_UP 8
+#define K_DOWN 3
+#define K_FIRE 10
+
+// SNES Controller
+// uncomment following line to enable snes controller support
+// #define SNES_CONTROLLER
+const uint8_t DATA_CLOCK = 11;
+const uint8_t DATA_LATCH = 12;
+const uint8_t DATA_SERIAL = 13;
+
+// Sound
+const uint8_t SOUND_PIN = 9; // do not change, belongs to used timer
+
+// GFX settings
+#define OPTIMIZE_SSD1306 // Optimizations for SSD1366 displays
+
+#define FRAME_TIME 66.666666 // Desired time per frame in ms (66.666666 is ~15 fps)
+#define RES_DIVIDER 2
+
+/* Higher values will result in lower horizontal resolution when rasterize and lower process and memory usage
+ Lower will require more process and memory, but looks nicer
+ */
+#define Z_RES_DIVIDER 2 // Zbuffer resolution divider. We sacrifice resolution to save memory
+#define DISTANCE_MULTIPLIER 20
+
+/* Distances are stored as uint8_t, multiplying the distance we can obtain more precision taking care 
+ of keep numbers inside the type range. Max is 256 / MAX_RENDER_DEPTH 
+ */
+
+#define MAX_RENDER_DEPTH 12
+#define MAX_SPRITE_DEPTH 8
+
+#define ZBUFFER_SIZE SCREEN_WIDTH / Z_RES_DIVIDER
+
+// Level
+#define LEVEL_WIDTH_BASE 6
+#define LEVEL_WIDTH (1 << LEVEL_WIDTH_BASE)
+#define LEVEL_HEIGHT 57
+#define LEVEL_SIZE LEVEL_WIDTH / 2 * LEVEL_HEIGHT
+
+// scenes
+#define INTRO 0
+#define GAME_PLAY 1
+
+// Game
+#define GUN_TARGET_POS 18
+#define GUN_SHOT_POS GUN_TARGET_POS + 4
+
+#define ROT_SPEED .12
+#define MOV_SPEED .2
+#define MOV_SPEED_INV 5 // 1 / MOV_SPEED
+
+#define JOGGING_SPEED .005
+#define ENEMY_SPEED .02
+#define FIREBALL_SPEED .2
+#define FIREBALL_ANGLES 45 // Num of angles per PI
+
+#define MAX_ENTITIES 10 // Max num of active entities
+#define MAX_STATIC_ENTITIES 28 // Max num of entities in sleep mode
+
+#define MAX_ENTITY_DISTANCE 200 // * DISTANCE_MULTIPLIER
+#define MAX_ENEMY_VIEW 80 // * DISTANCE_MULTIPLIER
+#define ITEM_COLLIDER_DIST 6 // * DISTANCE_MULTIPLIER
+#define ENEMY_COLLIDER_DIST 4 // * DISTANCE_MULTIPLIER
+#define FIREBALL_COLLIDER_DIST 2 // * DISTANCE_MULTIPLIER
+#define ENEMY_MELEE_DIST 6 // * DISTANCE_MULTIPLIER
+#define WALL_COLLIDER_DIST .2
+
+#define ENEMY_MELEE_DAMAGE 8
+#define ENEMY_FIREBALL_DAMAGE 20
+#define GUN_MAX_DAMAGE 20
+
+// display
+const uint8_t SCREEN_WIDTH = 128;
+const uint8_t SCREEN_HEIGHT = 64;
+const uint8_t HALF_WIDTH = SCREEN_WIDTH / 2;
+const uint8_t RENDER_HEIGHT = 56; // raycaster working height (the rest is for the hud)
+const uint8_t HALF_HEIGHT = SCREEN_HEIGHT / 2;
+
+#endif

+ 280 - 0
main_apps_sources/doom/display.h

@@ -0,0 +1,280 @@
+#include <gui/gui.h>
+#include <furi_hal.h>
+#include "constants.h"
+#include <doom_icons.h>
+#include "assets.h"
+
+#define CHECK_BIT(var, pos) ((var) & (1 << (pos)))
+
+static const uint8_t bit_mask[8] = {128, 64, 32, 16, 8, 4, 2, 1};
+
+#define pgm_read_byte(addr) (*(const unsigned char*)(addr))
+#define read_bit(b, n) b& pgm_read_byte(bit_mask + n) ? 1 : 0
+//#define read_bit(byte, index) (((unsigned)(byte) >> (index)) & 1)
+
+void drawVLine(uint8_t x, int8_t start_y, int8_t end_y, uint8_t intensity, Canvas* const canvas);
+void drawPixel(int8_t x, int8_t y, bool color, bool raycasterViewport, Canvas* const canvas);
+void drawSprite(
+    int8_t x,
+    int8_t y,
+    const uint8_t* bitmap,
+    const uint8_t* bitmap_mask,
+    int16_t w,
+    int16_t h,
+    uint8_t sprite,
+    double distance,
+    Canvas* const canvas);
+void drawBitmap(
+    int16_t x,
+    int16_t y,
+    const Icon* i,
+    int16_t w,
+    int16_t h,
+    uint16_t color,
+    Canvas* const canvas);
+void drawTextSpace(int8_t x, int8_t y, char* txt, uint8_t space, Canvas* const canvas);
+void drawChar(int8_t x, int8_t y, char ch, Canvas* const canvas);
+void clearRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h, Canvas* const canvas);
+void drawGun(
+    int16_t x,
+    int16_t y,
+    const uint8_t* bitmap,
+    int16_t w,
+    int16_t h,
+    uint16_t color,
+    Canvas* const canvas);
+void drawRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h, Canvas* const canvas);
+void drawText(uint8_t x, uint8_t y, uint8_t num, Canvas* const canvas);
+void fadeScreen(uint8_t intensity, bool color, Canvas* const canvas);
+bool getGradientPixel(uint8_t x, uint8_t y, uint8_t i);
+double getActualFps();
+void fps();
+uint8_t reverse_bits(uint8_t num);
+
+// FPS control
+double delta = 1;
+uint32_t lastFrameTime = 0;
+uint8_t zbuffer[128]; /// 128 = screen width & REMOVE WHEN DISPLAY.H IMPLEMENTED
+
+void drawGun(
+    int16_t x,
+    int16_t y,
+    const uint8_t* bitmap,
+    int16_t w,
+    int16_t h,
+    uint16_t color,
+    Canvas* const canvas) {
+    int16_t byteWidth = (w + 7) / 8;
+    uint8_t byte = 0;
+    for(int16_t j = 0; j < h; j++, y++) {
+        for(int16_t i = 0; i < w; i++) {
+            if(i & 7)
+                byte <<= 1;
+            else
+                byte = pgm_read_byte(&bitmap[j * byteWidth + i / 8]);
+            if(byte & 0x80) drawPixel(x + i, y, color, false, canvas);
+        }
+    }
+}
+
+void drawVLine(uint8_t x, int8_t start_y, int8_t end_y, uint8_t intensity, Canvas* const canvas) {
+    UNUSED(intensity);
+    uint8_t dots = end_y - start_y;
+    for(int i = 0; i < dots; i++) {
+        canvas_draw_dot(canvas, x, start_y + i);
+    }
+}
+
+void drawBitmap(
+    int16_t x,
+    int16_t y,
+    const Icon* i,
+    int16_t w,
+    int16_t h,
+    uint16_t color,
+    Canvas* const canvas) {
+    UNUSED(w);
+    UNUSED(h);
+    if(!color) {
+        canvas_invert_color(canvas);
+    }
+    canvas_draw_icon(canvas, x, y, i);
+    if(!color) {
+        canvas_invert_color(canvas);
+    }
+}
+
+void drawText(uint8_t x, uint8_t y, uint8_t num, Canvas* const canvas) {
+    char buf[4];
+    snprintf(buf, 4, "%d", num);
+    drawTextSpace(x, y, buf, 1, canvas);
+}
+
+void drawTextSpace(int8_t x, int8_t y, char* txt, uint8_t space, Canvas* const canvas) {
+    uint8_t pos = x;
+    uint8_t i = 0;
+    char ch;
+    while((ch = txt[i]) != '\0') {
+        drawChar(pos, y, ch, canvas);
+        i++;
+        pos += CHAR_WIDTH + space;
+
+        // shortcut on end of screen
+        if(pos > SCREEN_WIDTH) return;
+    }
+}
+
+// Custom drawBitmap method with scale support, mask, zindex and pattern filling
+void drawSprite(
+    int8_t x,
+    int8_t y,
+    const uint8_t* bitmap,
+    const uint8_t* bitmap_mask,
+    int16_t w,
+    int16_t h,
+    uint8_t sprite,
+    double distance,
+    Canvas* const canvas) {
+    uint8_t tw = (double)w / distance;
+    uint8_t th = (double)h / distance;
+    uint8_t byte_width = w / 8;
+    uint8_t pixel_size = fmax(1, (double)1.0 / (double)distance);
+    uint16_t sprite_offset = byte_width * h * sprite;
+
+    bool pixel;
+    bool maskPixel;
+
+    // Don't draw the whole sprite if the anchor is hidden by z buffer
+    // Not checked per pixel for performance reasons
+    if(zbuffer[(int)(fmin(fmax(x, 0), ZBUFFER_SIZE - 1) / Z_RES_DIVIDER)] <
+       distance * DISTANCE_MULTIPLIER) {
+        return;
+    }
+
+    for(uint8_t ty = 0; ty < th; ty += pixel_size) {
+        // Don't draw out of screen
+        if(y + ty < 0 || y + ty >= RENDER_HEIGHT) {
+            continue;
+        }
+
+        uint8_t sy = ty * distance; // The y from the sprite
+
+        for(uint8_t tx = 0; tx < tw; tx += pixel_size) {
+            uint8_t sx = tx * distance; // The x from the sprite
+            uint16_t byte_offset = sprite_offset + sy * byte_width + sx / 8;
+
+            // Don't draw out of screen
+            if(x + tx < 0 || x + tx >= SCREEN_WIDTH) {
+                continue;
+            }
+
+            maskPixel = read_bit(pgm_read_byte(bitmap_mask + byte_offset), sx % 8);
+
+            if(maskPixel) {
+                pixel = read_bit(pgm_read_byte(bitmap + byte_offset), sx % 8);
+                for(uint8_t ox = 0; ox < pixel_size; ox++) {
+                    for(uint8_t oy = 0; oy < pixel_size; oy++) {
+                        if(bitmap == imp_inv)
+                            drawPixel(x + tx + ox, y + ty + oy, 1, true, canvas);
+                        else
+                            drawPixel(x + tx + ox, y + ty + oy, pixel, true, canvas);
+                    }
+                }
+            }
+        }
+    }
+}
+
+void drawPixel(int8_t x, int8_t y, bool color, bool raycasterViewport, Canvas* const canvas) {
+    if(x < 0 || x >= SCREEN_WIDTH || y < 0 ||
+       y >= (raycasterViewport ? RENDER_HEIGHT : SCREEN_HEIGHT)) {
+        return;
+    }
+    if(color)
+        canvas_draw_dot(canvas, x, y);
+    else {
+        canvas_invert_color(canvas);
+        canvas_draw_dot(canvas, x, y);
+        canvas_invert_color(canvas);
+    }
+}
+
+void drawChar(int8_t x, int8_t y, char ch, Canvas* const canvas) {
+    uint8_t lsb;
+    uint8_t c = 0;
+    while(CHAR_MAP[c] != ch && CHAR_MAP[c] != '\0') c++;
+    for(uint8_t i = 0; i < 6; i++) {
+        //lsb = (char_arr[c][i] >> 4);
+        lsb = reverse_bits(char_arr[c][i]);
+        for(uint8_t n = 0; n < 4; n++) {
+            if(CHECK_BIT(lsb, n)) {
+                drawPixel(x + n, y + i, true, false, canvas);
+            }
+        }
+    }
+}
+
+void clearRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h, Canvas* const canvas) {
+    canvas_invert_color(canvas);
+
+    for(int i = 0; i < w; i++) {
+        for(int j = 0; j < h; j++) {
+            canvas_draw_dot(canvas, x + i, y + j);
+        }
+    }
+
+    canvas_invert_color(canvas);
+}
+
+void drawRect(uint8_t x, uint8_t y, uint8_t w, uint8_t h, Canvas* const canvas) {
+    for(int i = 0; i < w; i++) {
+        for(int j = 0; j < h; j++) {
+            canvas_draw_dot(canvas, x + i, y + j);
+        }
+    }
+}
+
+bool getGradientPixel(uint8_t x, uint8_t y, uint8_t i) {
+    if(i == 0) return 0;
+    if(i >= GRADIENT_COUNT - 1) return 1;
+
+    uint8_t index =
+        fmax(0, fmin(GRADIENT_COUNT - 1, i)) * GRADIENT_WIDTH * GRADIENT_HEIGHT // gradient index
+        + y * GRADIENT_WIDTH % (GRADIENT_WIDTH * GRADIENT_HEIGHT) // y byte offset
+        + x / GRADIENT_HEIGHT % GRADIENT_WIDTH; // x byte offset
+    //uint8_t *gradient_data = NULL;
+    //furi_hal_compress_icon_decode(icon_get_data(&I_gradient_inv), &gradient_data);
+    // return the bit based on x
+    return read_bit(pgm_read_byte(gradient + index), x % 8);
+}
+
+void fadeScreen(uint8_t intensity, bool color, Canvas* const canvas) {
+    for(uint8_t x = 0; x < SCREEN_WIDTH; x++) {
+        for(uint8_t y = 0; y < SCREEN_HEIGHT; y++) {
+            if(getGradientPixel(x, y, intensity)) drawPixel(x, y, color, false, canvas);
+        }
+    }
+}
+
+// Adds a delay to limit play to specified fps
+// Calculates also delta to keep movement consistent in lower framerates
+void fps() {
+    while(furi_get_tick() - lastFrameTime < FRAME_TIME)
+        ;
+    delta = (double)(furi_get_tick() - lastFrameTime) / (double)FRAME_TIME;
+    lastFrameTime = furi_get_tick();
+}
+
+double getActualFps() {
+    return 1000 / ((double)FRAME_TIME * (double)delta);
+}
+
+uint8_t reverse_bits(uint8_t num) {
+    unsigned int NO_OF_BITS = sizeof(num) * 8;
+    uint8_t reverse_num = 0;
+    uint8_t i;
+    for(i = 0; i < NO_OF_BITS; i++) {
+        if((num & (1 << i))) reverse_num |= 1 << ((NO_OF_BITS - 1) - i);
+    }
+    return reverse_num;
+}

+ 1104 - 0
main_apps_sources/doom/doom.c

@@ -0,0 +1,1104 @@
+#include <furi.h>
+#include <gui/gui.h>
+#include <input/input.h>
+#include <stdlib.h>
+#include <math.h>
+#include <sys/time.h>
+#include "sound.h"
+#include "display.h"
+#include "assets.h"
+#include "constants.h"
+#include "entities.h"
+#include "types.h"
+#include "level.h"
+#include <notification/notification.h>
+#include <notification/notification_messages.h>
+#include <dolphin/dolphin.h>
+
+#define SOUND
+
+// Useful macros
+#define swap(a, b)          \
+    do {                    \
+        typeof(a) temp = a; \
+        a = b;              \
+        b = temp;           \
+    } while(0)
+#define sign(a, b) (double)(a > b ? 1 : (b > a ? -1 : 0))
+#define pgm_read_byte(addr) (*(const unsigned char*)(addr))
+
+typedef enum {
+    EventTypeTick,
+    EventTypeKey,
+} EventType;
+
+typedef struct {
+    EventType type;
+    InputEvent input;
+} PluginEvent;
+
+typedef struct {
+    FuriMutex* mutex;
+    Player player;
+    Entity entity[MAX_ENTITIES];
+    StaticEntity static_entity[MAX_STATIC_ENTITIES];
+    uint8_t num_entities;
+    uint8_t num_static_entities;
+
+    uint8_t scene;
+    uint8_t gun_pos;
+    double jogging;
+    double view_height;
+    bool init;
+
+    bool up;
+    bool down;
+    bool left;
+    bool right;
+    bool fired;
+    bool gun_fired;
+
+    double rot_speed;
+    double old_dir_x;
+    double old_plane_x;
+    NotificationApp* notify;
+#ifdef SOUND
+    MusicPlayer* music_instance;
+    bool intro_sound;
+#endif
+} PluginState;
+
+static const NotificationSequence sequence_short_sound = {
+    &message_note_c5,
+    &message_delay_50,
+    &message_sound_off,
+    NULL,
+};
+static const NotificationSequence sequence_long_sound = {
+    &message_note_c3,
+    &message_delay_100,
+    &message_sound_off,
+    NULL,
+};
+
+Coords translateIntoView(Coords* pos, PluginState* const plugin_state);
+void updateHud(Canvas* const canvas, PluginState* const plugin_state);
+// general
+
+bool invert_screen = false;
+uint8_t flash_screen = 0;
+
+// game
+// player and entities
+
+uint8_t getBlockAt(const uint8_t level[], uint8_t x, uint8_t y) {
+    if(x >= LEVEL_WIDTH || y >= LEVEL_HEIGHT) {
+        return E_FLOOR;
+    }
+
+    // y is read in inverse order
+    return pgm_read_byte(level + (((LEVEL_HEIGHT - 1 - y) * LEVEL_WIDTH + x) / 2)) >>
+               (!(x % 2) * 4) // displace part of wanted bits
+           & 0b1111; // mask wanted bits
+}
+
+// Finds the player in the map
+void initializeLevel(const uint8_t level[], PluginState* const plugin_state) {
+    for(uint8_t y = LEVEL_HEIGHT - 1; y > 0; y--) {
+        for(uint8_t x = 0; x < LEVEL_WIDTH; x++) {
+            uint8_t block = getBlockAt(level, x, y);
+
+            if(block == E_PLAYER) {
+                plugin_state->player = create_player(x, y);
+                return;
+            }
+
+            // todo create other static entities
+        }
+    }
+}
+
+bool isSpawned(UID uid, PluginState* const plugin_state) {
+    for(uint8_t i = 0; i < plugin_state->num_entities; i++) {
+        if(plugin_state->entity[i].uid == uid) return true;
+    }
+
+    return false;
+}
+
+bool isStatic(UID uid, PluginState* const plugin_state) {
+    for(uint8_t i = 0; i < plugin_state->num_static_entities; i++) {
+        if(plugin_state->static_entity[i].uid == uid) return true;
+    }
+
+    return false;
+}
+
+void spawnEntity(uint8_t type, uint8_t x, uint8_t y, PluginState* const plugin_state) {
+    // Limit the number of spawned entities
+    if(plugin_state->num_entities >= MAX_ENTITIES) {
+        return;
+    }
+
+    // todo: read static entity status
+
+    switch(type) {
+    case E_ENEMY:
+        plugin_state->entity[plugin_state->num_entities] = create_enemy(x, y);
+        plugin_state->num_entities++;
+        break;
+
+    case E_KEY:
+        plugin_state->entity[plugin_state->num_entities] = create_key(x, y);
+        plugin_state->num_entities++;
+        break;
+
+    case E_MEDIKIT:
+        plugin_state->entity[plugin_state->num_entities] = create_medikit(x, y);
+        plugin_state->num_entities++;
+        break;
+    }
+}
+
+void spawnFireball(double x, double y, PluginState* const plugin_state) {
+    // Limit the number of spawned entities
+    if(plugin_state->num_entities >= MAX_ENTITIES) {
+        return;
+    }
+
+    UID uid = create_uid(E_FIREBALL, x, y);
+    // Remove if already exists, don't throw anything. Not the best, but shouldn't happen too often
+    if(isSpawned(uid, plugin_state)) return;
+
+    // Calculate direction. 32 angles
+    int16_t dir =
+        FIREBALL_ANGLES + atan2(y - plugin_state->player.pos.y, x - plugin_state->player.pos.x) /
+                              (double)PI * FIREBALL_ANGLES;
+    if(dir < 0) dir += FIREBALL_ANGLES * 2;
+    plugin_state->entity[plugin_state->num_entities] = create_fireball(x, y, dir);
+    plugin_state->num_entities++;
+}
+
+void removeEntity(UID uid, PluginState* const plugin_state) {
+    uint8_t i = 0;
+    bool found = false;
+
+    while(i < plugin_state->num_entities) {
+        if(!found && plugin_state->entity[i].uid == uid) {
+            // todo: doze it
+            found = true;
+            plugin_state->num_entities--;
+        }
+
+        // displace entities
+        if(found) {
+            plugin_state->entity[i] = plugin_state->entity[i + 1];
+        }
+
+        i++;
+    }
+}
+
+void removeStaticEntity(UID uid, PluginState* const plugin_state) {
+    uint8_t i = 0;
+    bool found = false;
+
+    while(i < plugin_state->num_static_entities) {
+        if(!found && plugin_state->static_entity[i].uid == uid) {
+            found = true;
+            plugin_state->num_static_entities--;
+        }
+
+        // displace entities
+        if(found) {
+            plugin_state->static_entity[i] = plugin_state->static_entity[i + 1];
+        }
+
+        i++;
+    }
+}
+
+UID detectCollision(
+    const uint8_t level[],
+    Coords* pos,
+    double relative_x,
+    double relative_y,
+    bool only_walls,
+    PluginState* const plugin_state) {
+    // Wall collision
+    uint8_t round_x = (int)(pos->x + relative_x);
+    uint8_t round_y = (int)(pos->y + relative_y);
+    uint8_t block = getBlockAt(level, round_x, round_y);
+
+    if(block == E_WALL) {
+        // playSound(hit_wall_snd, HIT_WALL_SND_LEN);
+        return create_uid(block, round_x, round_y);
+    }
+
+    if(only_walls) {
+        return UID_null;
+    }
+
+    // Entity collision
+    for(uint8_t i = 0; i < plugin_state->num_entities; i++) {
+        // Don't collide with itself
+        if(&(plugin_state->entity[i].pos) == pos) {
+            continue;
+        }
+
+        uint8_t type = uid_get_type(plugin_state->entity[i].uid);
+
+        // Only ALIVE enemy collision
+        if(type != E_ENEMY || plugin_state->entity[i].state == S_DEAD ||
+           plugin_state->entity[i].state == S_HIDDEN) {
+            continue;
+        }
+
+        Coords new_coords = {
+            plugin_state->entity[i].pos.x - relative_x,
+            plugin_state->entity[i].pos.y - relative_y};
+        uint8_t distance = coords_distance(pos, &new_coords);
+
+        // Check distance and if it's getting closer
+        if(distance < ENEMY_COLLIDER_DIST && distance < plugin_state->entity[i].distance) {
+            return plugin_state->entity[i].uid;
+        }
+    }
+
+    return UID_null;
+}
+
+// Shoot
+void fire(PluginState* const plugin_state) {
+    //playSound(shoot_snd, SHOOT_SND_LEN);
+
+    for(uint8_t i = 0; i < plugin_state->num_entities; i++) {
+        // Shoot only ALIVE enemies
+        if(uid_get_type(plugin_state->entity[i].uid) != E_ENEMY ||
+           plugin_state->entity[i].state == S_DEAD || plugin_state->entity[i].state == S_HIDDEN) {
+            continue;
+        }
+
+        Coords transform = translateIntoView(&(plugin_state->entity[i].pos), plugin_state);
+        if(fabs(transform.x) < 20 && transform.y > 0) {
+            uint8_t damage = (double)fmin(
+                GUN_MAX_DAMAGE,
+                GUN_MAX_DAMAGE / (fabs(transform.x) * plugin_state->entity[i].distance) / 5);
+            if(damage > 0) {
+                plugin_state->entity[i].health = fmax(0, plugin_state->entity[i].health - damage);
+                plugin_state->entity[i].state = S_HIT;
+                plugin_state->entity[i].timer = 4;
+            }
+        }
+    }
+}
+
+UID updatePosition(
+    const uint8_t level[],
+    Coords* pos,
+    double relative_x,
+    double relative_y,
+    bool only_walls,
+    PluginState* const plugin_state) {
+    UID collide_x = detectCollision(level, pos, relative_x, 0, only_walls, plugin_state);
+    UID collide_y = detectCollision(level, pos, 0, relative_y, only_walls, plugin_state);
+
+    if(!collide_x) pos->x += relative_x;
+    if(!collide_y) pos->y += relative_y;
+
+    return collide_x || collide_y || UID_null;
+}
+
+void updateEntities(const uint8_t level[], Canvas* const canvas, PluginState* const plugin_state) {
+    uint8_t i = 0;
+    while(i < plugin_state->num_entities) {
+        // update distance
+        plugin_state->entity[i].distance =
+            coords_distance(&(plugin_state->player.pos), &(plugin_state->entity[i].pos));
+
+        // Run the timer. Works with actual frames.
+        // Todo: use delta here. But needs double type and more memory
+        if(plugin_state->entity[i].timer > 0) plugin_state->entity[i].timer--;
+
+        // too far away. put it in doze mode
+        if(plugin_state->entity[i].distance > MAX_ENTITY_DISTANCE) {
+            removeEntity(plugin_state->entity[i].uid, plugin_state);
+            // don't increase 'i', since current one has been removed
+            continue;
+        }
+
+        // bypass render if hidden
+        if(plugin_state->entity[i].state == S_HIDDEN) {
+            i++;
+            continue;
+        }
+
+        uint8_t type = uid_get_type(plugin_state->entity[i].uid);
+
+        switch(type) {
+        case E_ENEMY: {
+            // Enemy "IA"
+            if(plugin_state->entity[i].health == 0) {
+                if(plugin_state->entity[i].state != S_DEAD) {
+                    plugin_state->entity[i].state = S_DEAD;
+                    plugin_state->entity[i].timer = 6;
+                }
+            } else if(plugin_state->entity[i].state == S_HIT) {
+                if(plugin_state->entity[i].timer == 0) {
+                    // Back to alert state
+                    plugin_state->entity[i].state = S_ALERT;
+                    plugin_state->entity[i].timer = 40; // delay next fireball thrown
+                }
+            } else if(plugin_state->entity[i].state == S_FIRING) {
+                if(plugin_state->entity[i].timer == 0) {
+                    // Back to alert state
+                    plugin_state->entity[i].state = S_ALERT;
+                    plugin_state->entity[i].timer = 40; // delay next fireball throwm
+                }
+            } else {
+                // ALERT STATE
+                if(plugin_state->entity[i].distance > ENEMY_MELEE_DIST &&
+                   plugin_state->entity[i].distance < MAX_ENEMY_VIEW) {
+                    if(plugin_state->entity[i].state != S_ALERT) {
+                        plugin_state->entity[i].state = S_ALERT;
+                        plugin_state->entity[i].timer = 20; // used to throw fireballs
+                    } else {
+                        if(plugin_state->entity[i].timer == 0) {
+                            // Throw a fireball
+                            spawnFireball(
+                                plugin_state->entity[i].pos.x,
+                                plugin_state->entity[i].pos.y,
+                                plugin_state);
+                            plugin_state->entity[i].state = S_FIRING;
+                            plugin_state->entity[i].timer = 6;
+                        } else {
+                            // move towards to the player.
+                            updatePosition(
+                                level,
+                                &(plugin_state->entity[i].pos),
+                                sign(plugin_state->player.pos.x, plugin_state->entity[i].pos.x) *
+                                    (double)ENEMY_SPEED * 1, // NOT SURE (delta)
+                                sign(plugin_state->player.pos.y, plugin_state->entity[i].pos.y) *
+                                    (double)ENEMY_SPEED * 1, // NOT SURE (delta)
+                                true,
+                                plugin_state);
+                        }
+                    }
+                } else if(plugin_state->entity[i].distance <= ENEMY_MELEE_DIST) {
+                    if(plugin_state->entity[i].state != S_MELEE) {
+                        // Preparing the melee attack
+                        plugin_state->entity[i].state = S_MELEE;
+                        plugin_state->entity[i].timer = 10;
+                    } else if(plugin_state->entity[i].timer == 0) {
+                        // Melee attack
+                        plugin_state->player.health =
+                            fmax(0, plugin_state->player.health - ENEMY_MELEE_DAMAGE);
+                        plugin_state->entity[i].timer = 14;
+                        flash_screen = 1;
+                        updateHud(canvas, plugin_state);
+                    }
+                } else {
+                    // stand
+                    plugin_state->entity[i].state = S_STAND;
+                }
+            }
+            break;
+        }
+
+        case E_FIREBALL: {
+            if(plugin_state->entity[i].distance < FIREBALL_COLLIDER_DIST) {
+                // Hit the player and disappear
+                plugin_state->player.health =
+                    fmax(0, plugin_state->player.health - ENEMY_FIREBALL_DAMAGE);
+                flash_screen = 1;
+                updateHud(canvas, plugin_state);
+                removeEntity(plugin_state->entity[i].uid, plugin_state);
+                continue; // continue in the loop
+            } else {
+                // Move. Only collide with walls.
+                // Note: using health to store the angle of the movement
+                UID collided = updatePosition(
+                    level,
+                    &(plugin_state->entity[i].pos),
+                    cos((double)plugin_state->entity[i].health / FIREBALL_ANGLES * (double)PI) *
+                        (double)FIREBALL_SPEED,
+                    sin((double)plugin_state->entity[i].health / FIREBALL_ANGLES * (double)PI) *
+                        (double)FIREBALL_SPEED,
+                    true,
+                    plugin_state);
+
+                if(collided) {
+                    removeEntity(plugin_state->entity[i].uid, plugin_state);
+                    continue; // continue in the entity check loop
+                }
+            }
+            break;
+        }
+
+        case E_MEDIKIT: {
+            if(plugin_state->entity[i].distance < ITEM_COLLIDER_DIST) {
+                // pickup
+                notification_message(plugin_state->notify, &sequence_long_sound);
+                //playSound(medkit_snd, MEDKIT_SND_LEN);
+                plugin_state->entity[i].state = S_HIDDEN;
+                plugin_state->player.health = fmin(100, plugin_state->player.health + 50);
+                updateHud(canvas, plugin_state);
+                flash_screen = 1;
+            }
+            break;
+        }
+
+        case E_KEY: {
+            if(plugin_state->entity[i].distance < ITEM_COLLIDER_DIST) {
+                // pickup
+                notification_message(plugin_state->notify, &sequence_long_sound);
+                //playSound(get_key_snd, GET_KEY_SND_LEN);
+                plugin_state->entity[i].state = S_HIDDEN;
+                plugin_state->player.keys++;
+                updateHud(canvas, plugin_state);
+                flash_screen = 1;
+            }
+            break;
+        }
+        }
+
+        i++;
+    }
+}
+
+// The map raycaster. Based on https://lodev.org/cgtutor/raycasting.html
+void renderMap(
+    const uint8_t level[],
+    double view_height,
+    Canvas* const canvas,
+    PluginState* const plugin_state) {
+    UID last_uid = 0; // NOT SURE ?
+
+    for(uint8_t x = 0; x < SCREEN_WIDTH; x += RES_DIVIDER) {
+        double camera_x = 2 * (double)x / SCREEN_WIDTH - 1;
+        double ray_x = plugin_state->player.dir.x + plugin_state->player.plane.x * camera_x;
+        double ray_y = plugin_state->player.dir.y + plugin_state->player.plane.y * camera_x;
+        uint8_t map_x = (uint8_t)plugin_state->player.pos.x;
+        uint8_t map_y = (uint8_t)plugin_state->player.pos.y;
+        Coords map_coords = {plugin_state->player.pos.x, plugin_state->player.pos.y};
+        double delta_x = fabs(1 / ray_x);
+        double delta_y = fabs(1 / ray_y);
+
+        int8_t step_x;
+        int8_t step_y;
+        double side_x;
+        double side_y;
+
+        if(ray_x < 0) {
+            step_x = -1;
+            side_x = (plugin_state->player.pos.x - map_x) * delta_x;
+        } else {
+            step_x = 1;
+            side_x = (map_x + (double)1.0 - plugin_state->player.pos.x) * delta_x;
+        }
+
+        if(ray_y < 0) {
+            step_y = -1;
+            side_y = (plugin_state->player.pos.y - map_y) * delta_y;
+        } else {
+            step_y = 1;
+            side_y = (map_y + (double)1.0 - plugin_state->player.pos.y) * delta_y;
+        }
+
+        // Wall detection
+        uint8_t depth = 0;
+        bool hit = 0;
+        bool side;
+        while(!hit && depth < MAX_RENDER_DEPTH) {
+            if(side_x < side_y) {
+                side_x += delta_x;
+                map_x += step_x;
+                side = 0;
+            } else {
+                side_y += delta_y;
+                map_y += step_y;
+                side = 1;
+            }
+
+            uint8_t block = getBlockAt(level, map_x, map_y);
+
+            if(block == E_WALL) {
+                hit = 1;
+            } else {
+                // Spawning entities here, as soon they are visible for the
+                // player. Not the best place, but would be a very performance
+                // cost scan for them in another loop
+                if(block == E_ENEMY || (block & 0b00001000) /* all collectable items */) {
+                    // Check that it's close to the player
+                    if(coords_distance(&(plugin_state->player.pos), &map_coords) <
+                       MAX_ENTITY_DISTANCE) {
+                        UID uid = create_uid(block, map_x, map_y);
+                        if(last_uid != uid && !isSpawned(uid, plugin_state)) {
+                            spawnEntity(block, map_x, map_y, plugin_state);
+                            last_uid = uid;
+                        }
+                    }
+                }
+            }
+
+            depth++;
+        }
+
+        if(hit) {
+            double distance;
+
+            if(side == 0) {
+                distance =
+                    fmax(1, (map_x - plugin_state->player.pos.x + (1 - step_x) / 2) / ray_x);
+            } else {
+                distance =
+                    fmax(1, (map_y - plugin_state->player.pos.y + (1 - step_y) / 2) / ray_y);
+            }
+
+            // store zbuffer value for the column
+            zbuffer[x / Z_RES_DIVIDER] = fmin(distance * DISTANCE_MULTIPLIER, 255);
+
+            // rendered line height
+            uint8_t line_height = RENDER_HEIGHT / distance;
+
+            drawVLine(
+                x,
+                view_height / distance - line_height / 2 + RENDER_HEIGHT / 2,
+                view_height / distance + line_height / 2 + RENDER_HEIGHT / 2,
+                GRADIENT_COUNT - (int)distance / MAX_RENDER_DEPTH * GRADIENT_COUNT - side * 2,
+                canvas);
+        }
+    }
+}
+
+// Sort entities from far to close
+uint8_t sortEntities(PluginState* const plugin_state) {
+    uint8_t gap = plugin_state->num_entities;
+    bool swapped = false;
+    while(gap > 1 || swapped) {
+        //shrink factor 1.3
+        gap = (gap * 10) / 13;
+        if(gap == 9 || gap == 10) gap = 11;
+        if(gap < 1) gap = 1;
+        swapped = false;
+        for(uint8_t i = 0; i < plugin_state->num_entities - gap; i++) {
+            uint8_t j = i + gap;
+            if(plugin_state->entity[i].distance < plugin_state->entity[j].distance) {
+                swap(plugin_state->entity[i], plugin_state->entity[j]);
+                swapped = true;
+            }
+        }
+    }
+    return swapped;
+}
+
+Coords translateIntoView(Coords* pos, PluginState* const plugin_state) {
+    //translate sprite position to relative to camera
+    double sprite_x = pos->x - plugin_state->player.pos.x;
+    double sprite_y = pos->y - plugin_state->player.pos.y;
+
+    //required for correct matrix multiplication
+    double inv_det =
+        ((double)1.0 /
+         ((double)plugin_state->player.plane.x * (double)plugin_state->player.dir.y -
+          (double)plugin_state->player.dir.x * (double)plugin_state->player.plane.y));
+    double transform_x =
+        inv_det * (plugin_state->player.dir.y * sprite_x - plugin_state->player.dir.x * sprite_y);
+    double transform_y = inv_det * (-plugin_state->player.plane.y * sprite_x +
+                                    plugin_state->player.plane.x * sprite_y); // Z in screen
+    Coords res = {transform_x, transform_y};
+    return res;
+}
+
+void renderEntities(double view_height, Canvas* const canvas, PluginState* const plugin_state) {
+    sortEntities(plugin_state);
+
+    for(uint8_t i = 0; i < plugin_state->num_entities; i++) {
+        if(plugin_state->entity[i].state == S_HIDDEN) continue;
+
+        Coords transform = translateIntoView(&(plugin_state->entity[i].pos), plugin_state);
+
+        // don´t render if behind the player or too far away
+        if(transform.y <= (double)0.1 || transform.y > MAX_SPRITE_DEPTH) {
+            continue;
+        }
+
+        int16_t sprite_screen_x = HALF_WIDTH * ((double)1.0 + transform.x / transform.y);
+        int8_t sprite_screen_y = RENDER_HEIGHT / 2 + view_height / transform.y;
+        uint8_t type = uid_get_type(plugin_state->entity[i].uid);
+
+        // don´t try to render if outside of screen
+        // doing this pre-shortcut due int16 -> int8 conversion makes out-of-screen
+        // values fit into the screen space
+        if(sprite_screen_x < -HALF_WIDTH || sprite_screen_x > SCREEN_WIDTH + HALF_WIDTH) {
+            continue;
+        }
+
+        switch(type) {
+        case E_ENEMY: {
+            uint8_t sprite;
+            if(plugin_state->entity[i].state == S_ALERT) {
+                // walking
+                sprite = ((int)furi_get_tick() / 500) % 2;
+            } else if(plugin_state->entity[i].state == S_FIRING) {
+                // fireball
+                sprite = 2;
+            } else if(plugin_state->entity[i].state == S_HIT) {
+                // hit
+                sprite = 3;
+            } else if(plugin_state->entity[i].state == S_MELEE) {
+                // melee atack
+                sprite = plugin_state->entity[i].timer > 10 ? 2 : 1;
+            } else if(plugin_state->entity[i].state == S_DEAD) {
+                // dying
+                sprite = plugin_state->entity[i].timer > 0 ? 3 : 4;
+            } else {
+                // stand
+                sprite = 0;
+            }
+
+            drawSprite(
+                sprite_screen_x - BMP_IMP_WIDTH * (double).5 / transform.y,
+                sprite_screen_y - 8 / transform.y,
+                imp_inv,
+                imp_mask_inv,
+                BMP_IMP_WIDTH,
+                BMP_IMP_HEIGHT,
+                sprite,
+                transform.y,
+                canvas);
+            break;
+        }
+
+        case E_FIREBALL: {
+            drawSprite(
+                sprite_screen_x - BMP_FIREBALL_WIDTH / 2 / transform.y,
+                sprite_screen_y - BMP_FIREBALL_HEIGHT / 2 / transform.y,
+                fireball,
+                fireball_mask,
+                BMP_FIREBALL_WIDTH,
+                BMP_FIREBALL_HEIGHT,
+                0,
+                transform.y,
+                canvas);
+            break;
+        }
+
+        case E_MEDIKIT: {
+            drawSprite(
+                sprite_screen_x - BMP_ITEMS_WIDTH / 2 / transform.y,
+                sprite_screen_y + 5 / transform.y,
+                item,
+                item_mask,
+                BMP_ITEMS_WIDTH,
+                BMP_ITEMS_HEIGHT,
+                0,
+                transform.y,
+                canvas);
+            break;
+        }
+
+        case E_KEY: {
+            drawSprite(
+                sprite_screen_x - BMP_ITEMS_WIDTH / 2 / transform.y,
+                sprite_screen_y + 5 / transform.y,
+                item,
+                item_mask,
+                BMP_ITEMS_WIDTH,
+                BMP_ITEMS_HEIGHT,
+                1,
+                transform.y,
+                canvas);
+            break;
+        }
+        }
+    }
+}
+
+void renderGun(uint8_t gun_pos, double amount_jogging, Canvas* const canvas) {
+    // jogging
+    char x = 48 + sin((double)furi_get_tick() * (double)JOGGING_SPEED) * 10 * amount_jogging;
+    char y = RENDER_HEIGHT - gun_pos +
+             fabs(cos((double)furi_get_tick() * (double)JOGGING_SPEED)) * 8 * amount_jogging;
+
+    if(gun_pos > GUN_SHOT_POS - 2) {
+        // Gun fire
+        drawBitmap(x + 6, y - 11, &I_fire_inv, BMP_FIRE_WIDTH, BMP_FIRE_HEIGHT, 1, canvas);
+    }
+
+    // Don't draw over the hud!
+    uint8_t clip_height = fmax(0, fmin(y + BMP_GUN_HEIGHT, RENDER_HEIGHT) - y);
+
+    // Draw the gun (black mask + actual sprite).
+    drawBitmap(x, y, &I_gun_mask_inv, BMP_GUN_WIDTH, clip_height, 0, canvas);
+    drawBitmap(x, y, &I_gun_inv, BMP_GUN_WIDTH, clip_height, 1, canvas);
+    //drawGun(x,y,gun_mask, BMP_GUN_WIDTH, clip_height, 0, canvas);
+    //drawGun(x,y,gun, BMP_GUN_WIDTH, clip_height, 1, canvas);
+}
+
+// Only needed first time
+void renderHud(Canvas* const canvas, PluginState* plugin_state) {
+    drawTextSpace(2, 58, "{}", 0, canvas); // Health symbol
+    drawTextSpace(40, 58, "[]", 0, canvas); // Keys symbol
+    updateHud(canvas, plugin_state);
+}
+
+// Render values for the HUD
+void updateHud(Canvas* const canvas, PluginState* plugin_state) {
+    clearRect(12, 58, 15, 6, canvas);
+    clearRect(50, 58, 15, 6, canvas);
+    drawText(12, 58, plugin_state->player.health, canvas);
+    drawText(50, 58, plugin_state->player.keys, canvas);
+}
+
+// Debug stats
+void renderStats(Canvas* const canvas, PluginState* plugin_state) {
+    clearRect(58, 58, 70, 6, canvas);
+    drawText(114, 58, (int)getActualFps(), canvas);
+    drawText(82, 58, plugin_state->num_entities, canvas);
+    // drawText(94, 58, freeMemory());
+}
+
+// Intro screen
+void loopIntro(Canvas* const canvas) {
+    canvas_draw_icon(canvas, 0, 0, &I_logo_inv);
+    //drawTextSpace(SCREEN_WIDTH / 2 - 25, SCREEN_HEIGHT * .8, "PRESS FIRE", 1, canvas);
+}
+
+static void render_callback(Canvas* const canvas, void* ctx) {
+    furi_assert(ctx);
+    PluginState* plugin_state = ctx;
+    furi_mutex_acquire(plugin_state->mutex, FuriWaitForever);
+
+    canvas_set_font(canvas, FontPrimary);
+
+    switch(plugin_state->scene) {
+    case INTRO: {
+        loopIntro(canvas);
+        break;
+    }
+    case GAME_PLAY: {
+        updateEntities(sto_level_1, canvas, plugin_state);
+
+        renderGun(plugin_state->gun_pos, plugin_state->jogging, canvas);
+        renderMap(sto_level_1, plugin_state->view_height, canvas, plugin_state);
+
+        renderEntities(plugin_state->view_height, canvas, plugin_state);
+
+        renderHud(canvas, plugin_state);
+        updateHud(canvas, plugin_state);
+        renderStats(canvas, plugin_state);
+        break;
+    }
+    }
+    furi_mutex_release(plugin_state->mutex);
+}
+
+static void input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) {
+    furi_assert(event_queue);
+
+    PluginEvent event = {.type = EventTypeKey, .input = *input_event};
+    furi_message_queue_put(event_queue, &event, 0);
+}
+
+static void doom_state_init(PluginState* const plugin_state) {
+    plugin_state->notify = furi_record_open(RECORD_NOTIFICATION);
+    plugin_state->num_entities = 0;
+    plugin_state->num_static_entities = 0;
+
+    plugin_state->scene = INTRO;
+    plugin_state->gun_pos = 0;
+    plugin_state->view_height = 0;
+    plugin_state->init = true;
+
+    plugin_state->up = false;
+    plugin_state->down = false;
+    plugin_state->left = false;
+    plugin_state->right = false;
+    plugin_state->fired = false;
+    plugin_state->gun_fired = false;
+#ifdef SOUND
+
+    plugin_state->music_instance = malloc(sizeof(MusicPlayer));
+    plugin_state->music_instance->model = malloc(sizeof(MusicPlayerModel));
+    memset(
+        plugin_state->music_instance->model->duration_history,
+        0xff,
+        MUSIC_PLAYER_SEMITONE_HISTORY_SIZE);
+    memset(
+        plugin_state->music_instance->model->semitone_history,
+        0xff,
+        MUSIC_PLAYER_SEMITONE_HISTORY_SIZE);
+    plugin_state->music_instance->model->volume = 2;
+
+    plugin_state->music_instance->model_mutex = furi_mutex_alloc(FuriMutexTypeNormal);
+    //plugin_state->music_instance->view_port = view_port_alloc();
+
+    plugin_state->music_instance->worker = music_player_worker_alloc();
+    //music_player_worker_set_volume(plugin_state->music_instance->worker, 0.75);
+    music_player_worker_set_volume(
+        plugin_state->music_instance->worker,
+        MUSIC_PLAYER_VOLUMES[plugin_state->music_instance->model->volume]);
+    plugin_state->intro_sound = true;
+    //init_sound(plugin_state->music_instance);
+#endif
+}
+
+static void doom_game_update_timer_callback(FuriMessageQueue* event_queue) {
+    furi_assert(event_queue);
+
+    PluginEvent event = {.type = EventTypeTick};
+    furi_message_queue_put(event_queue, &event, 0);
+}
+
+static void doom_game_tick(PluginState* const plugin_state) {
+    if(plugin_state->scene == GAME_PLAY) {
+        //fps();
+        //player is alive
+        if(plugin_state->player.health > 0) {
+            if(plugin_state->up) {
+                plugin_state->player.velocity +=
+                    ((double)MOV_SPEED - plugin_state->player.velocity) * (double).4;
+                plugin_state->jogging = fabs(plugin_state->player.velocity) * MOV_SPEED_INV;
+                //plugin_state->up = false;
+            } else if(plugin_state->down) {
+                plugin_state->player.velocity +=
+                    (-(double)MOV_SPEED - plugin_state->player.velocity) * (double).4;
+                plugin_state->jogging = fabs(plugin_state->player.velocity) * MOV_SPEED_INV;
+                //plugin_state->down = false;
+            } else {
+                plugin_state->player.velocity *= (double).5;
+                plugin_state->jogging = fabs(plugin_state->player.velocity) * MOV_SPEED_INV;
+            }
+
+            if(plugin_state->right) {
+                plugin_state->rot_speed = (double)ROT_SPEED * delta;
+                plugin_state->old_dir_x = plugin_state->player.dir.x;
+                plugin_state->player.dir.x =
+                    plugin_state->player.dir.x * cos(-(plugin_state->rot_speed)) -
+                    plugin_state->player.dir.y * sin(-(plugin_state->rot_speed));
+                plugin_state->player.dir.y =
+                    plugin_state->old_dir_x * sin(-(plugin_state->rot_speed)) +
+                    plugin_state->player.dir.y * cos(-(plugin_state->rot_speed));
+                plugin_state->old_plane_x = plugin_state->player.plane.x;
+                plugin_state->player.plane.x =
+                    plugin_state->player.plane.x * cos(-(plugin_state->rot_speed)) -
+                    plugin_state->player.plane.y * sin(-(plugin_state->rot_speed));
+                plugin_state->player.plane.y =
+                    plugin_state->old_plane_x * sin(-(plugin_state->rot_speed)) +
+                    plugin_state->player.plane.y * cos(-(plugin_state->rot_speed));
+
+                //plugin_state->right = false;
+            } else if(plugin_state->left) {
+                plugin_state->rot_speed = (double)ROT_SPEED * delta;
+                plugin_state->old_dir_x = plugin_state->player.dir.x;
+                plugin_state->player.dir.x =
+                    plugin_state->player.dir.x * cos(plugin_state->rot_speed) -
+                    plugin_state->player.dir.y * sin(plugin_state->rot_speed);
+                plugin_state->player.dir.y =
+                    plugin_state->old_dir_x * sin(plugin_state->rot_speed) +
+                    plugin_state->player.dir.y * cos(plugin_state->rot_speed);
+                plugin_state->old_plane_x = plugin_state->player.plane.x;
+                plugin_state->player.plane.x =
+                    plugin_state->player.plane.x * cos(plugin_state->rot_speed) -
+                    plugin_state->player.plane.y * sin(plugin_state->rot_speed);
+                plugin_state->player.plane.y =
+                    plugin_state->old_plane_x * sin(plugin_state->rot_speed) +
+                    plugin_state->player.plane.y * cos(plugin_state->rot_speed);
+                //plugin_state->left = false;
+            }
+            plugin_state->view_height =
+                fabs(sin((double)furi_get_tick() * (double)JOGGING_SPEED)) * 6 *
+                plugin_state->jogging;
+
+            if(plugin_state->gun_pos > GUN_TARGET_POS) {
+                // Right after fire
+                plugin_state->gun_pos -= 1;
+            } else if(plugin_state->gun_pos < GUN_TARGET_POS) {
+                plugin_state->gun_pos += 2;
+            } else if(!plugin_state->gun_fired && plugin_state->fired) {
+                //furi_hal_speaker_start(20480 / 10, 0.45f);
+                /*#ifdef SOUND
+        music_player_worker_start(plugin_state->music_instance->worker);
+#endif*/
+                plugin_state->gun_pos = GUN_SHOT_POS;
+                plugin_state->gun_fired = true;
+                plugin_state->fired = false;
+                fire(plugin_state);
+
+            } else if(plugin_state->gun_fired && !plugin_state->fired) {
+                //furi_hal_speaker_stop();
+                plugin_state->gun_fired = false;
+
+                notification_message(plugin_state->notify, &sequence_short_sound);
+
+                /*#ifdef SOUND
+        music_player_worker_stop(plugin_state->music_instance->worker);
+#endif*/
+            }
+        } else {
+            // Player is dead
+            if(plugin_state->view_height > -10) plugin_state->view_height--;
+            if(plugin_state->gun_pos > 1) plugin_state->gun_pos -= 2;
+        }
+
+        if(fabs(plugin_state->player.velocity) > (double)0.003) {
+            updatePosition(
+                sto_level_1,
+                &(plugin_state->player.pos),
+                plugin_state->player.dir.x * plugin_state->player.velocity * delta,
+                plugin_state->player.dir.y * plugin_state->player.velocity * delta,
+                false,
+                plugin_state);
+        } else {
+            plugin_state->player.velocity = 0;
+        }
+    }
+}
+
+int32_t doom_app() {
+    FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent));
+    PluginState* plugin_state = malloc(sizeof(PluginState));
+    doom_state_init(plugin_state);
+    plugin_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
+    if(!plugin_state->mutex) {
+        FURI_LOG_E("Doom_game", "cannot create mutex\r\n");
+        furi_record_close(RECORD_NOTIFICATION);
+        furi_message_queue_free(event_queue);
+        free(plugin_state);
+        return 255;
+    }
+    FuriTimer* timer =
+        furi_timer_alloc(doom_game_update_timer_callback, FuriTimerTypePeriodic, event_queue);
+    furi_timer_start(timer, furi_kernel_get_tick_frequency() / 12);
+    // Set system callbacks
+    ViewPort* view_port = view_port_alloc();
+    view_port_draw_callback_set(view_port, render_callback, plugin_state);
+    view_port_input_callback_set(view_port, input_callback, event_queue);
+
+    // Open GUI and register view_port
+    Gui* gui = furi_record_open(RECORD_GUI);
+    gui_add_view_port(gui, view_port, GuiLayerFullscreen);
+
+    //////////////////////////////////
+    plugin_state->init = false;
+
+    PluginEvent event;
+#ifdef SOUND
+    music_player_worker_load_rtttl_from_string(plugin_state->music_instance->worker, dsintro);
+    music_player_worker_start(plugin_state->music_instance->worker);
+#endif
+    // Call dolphin deed on game start
+    dolphin_deed(DolphinDeedPluginGameStart);
+
+    for(bool processing = true; processing;) {
+        FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100);
+        furi_mutex_acquire(plugin_state->mutex, FuriWaitForever);
+#ifdef SOUND
+        furi_check(
+            furi_mutex_acquire(plugin_state->music_instance->model_mutex, FuriWaitForever) ==
+            FuriStatusOk);
+#endif
+        if(event_status == FuriStatusOk) {
+            // press events
+            if(event.type == EventTypeKey) {
+                if(event.input.key == InputKeyBack) {
+                    processing = false;
+#ifdef SOUND
+                    if(plugin_state->intro_sound) {
+                        furi_mutex_release(plugin_state->music_instance->model_mutex);
+                        music_player_worker_stop(plugin_state->music_instance->worker);
+                    }
+#endif
+                }
+
+                if(event.input.type == InputTypePress) {
+                    if(plugin_state->scene == INTRO && event.input.key == InputKeyOk) {
+                        plugin_state->scene = GAME_PLAY;
+                        initializeLevel(sto_level_1, plugin_state);
+#ifdef SOUND
+                        furi_mutex_release(plugin_state->music_instance->model_mutex);
+                        music_player_worker_stop(plugin_state->music_instance->worker);
+                        plugin_state->intro_sound = false;
+#endif
+                        goto skipintro;
+                    }
+
+                    //While playing game
+                    if(plugin_state->scene == GAME_PLAY) {
+                        // If the player is alive
+                        if(plugin_state->player.health > 0) {
+                            //Player speed
+                            if(event.input.key == InputKeyUp) {
+                                plugin_state->up = true;
+                            } else if(event.input.key == InputKeyDown) {
+                                plugin_state->down = true;
+                            }
+                            // Player rotation
+                            if(event.input.key == InputKeyRight) {
+                                plugin_state->right = true;
+                            } else if(event.input.key == InputKeyLeft) {
+                                plugin_state->left = true;
+                            }
+                            if(event.input.key == InputKeyOk) {
+                                /*#ifdef SOUND
+                        music_player_worker_load_rtttl_from_string(plugin_state->music_instance->worker, dspistol);
+#endif*/
+                                if(plugin_state->fired) {
+                                    plugin_state->fired = false;
+                                } else {
+                                    plugin_state->fired = true;
+                                }
+                            }
+                        } else {
+                            // Player is dead
+                            if(event.input.key == InputKeyOk) plugin_state->scene = INTRO;
+                        }
+                    }
+                }
+                if(event.input.type == InputTypeRelease) {
+                    if(plugin_state->player.health > 0) {
+                        //Player speed
+                        if(event.input.key == InputKeyUp) {
+                            plugin_state->up = false;
+                        } else if(event.input.key == InputKeyDown) {
+                            plugin_state->down = false;
+                        }
+                        // Player rotation
+                        if(event.input.key == InputKeyRight) {
+                            plugin_state->right = false;
+                        } else if(event.input.key == InputKeyLeft) {
+                            plugin_state->left = false;
+                        }
+                    }
+                }
+            }
+
+        skipintro:
+            if(event.type == EventTypeTick) {
+                doom_game_tick(plugin_state);
+            }
+        }
+#ifdef SOUND
+        furi_mutex_release(plugin_state->music_instance->model_mutex);
+#endif
+        view_port_update(view_port);
+        furi_mutex_release(plugin_state->mutex);
+    }
+#ifdef SOUND
+    music_player_worker_free(plugin_state->music_instance->worker);
+    furi_mutex_free(plugin_state->music_instance->model_mutex);
+    free(plugin_state->music_instance->model);
+    free(plugin_state->music_instance);
+#endif
+    furi_record_close(RECORD_NOTIFICATION);
+    furi_timer_free(timer);
+    view_port_enabled_set(view_port, false);
+    gui_remove_view_port(gui, view_port);
+    furi_record_close(RECORD_GUI);
+    view_port_free(view_port);
+    furi_mutex_free(plugin_state->mutex);
+    furi_message_queue_free(event_queue);
+    free(plugin_state);
+    return 0;
+}

BIN
main_apps_sources/doom/doom_10px.png


+ 504 - 0
main_apps_sources/doom/doom_music_player_worker.c

@@ -0,0 +1,504 @@
+#include "doom_music_player_worker.h"
+
+#include <furi_hal.h>
+#include <furi.h>
+
+#include <storage/storage.h>
+#include <lib/flipper_format/flipper_format.h>
+
+#include <m-array.h>
+
+#define TAG "MusicPlayerWorker"
+
+#define MUSIC_PLAYER_FILETYPE "Flipper Music Format"
+#define MUSIC_PLAYER_VERSION 0
+
+#define SEMITONE_PAUSE 0xFF
+
+#define NOTE_C4 261.63f
+#define NOTE_C4_SEMITONE (4.0f * 12.0f)
+#define TWO_POW_TWELTH_ROOT 1.059463094359f
+
+typedef struct {
+    uint8_t semitone;
+    uint8_t duration;
+    uint8_t dots;
+} NoteBlock;
+
+ARRAY_DEF(NoteBlockArray, NoteBlock, M_POD_OPLIST);
+
+struct MusicPlayerWorker {
+    FuriThread* thread;
+    bool should_work;
+
+    MusicPlayerWorkerCallback callback;
+    void* callback_context;
+
+    float volume;
+    uint32_t bpm;
+    uint32_t duration;
+    uint32_t octave;
+    NoteBlockArray_t notes;
+};
+
+static int32_t music_player_worker_thread_callback(void* context) {
+    furi_assert(context);
+    MusicPlayerWorker* instance = context;
+
+    NoteBlockArray_it_t it;
+    NoteBlockArray_it(it, instance->notes);
+    if(furi_hal_speaker_acquire(1000)) {
+        while(instance->should_work) {
+            if(NoteBlockArray_end_p(it)) {
+                NoteBlockArray_it(it, instance->notes);
+                furi_delay_ms(10);
+            } else {
+                NoteBlock* note_block = NoteBlockArray_ref(it);
+
+                float note_from_a4 = (float)note_block->semitone - NOTE_C4_SEMITONE;
+                float frequency = NOTE_C4 * powf(TWO_POW_TWELTH_ROOT, note_from_a4);
+                float duration = 60.0 * furi_kernel_get_tick_frequency() * 4 / instance->bpm /
+                                 note_block->duration;
+                uint32_t dots = note_block->dots;
+                while(dots > 0) {
+                    duration += duration / 2;
+                    dots--;
+                }
+                uint32_t next_tick = furi_get_tick() + duration;
+                float volume = instance->volume;
+
+                if(instance->callback) {
+                    instance->callback(
+                        note_block->semitone,
+                        note_block->dots,
+                        note_block->duration,
+                        0.0,
+                        instance->callback_context);
+                }
+
+                furi_hal_speaker_stop();
+                furi_hal_speaker_start(frequency, volume);
+                while(instance->should_work && furi_get_tick() < next_tick) {
+                    volume *= 0.9945679;
+                    furi_hal_speaker_set_volume(volume);
+                    furi_delay_ms(2);
+                }
+                NoteBlockArray_next(it);
+            }
+        }
+
+        furi_hal_speaker_stop();
+        furi_hal_speaker_release();
+    } else {
+        FURI_LOG_E(TAG, "Speaker system is busy with another process.");
+    }
+
+    return 0;
+}
+
+MusicPlayerWorker* music_player_worker_alloc() {
+    MusicPlayerWorker* instance = malloc(sizeof(MusicPlayerWorker));
+
+    NoteBlockArray_init(instance->notes);
+
+    instance->thread = furi_thread_alloc();
+    furi_thread_set_name(instance->thread, "MusicPlayerWorker");
+    furi_thread_set_stack_size(instance->thread, 1024);
+    furi_thread_set_context(instance->thread, instance);
+    furi_thread_set_callback(instance->thread, music_player_worker_thread_callback);
+
+    instance->volume = 1.0f;
+
+    return instance;
+}
+
+void music_player_worker_free(MusicPlayerWorker* instance) {
+    furi_assert(instance);
+    furi_thread_free(instance->thread);
+    NoteBlockArray_clear(instance->notes);
+    free(instance);
+}
+
+static bool is_digit(const char c) {
+    return isdigit(c) != 0;
+}
+
+static bool is_letter(const char c) {
+    return islower(c) != 0 || isupper(c) != 0;
+}
+
+static bool is_space(const char c) {
+    return c == ' ' || c == '\t';
+}
+
+static size_t extract_number(const char* string, uint32_t* number) {
+    size_t ret = 0;
+    while(is_digit(*string)) {
+        *number *= 10;
+        *number += (*string - '0');
+        string++;
+        ret++;
+    }
+    return ret;
+}
+
+static size_t extract_dots(const char* string, uint32_t* number) {
+    size_t ret = 0;
+    while(*string == '.') {
+        *number += 1;
+        string++;
+        ret++;
+    }
+    return ret;
+}
+
+static size_t extract_char(const char* string, char* symbol) {
+    if(is_letter(*string)) {
+        *symbol = *string;
+        return 1;
+    } else {
+        return 0;
+    }
+}
+
+static size_t extract_sharp(const char* string, char* symbol) {
+    if(*string == '#' || *string == '_') {
+        *symbol = '#';
+        return 1;
+    } else {
+        return 0;
+    }
+}
+
+static size_t skip_till(const char* string, const char symbol) {
+    size_t ret = 0;
+    while(*string != '\0' && *string != symbol) {
+        string++;
+        ret++;
+    }
+    if(*string != symbol) {
+        ret = 0;
+    }
+    return ret;
+}
+
+static bool music_player_worker_add_note(
+    MusicPlayerWorker* instance,
+    uint8_t semitone,
+    uint8_t duration,
+    uint8_t dots) {
+    NoteBlock note_block;
+
+    note_block.semitone = semitone;
+    note_block.duration = duration;
+    note_block.dots = dots;
+
+    NoteBlockArray_push_back(instance->notes, note_block);
+
+    return true;
+}
+
+static int8_t note_to_semitone(const char note) {
+    switch(note) {
+    case 'C':
+        return 0;
+    // C#
+    case 'D':
+        return 2;
+    // D#
+    case 'E':
+        return 4;
+    case 'F':
+        return 5;
+    // F#
+    case 'G':
+        return 7;
+    // G#
+    case 'A':
+        return 9;
+    // A#
+    case 'B':
+        return 11;
+    default:
+        return 0;
+    }
+}
+
+static bool music_player_worker_parse_notes(MusicPlayerWorker* instance, const char* string) {
+    const char* cursor = string;
+    bool result = true;
+
+    while(*cursor != '\0') {
+        if(!is_space(*cursor)) {
+            uint32_t duration = 0;
+            char note_char = '\0';
+            char sharp_char = '\0';
+            uint32_t octave = 0;
+            uint32_t dots = 0;
+
+            // Parsing
+            cursor += extract_number(cursor, &duration);
+            cursor += extract_char(cursor, &note_char);
+            cursor += extract_sharp(cursor, &sharp_char);
+            cursor += extract_number(cursor, &octave);
+            cursor += extract_dots(cursor, &dots);
+
+            // Post processing
+            note_char = toupper(note_char);
+            if(!duration) {
+                duration = instance->duration;
+            }
+            if(!octave) {
+                octave = instance->octave;
+            }
+
+            // Validation
+            bool is_valid = true;
+            is_valid &= (duration >= 1 && duration <= 128);
+            is_valid &= ((note_char >= 'A' && note_char <= 'G') || note_char == 'P');
+            is_valid &= (sharp_char == '#' || sharp_char == '\0');
+            is_valid &= (octave <= 16);
+            is_valid &= (dots <= 16);
+            if(!is_valid) {
+                FURI_LOG_E(
+                    TAG,
+                    "Invalid note: %lu%c%c%lu.%lu",
+                    duration,
+                    note_char == '\0' ? '_' : note_char,
+                    sharp_char == '\0' ? '_' : sharp_char,
+                    octave,
+                    dots);
+                result = false;
+                break;
+            }
+
+            // Note to semitones
+            uint8_t semitone = 0;
+            if(note_char == 'P') {
+                semitone = SEMITONE_PAUSE;
+            } else {
+                semitone += octave * 12;
+                semitone += note_to_semitone(note_char);
+                semitone += sharp_char == '#' ? 1 : 0;
+            }
+
+            if(music_player_worker_add_note(instance, semitone, duration, dots)) {
+                FURI_LOG_D(
+                    TAG,
+                    "Added note: %c%c%lu.%lu = %u %lu",
+                    note_char == '\0' ? '_' : note_char,
+                    sharp_char == '\0' ? '_' : sharp_char,
+                    octave,
+                    dots,
+                    semitone,
+                    duration);
+            } else {
+                FURI_LOG_E(
+                    TAG,
+                    "Invalid note: %c%c%lu.%lu = %u %lu",
+                    note_char == '\0' ? '_' : note_char,
+                    sharp_char == '\0' ? '_' : sharp_char,
+                    octave,
+                    dots,
+                    semitone,
+                    duration);
+            }
+            cursor += skip_till(cursor, ',');
+        }
+
+        if(*cursor != '\0') cursor++;
+    }
+
+    return result;
+}
+
+bool music_player_worker_load(MusicPlayerWorker* instance, const char* file_path) {
+    furi_assert(instance);
+    furi_assert(file_path);
+
+    bool ret = false;
+    if(strcasestr(file_path, ".fmf")) {
+        ret = music_player_worker_load_fmf_from_file(instance, file_path);
+    } else {
+        ret = music_player_worker_load_rtttl_from_file(instance, file_path);
+    }
+    return ret;
+}
+
+bool music_player_worker_load_fmf_from_file(MusicPlayerWorker* instance, const char* file_path) {
+    furi_assert(instance);
+    furi_assert(file_path);
+
+    bool result = false;
+    FuriString* temp_str;
+    temp_str = furi_string_alloc();
+
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    FlipperFormat* file = flipper_format_file_alloc(storage);
+
+    do {
+        if(!flipper_format_file_open_existing(file, file_path)) break;
+
+        uint32_t version = 0;
+        if(!flipper_format_read_header(file, temp_str, &version)) break;
+        if(furi_string_cmp_str(temp_str, MUSIC_PLAYER_FILETYPE) ||
+           (version != MUSIC_PLAYER_VERSION)) {
+            FURI_LOG_E(TAG, "Incorrect file format or version");
+            break;
+        }
+
+        if(!flipper_format_read_uint32(file, "BPM", &instance->bpm, 1)) {
+            FURI_LOG_E(TAG, "BPM is missing");
+            break;
+        }
+        if(!flipper_format_read_uint32(file, "Duration", &instance->duration, 1)) {
+            FURI_LOG_E(TAG, "Duration is missing");
+            break;
+        }
+        if(!flipper_format_read_uint32(file, "Octave", &instance->octave, 1)) {
+            FURI_LOG_E(TAG, "Octave is missing");
+            break;
+        }
+
+        if(!flipper_format_read_string(file, "Notes", temp_str)) {
+            FURI_LOG_E(TAG, "Notes is missing");
+            break;
+        }
+
+        if(!music_player_worker_parse_notes(instance, furi_string_get_cstr(temp_str))) {
+            break;
+        }
+
+        result = true;
+    } while(false);
+
+    furi_record_close(RECORD_STORAGE);
+    flipper_format_free(file);
+    furi_string_free(temp_str);
+
+    return result;
+}
+
+bool music_player_worker_load_rtttl_from_file(MusicPlayerWorker* instance, const char* file_path) {
+    furi_assert(instance);
+    furi_assert(file_path);
+
+    bool result = false;
+    FuriString* content;
+    content = furi_string_alloc();
+    Storage* storage = furi_record_open(RECORD_STORAGE);
+    File* file = storage_file_alloc(storage);
+
+    do {
+        if(!storage_file_open(file, file_path, FSAM_READ, FSOM_OPEN_EXISTING)) {
+            FURI_LOG_E(TAG, "Unable to open file");
+            break;
+        };
+
+        uint16_t ret = 0;
+        do {
+            uint8_t buffer[65] = {0};
+            ret = storage_file_read(file, buffer, sizeof(buffer) - 1);
+            for(size_t i = 0; i < ret; i++) {
+                furi_string_push_back(content, buffer[i]);
+            }
+        } while(ret > 0);
+
+        furi_string_trim(content);
+        if(!furi_string_size(content)) {
+            FURI_LOG_E(TAG, "Empty file");
+            break;
+        }
+
+        if(!music_player_worker_load_rtttl_from_string(instance, furi_string_get_cstr(content))) {
+            FURI_LOG_E(TAG, "Invalid file content");
+            break;
+        }
+
+        result = true;
+    } while(0);
+
+    storage_file_free(file);
+    furi_record_close(RECORD_STORAGE);
+    furi_string_free(content);
+
+    return result;
+}
+
+bool music_player_worker_load_rtttl_from_string(MusicPlayerWorker* instance, const char* string) {
+    furi_assert(instance);
+
+    const char* cursor = string;
+
+    // Skip name
+    cursor += skip_till(cursor, ':');
+    if(*cursor != ':') {
+        return false;
+    }
+
+    // Duration
+    cursor += skip_till(cursor, '=');
+    if(*cursor != '=') {
+        return false;
+    }
+    cursor++;
+    cursor += extract_number(cursor, &instance->duration);
+
+    // Octave
+    cursor += skip_till(cursor, '=');
+    if(*cursor != '=') {
+        return false;
+    }
+    cursor++;
+    cursor += extract_number(cursor, &instance->octave);
+
+    // BPM
+    cursor += skip_till(cursor, '=');
+    if(*cursor != '=') {
+        return false;
+    }
+    cursor++;
+    cursor += extract_number(cursor, &instance->bpm);
+
+    // Notes
+    cursor += skip_till(cursor, ':');
+    if(*cursor != ':') {
+        return false;
+    }
+    cursor++;
+    if(!music_player_worker_parse_notes(instance, cursor)) {
+        return false;
+    }
+
+    return true;
+}
+
+void music_player_worker_set_callback(
+    MusicPlayerWorker* instance,
+    MusicPlayerWorkerCallback callback,
+    void* context) {
+    furi_assert(instance);
+    instance->callback = callback;
+    instance->callback_context = context;
+}
+
+void music_player_worker_set_volume(MusicPlayerWorker* instance, float volume) {
+    furi_assert(instance);
+    instance->volume = volume;
+}
+
+void music_player_worker_start(MusicPlayerWorker* instance) {
+    furi_assert(instance);
+    furi_assert(instance->should_work == false);
+
+    instance->should_work = true;
+    furi_thread_start(instance->thread);
+}
+
+void music_player_worker_stop(MusicPlayerWorker* instance) {
+    furi_assert(instance);
+    furi_assert(instance->should_work == true);
+
+    instance->should_work = false;
+    furi_thread_join(instance->thread);
+}

+ 44 - 0
main_apps_sources/doom/doom_music_player_worker.h

@@ -0,0 +1,44 @@
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void (*MusicPlayerWorkerCallback)(
+    uint8_t semitone,
+    uint8_t dots,
+    uint8_t duration,
+    float position,
+    void* context);
+
+typedef struct MusicPlayerWorker MusicPlayerWorker;
+
+MusicPlayerWorker* music_player_worker_alloc();
+
+void music_player_worker_free(MusicPlayerWorker* instance);
+
+bool music_player_worker_load(MusicPlayerWorker* instance, const char* file_path);
+
+bool music_player_worker_load_fmf_from_file(MusicPlayerWorker* instance, const char* file_path);
+
+bool music_player_worker_load_rtttl_from_file(MusicPlayerWorker* instance, const char* file_path);
+
+bool music_player_worker_load_rtttl_from_string(MusicPlayerWorker* instance, const char* string);
+
+void music_player_worker_set_callback(
+    MusicPlayerWorker* instance,
+    MusicPlayerWorkerCallback callback,
+    void* context);
+
+void music_player_worker_set_volume(MusicPlayerWorker* instance, float volume);
+
+void music_player_worker_start(MusicPlayerWorker* instance);
+
+void music_player_worker_stop(MusicPlayerWorker* instance);
+
+#ifdef __cplusplus
+}
+#endif

+ 42 - 0
main_apps_sources/doom/entities.c

@@ -0,0 +1,42 @@
+#include "entities.h"
+
+//extern "C"
+/*Player create_player(double x, double y){
+	return {create_coords((double) x + (double)0.5, (double) y + (double)0.5), create_coords(1, 0), create_coords(0, -0.66), 0, 100, 0};
+}*/
+
+Player create_player(double x, double y) {
+    Player p;
+    p.pos = create_coords((double)x + (double)0.5, (double)y + (double)0.5);
+    p.dir = create_coords(1, 0);
+    p.plane = create_coords(0, -0.66);
+    p.velocity = 0;
+    p.health = 100;
+    p.keys = 0;
+    return p; //{create_coords((double) x + (double)0.5, (double) y + (double)0.5), create_coords(1, 0), create_coords(0, -0.66), 0, 100, 0};
+}
+
+//extern "C"
+Entity
+    create_entity(uint8_t type, uint8_t x, uint8_t y, uint8_t initialState, uint8_t initialHealth) {
+    UID uid = create_uid(type, x, y);
+    Coords pos = create_coords((double)x + (double).5, (double)y + (double).5);
+    Entity new_entity; // = { uid, pos, initialState, initialHealth, 0, 0 };
+    new_entity.uid = uid;
+    new_entity.pos = pos;
+    new_entity.state = initialState;
+    new_entity.health = initialHealth;
+    new_entity.distance = 0;
+    new_entity.timer = 0;
+    return new_entity;
+}
+
+//extern "C"
+StaticEntity crate_static_entity(UID uid, uint8_t x, uint8_t y, bool active) {
+    StaticEntity ent;
+    ent.uid = uid;
+    ent.x = x;
+    ent.y = y;
+    ent.active = active;
+    return ent;
+}

+ 56 - 0
main_apps_sources/doom/entities.h

@@ -0,0 +1,56 @@
+#ifndef _entities_h
+#define _entities_h
+#include <stdint.h>
+#include <stdbool.h>
+#include "types.h"
+
+// Shortcuts
+//#define create_player(x, y)   {create_coords((double) x + (double)0.5, (double) y + (double)0.5), create_coords(1, 0), create_coords(0, -0.66), 0, 100}
+
+#define create_enemy(x, y) create_entity(E_ENEMY, x, y, S_STAND, 50)
+#define create_medikit(x, y) create_entity(E_MEDIKIT, x, y, S_STAND, 0)
+#define create_key(x, y) create_entity(E_KEY, x, y, S_STAND, 0)
+#define create_fireball(x, y, dir) create_entity(E_FIREBALL, x, y, S_STAND, dir)
+#define create_door(x, y) create_entity(E_DOOR, x, y, S_STAND, 0)
+
+// entity statuses
+#define S_STAND 0
+#define S_ALERT 1
+#define S_FIRING 2
+#define S_MELEE 3
+#define S_HIT 4
+#define S_DEAD 5
+#define S_HIDDEN 6
+#define S_OPEN 7
+#define S_CLOSE 8
+
+typedef struct Player {
+    Coords pos;
+    Coords dir;
+    Coords plane;
+    double velocity;
+    uint8_t health;
+    uint8_t keys;
+} Player;
+
+typedef struct Entity {
+    UID uid;
+    Coords pos;
+    uint8_t state;
+    uint8_t health; // angle for fireballs
+    uint8_t distance;
+    uint8_t timer;
+} Entity;
+
+typedef struct StaticEntity {
+    UID uid;
+    uint8_t x;
+    uint8_t y;
+    bool active;
+} StaticEntity;
+
+Entity
+    create_entity(uint8_t type, uint8_t x, uint8_t y, uint8_t initialState, uint8_t initialHealth);
+StaticEntity create_static_entity(UID uid, uint8_t x, uint8_t y, bool active);
+Player create_player(double x, double y);
+#endif

BIN
main_apps_sources/doom/img/1.png


BIN
main_apps_sources/doom/img/2.png


BIN
main_apps_sources/doom/img/3.png


+ 188 - 0
main_apps_sources/doom/level.h

@@ -0,0 +1,188 @@
+#ifndef _level_h
+#define _level_h
+
+#include "constants.h"
+
+/*
+  Based on E1M1 from Wolfenstein 3D
+
+  ################################################################
+  #############################...........########################
+  ######....###################........E..########################
+  ######....########..........#...........#...####################
+  ######.....#######..........L.....E.......M.####################
+  ######.....#######..........#...........#...####################
+  ##################...########...........########################
+  ######.........###...########...........########################
+  ######.........###...#############D#############################
+  ######.........#......E##########...############################
+  ######....E....D...E...##########...############################
+  ######.........#.......##########...############################
+  ######....E....##################...############################
+  #...##.........##################...############################
+  #.K.######D######################...############################
+  #...#####...###############...#E.....K##########################
+  ##D######...###############..####...############################
+  #...#####...###############..####...############################
+  #...#...#...###############..####...############################
+  #...D...#...#####################...############################
+  #...#...#...#####################...############################
+  #...######D#######################L#############################
+  #.E.##.........#################.....#################........##
+  #...##.........############...............############........##
+  #...##...E.....############...............############........##
+  #....#.........############...E.......E....#.........#........##
+  #....L....K....############................D....E....D....E...##
+  #....#.........############................#.........#........##
+  #...##.....E...############...............####....####........##
+  #...##.........############...............#####..#####.....M..##
+  #...##.........#################.....##########..#####........##
+  #...######L#######################D############..###############
+  #...#####...#####################...###########..###############
+  #E.E#####...#####################...###########..###############
+  #...#...#...#####################.E.###########..###############
+  #...D.M.#...#####################...###########..###############
+  #...#...#...#####################...###########..###.#.#.#.#####
+  #...#####...#####################...###########...#.........####
+  #...#####...#####################...###########...D....E..K.####
+  #................##......########...###########...#.........####
+  #....E........E...L...E...X######...################.#.#.#.#####
+  #................##......########...############################
+  #################################...############################
+  #############..#..#..#############L#############################
+  ###########....#..#.########....#...#....#######################
+  #############.....##########.P..D...D....#######################
+  ############################....#...#....#######################
+  ##############..#################...############################
+  ##############..############....#...#....#######################
+  ############################....D...D....#######################
+  ############################....#...#....#######################
+  #################################...############################
+  ############################.............#######################
+  ############################..........EK.#######################
+  ############################.............#######################
+  ################################################################
+*/
+
+/*
+   Same map above built from some regexp replacements using the legend above.
+   Using this way lets me use only 4 bit to store each block
+*/
+const uint8_t sto_level_1[LEVEL_SIZE] = {
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00,
+    0x00, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00,
+    0x00, 0x20, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xF0, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0x4F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x2F, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x02, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x20, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x90, 0xFF, 0xFF, 0xFF, 0x4F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0xF2,
+    0x00, 0x00, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0x4F, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xF0, 0x00, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0x40, 0x00, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xF0, 0x00, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0x4F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0x5F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x20, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF,
+    0xF0, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF,
+    0xF0, 0x00, 0xFF, 0x00, 0x02, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF,
+    0xF0, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x20,
+    0x00, 0x00, 0x00, 0x20, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xFF,
+    0xF0, 0x00, 0x05, 0x00, 0x00, 0x90, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x00, 0x20, 0x00, 0xFF,
+    0xF0, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xFF,
+    0xF0, 0x00, 0xFF, 0x00, 0x00, 0x02, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF,
+    0xF0, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0x00, 0x00, 0x08, 0x00, 0xFF,
+    0xF0, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0x5F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0x4F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF2, 0x02, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xF0, 0x00, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0x40, 0x80, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xF0, 0x00, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0x0F, 0x0F, 0x0F, 0x0F, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x40, 0x00, 0x02, 0x00, 0x90, 0xFF, 0xFF,
+    0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
+    0xF0, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x50, 0x00, 0x20, 0x00, 0x7F, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x0F, 0x0F, 0x0F, 0xFF, 0xFF,
+    0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0x00, 0xF0, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0x5F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x0F, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+    0xF0, 0x00, 0xF0, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00,
+    0x40, 0x00, 0x40, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+    0xF0, 0x00, 0xF0, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+    0xF0, 0x00, 0xF0, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+    0x40, 0x00, 0x40, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+    0xF0, 0x00, 0xF0, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xF0, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x29, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+};
+
+#endif

+ 34 - 0
main_apps_sources/doom/sound.h

@@ -0,0 +1,34 @@
+#ifndef sound_h
+#define sound_h
+#include <furi.h>
+#include <furi_hal.h>
+#include <stdint.h>
+#include "doom_music_player_worker.h"
+
+//static const char dspistol[] = "AnyConv:d=,o=,b=120:408,40p,40p,40p,40p,405,40p,40p,40p,405,30p.,30p.,30p.,13p";
+static const char dsintro[] =
+    "Doom:d=32,o=4,b=56:f,f,f5,f,f,d#5,f,f,c#5,f,f,b,f,f,c5,c#5,f,f,f5,f,f,d#5,f,f,c#5,f,f,8b.,f,f,f5,f,f,d#5,f,f,c#5,f,f,b,f,f,c5,c#5,f,f,f5,f,f,d#5,f,f,c#5,f,f,8b.,a#,a#,a#5,a#,a#,g#5,a#,a#,f#5,a#,a#,e5,a#,a#,f5,f#5,a#,a#,a#5,a#,a#,g#5,a#,a#,f#5,a#,a#,8e5";
+//static const char dsgetpow[] = "dsgetpow:d=,o=,b=120:407,40p,30.6,407,40p,406,40p,407,40p,40p,407,30p.,407";
+//static const char dsnoway[] = "dsnoway:d=,o=,b=120:407,30.4";
+
+#define MUSIC_PLAYER_SEMITONE_HISTORY_SIZE 4
+static const float MUSIC_PLAYER_VOLUMES[] = {0, .25, .5, .75, 1};
+
+typedef struct {
+    uint8_t semitone_history[MUSIC_PLAYER_SEMITONE_HISTORY_SIZE];
+    uint8_t duration_history[MUSIC_PLAYER_SEMITONE_HISTORY_SIZE];
+
+    uint8_t volume;
+    uint8_t semitone;
+    uint8_t dots;
+    uint8_t duration;
+    float position;
+} MusicPlayerModel;
+
+typedef struct {
+    MusicPlayerModel* model;
+    MusicPlayerWorker* worker;
+    FuriMutex** model_mutex;
+} MusicPlayer;
+
+#endif

+ 33 - 0
main_apps_sources/doom/types.c

@@ -0,0 +1,33 @@
+#include "types.h"
+
+/*template <class T>
+inline T sq(T value) {
+    return value * value;
+}*/
+
+double sq(double val) {
+    return val * val;
+}
+
+//extern "C"
+Coords create_coords(double x, double y) {
+    Coords cord;
+    cord.x = x;
+    cord.y = y;
+    return cord;
+}
+
+//extern "C"
+uint8_t coords_distance(Coords* a, Coords* b) {
+    return sqrt(sq(a->x - b->x) + sq(a->y - b->y)) * 20;
+}
+
+//extern "C"
+UID create_uid(uint8_t type, uint8_t x, uint8_t y) {
+    return ((y << 6) | x) << 4 | type;
+}
+
+//extern "C"
+uint8_t uid_get_type(UID uid) {
+    return uid & 0x0F;
+}

+ 36 - 0
main_apps_sources/doom/types.h

@@ -0,0 +1,36 @@
+#ifndef _types_h
+#define _types_h
+
+#include <stdint.h>
+#include <math.h>
+//#include "constants.h"
+
+#define UID_null 0
+
+// Entity types (legend applies to level.h)
+#define E_FLOOR 0x0 // . (also null)
+#define E_WALL 0xF // #
+#define E_PLAYER 0x1 // P
+#define E_ENEMY 0x2 // E
+#define E_DOOR 0x4 // D
+#define E_LOCKEDDOOR 0x5 // L
+#define E_EXIT 0x7 // X
+// collectable entities >= 0x8
+#define E_MEDIKIT 0x8 // M
+#define E_KEY 0x9 // K
+#define E_FIREBALL 0xA // not in map
+
+typedef uint16_t UID;
+typedef uint8_t EType;
+
+typedef struct Coords {
+    double x;
+    double y;
+} Coords;
+
+UID create_uid(EType type, uint8_t x, uint8_t y);
+EType uid_get_type(UID uid);
+Coords create_coords(double x, double y);
+uint8_t coords_distance(Coords* a, Coords* b);
+
+#endif

+ 674 - 0
main_apps_sources/gps_nmea_uart/LICENSE

@@ -0,0 +1,674 @@
+                    GNU 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.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.

+ 46 - 0
main_apps_sources/gps_nmea_uart/README.md

@@ -0,0 +1,46 @@
+# GPS for Flipper Zero
+
+A simple Flipper Zero application for NMEA 0183 serial GPS modules, such as the
+- Adafruit Ultimate GPS Breakout.
+
+Heavy lifting (NMEA parsing) provided by minmea.
+
+## Usage
+
+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.
+- 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
+  again to disable.
+- Long press the back button to **exit** the app.
+
+## Hardware Setup
+
+Connect the GPS module to power and the USART using GPIO pins 9 (3.3V), 11
+(GND), 13 (TX), and 14 (RX), as appropriate.
+
+
+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
+
+* Adafruit Ultimate GPS Breakout
+* Beitian BN-180
+* Royaltek RBT-2100LP
+* u-blox NEO-6M
+
+If you have verified this application working with a module not listed here,
+please submit a PR adding it to the list.
+
+## Links
+
+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

+ 14 - 0
main_apps_sources/gps_nmea_uart/application.fam

@@ -0,0 +1,14 @@
+App(
+    appid="gps_nmea",
+    name="[NMEA] GPS",
+    apptype=FlipperAppType.EXTERNAL,
+    entry_point="gps_app",
+    requires=["gui"],
+    stack_size=1 * 1024,
+    order=35,
+    fap_icon="gps_10px.png",
+    fap_category="GPIO",
+    fap_author="@ezod & @xMasterX",
+    fap_version="1.0",
+    fap_description="Works with GPS modules via UART, using NMEA protocol.",
+)

+ 190 - 0
main_apps_sources/gps_nmea_uart/gps.c

@@ -0,0 +1,190 @@
+#include "gps_uart.h"
+
+#include <furi.h>
+#include <gui/gui.h>
+#include <string.h>
+
+typedef enum {
+    EventTypeTick,
+    EventTypeKey,
+} EventType;
+
+typedef struct {
+    EventType type;
+    InputEvent input;
+} PluginEvent;
+
+static void render_callback(Canvas* const canvas, void* context) {
+    furi_assert(context);
+    GpsUart* gps_uart = context;
+    furi_mutex_acquire(gps_uart->mutex, FuriWaitForever);
+
+    if(!gps_uart->changing_baudrate) {
+        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");
+        canvas_draw_str_aligned(canvas, 21, 30, AlignCenter, AlignBottom, "Course");
+        canvas_draw_str_aligned(canvas, 64, 30, AlignCenter, AlignBottom, "Speed");
+        canvas_draw_str_aligned(canvas, 107, 30, AlignCenter, AlignBottom, "Altitude");
+        canvas_draw_str_aligned(canvas, 32, 52, AlignCenter, AlignBottom, "Satellites");
+        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);
+        canvas_draw_str_aligned(canvas, 96, 18, AlignCenter, AlignBottom, buffer);
+        snprintf(buffer, 64, "%.1f", (double)gps_uart->status.course);
+        canvas_draw_str_aligned(canvas, 21, 40, AlignCenter, AlignBottom, buffer);
+        if(!gps_uart->speed_in_kms) {
+            snprintf(buffer, 64, "%.2f kn", (double)gps_uart->status.speed);
+        } else {
+            snprintf(buffer, 64, "%.2f km", (double)(gps_uart->status.speed * 1.852));
+        }
+        canvas_draw_str_aligned(canvas, 64, 40, AlignCenter, AlignBottom, buffer);
+        snprintf(
+            buffer,
+            64,
+            "%.1f %c",
+            (double)gps_uart->status.altitude,
+            tolower(gps_uart->status.altitude_units));
+        canvas_draw_str_aligned(canvas, 107, 40, AlignCenter, AlignBottom, buffer);
+        snprintf(buffer, 64, "%d", gps_uart->status.satellites_tracked);
+        canvas_draw_str_aligned(canvas, 32, 62, AlignCenter, AlignBottom, buffer);
+        snprintf(
+            buffer,
+            64,
+            "%02d:%02d:%02d UTC",
+            gps_uart->status.time_hours,
+            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);
+    }
+
+    furi_mutex_release(gps_uart->mutex);
+}
+
+static void input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) {
+    furi_assert(event_queue);
+
+    PluginEvent event = {.type = EventTypeKey, .input = *input_event};
+    furi_message_queue_put(event_queue, &event, FuriWaitForever);
+}
+
+int32_t gps_app(void* p) {
+    UNUSED(p);
+
+    FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(PluginEvent));
+
+    GpsUart* gps_uart = gps_uart_enable();
+
+    gps_uart->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
+    if(!gps_uart->mutex) {
+        FURI_LOG_E("GPS", "cannot create mutex\r\n");
+        free(gps_uart);
+        return 255;
+    }
+
+    // set system callbacks
+    ViewPort* view_port = view_port_alloc();
+    view_port_draw_callback_set(view_port, render_callback, gps_uart);
+    view_port_input_callback_set(view_port, input_callback, event_queue);
+
+    // open GUI and register view_port
+    Gui* gui = furi_record_open(RECORD_GUI);
+    gui_add_view_port(gui, view_port, GuiLayerFullscreen);
+
+    PluginEvent event;
+    for(bool processing = true; processing;) {
+        FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100);
+
+        furi_mutex_acquire(gps_uart->mutex, FuriWaitForever);
+
+        if(event_status == FuriStatusOk) {
+            // press events
+            if(event.type == EventTypeKey) {
+                if(event.input.type == InputTypeShort) {
+                    switch(event.input.key) {
+                    case InputKeyUp:
+                    case InputKeyDown:
+                    case InputKeyRight:
+                    case InputKeyLeft:
+                    case InputKeyBack:
+                        break;
+                    case InputKeyOk:
+                        if(!gps_uart->backlight_on) {
+                            notification_message_block(
+                                gps_uart->notifications, &sequence_display_backlight_enforce_on);
+                            gps_uart->backlight_on = 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;
+                        }
+                        break;
+                    default:
+                        break;
+                    }
+                } else if(event.input.type == InputTypeLong) {
+                    switch(event.input.key) {
+                    case InputKeyUp:
+                        gps_uart_deinit_thread(gps_uart);
+                        const int baudrate_length =
+                            sizeof(gps_baudrates) / sizeof(gps_baudrates[0]);
+                        current_gps_baudrate++;
+                        if(current_gps_baudrate >= baudrate_length) {
+                            current_gps_baudrate = 0;
+                        }
+                        gps_uart->baudrate = gps_baudrates[current_gps_baudrate];
+
+                        gps_uart_init_thread(gps_uart);
+                        gps_uart->changing_baudrate = true;
+                        view_port_update(view_port);
+                        furi_mutex_release(gps_uart->mutex);
+                        break;
+                    case InputKeyRight:
+                        if(gps_uart->speed_in_kms) {
+                            gps_uart->speed_in_kms = false;
+                        } else {
+                            gps_uart->speed_in_kms = true;
+                        }
+                        break;
+                    case InputKeyBack:
+                        processing = false;
+                        break;
+                    default:
+                        break;
+                    }
+                }
+            }
+        }
+        if(!gps_uart->changing_baudrate) {
+            view_port_update(view_port);
+            furi_mutex_release(gps_uart->mutex);
+        } else {
+            furi_delay_ms(1000);
+            gps_uart->changing_baudrate = false;
+        }
+    }
+
+    notification_message_block(gps_uart->notifications, &sequence_display_backlight_enforce_auto);
+    view_port_enabled_set(view_port, false);
+    gui_remove_view_port(gui, view_port);
+    furi_record_close(RECORD_GUI);
+    view_port_free(view_port);
+    furi_message_queue_free(event_queue);
+    furi_mutex_free(gps_uart->mutex);
+    gps_uart_disable(gps_uart);
+
+    return 0;
+}

BIN
main_apps_sources/gps_nmea_uart/gps_10px.png


+ 217 - 0
main_apps_sources/gps_nmea_uart/gps_uart.c

@@ -0,0 +1,217 @@
+#include <string.h>
+
+#include "minmea.h"
+#include "gps_uart.h"
+
+typedef enum {
+    WorkerEvtStop = (1 << 0),
+    WorkerEvtRxDone = (1 << 1),
+} WorkerEvtFlags;
+
+#define WORKER_ALL_RX_EVENTS (WorkerEvtStop | WorkerEvtRxDone)
+
+static void gps_uart_on_irq_cb(UartIrqEvent ev, uint8_t data, void* context) {
+    GpsUart* gps_uart = (GpsUart*)context;
+
+    if(ev == UartIrqEventRXNE) {
+        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);
+}
+
+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();
+}
+
+static void gps_uart_parse_nmea(GpsUart* gps_uart, char* line) {
+    switch(minmea_sentence_id(line, false)) {
+    case MINMEA_SENTENCE_RMC: {
+        struct minmea_sentence_rmc frame;
+        if(minmea_parse_rmc(&frame, line)) {
+            gps_uart->status.valid = frame.valid;
+            gps_uart->status.latitude = minmea_tocoord(&frame.latitude);
+            gps_uart->status.longitude = minmea_tocoord(&frame.longitude);
+            gps_uart->status.speed = minmea_tofloat(&frame.speed);
+            gps_uart->status.course = minmea_tofloat(&frame.course);
+            gps_uart->status.time_hours = frame.time.hours;
+            gps_uart->status.time_minutes = frame.time.minutes;
+            gps_uart->status.time_seconds = frame.time.seconds;
+
+            notification_message_block(gps_uart->notifications, &sequence_blink_green_10);
+        }
+    } break;
+
+    case MINMEA_SENTENCE_GGA: {
+        struct minmea_sentence_gga frame;
+        if(minmea_parse_gga(&frame, line)) {
+            gps_uart->status.latitude = minmea_tocoord(&frame.latitude);
+            gps_uart->status.longitude = minmea_tocoord(&frame.longitude);
+            gps_uart->status.altitude = minmea_tofloat(&frame.altitude);
+            gps_uart->status.altitude_units = frame.altitude_units;
+            gps_uart->status.fix_quality = frame.fix_quality;
+            gps_uart->status.satellites_tracked = frame.satellites_tracked;
+            gps_uart->status.time_hours = frame.time.hours;
+            gps_uart->status.time_minutes = frame.time.minutes;
+            gps_uart->status.time_seconds = frame.time.seconds;
+
+            notification_message_block(gps_uart->notifications, &sequence_blink_magenta_10);
+        }
+    } break;
+
+    case MINMEA_SENTENCE_GLL: {
+        struct minmea_sentence_gll frame;
+        if(minmea_parse_gll(&frame, line)) {
+            gps_uart->status.latitude = minmea_tocoord(&frame.latitude);
+            gps_uart->status.longitude = minmea_tocoord(&frame.longitude);
+            gps_uart->status.time_hours = frame.time.hours;
+            gps_uart->status.time_minutes = frame.time.minutes;
+            gps_uart->status.time_seconds = frame.time.seconds;
+
+            notification_message_block(gps_uart->notifications, &sequence_blink_red_10);
+        }
+    } break;
+
+    default:
+        break;
+    }
+}
+
+static int32_t gps_uart_worker(void* context) {
+    GpsUart* gps_uart = (GpsUart*)context;
+
+    size_t rx_offset = 0;
+
+    while(1) {
+        uint32_t events =
+            furi_thread_flags_wait(WORKER_ALL_RX_EVENTS, FuriFlagWaitAny, FuriWaitForever);
+        furi_check((events & FuriFlagError) == 0);
+
+        if(events & WorkerEvtStop) {
+            break;
+        }
+
+        if(events & WorkerEvtRxDone) {
+            size_t len = 0;
+            do {
+                // receive serial bytes into rx_buf, starting at rx_offset from the start of the buffer
+                // the maximum we can receive is RX_BUF_SIZE - 1 - rx_offset
+                len = furi_stream_buffer_receive(
+                    gps_uart->rx_stream,
+                    gps_uart->rx_buf + rx_offset,
+                    RX_BUF_SIZE - 1 - rx_offset,
+                    0);
+                if(len > 0) {
+                    // increase rx_offset by the number of bytes received, and null-terminate rx_buf
+                    rx_offset += len;
+                    gps_uart->rx_buf[rx_offset] = '\0';
+
+                    // look for strings ending in newlines, starting at the start of rx_buf
+                    char* line_current = (char*)gps_uart->rx_buf;
+                    while(1) {
+                        // skip null characters
+                        while(*line_current == '\0' &&
+                              line_current < (char*)gps_uart->rx_buf + rx_offset - 1) {
+                            line_current++;
+                        }
+
+                        // find the next newline
+                        char* newline = strchr(line_current, '\n');
+                        if(newline) // newline found
+                        {
+                            // put a null terminator in place of the newline, to delimit the line string
+                            *newline = '\0';
+
+                            // attempt to parse the line as a NMEA sentence
+                            gps_uart_parse_nmea(gps_uart, line_current);
+
+                            // move the cursor to the character after the newline
+                            line_current = newline + 1;
+                        } else // no more newlines found
+                        {
+                            if(line_current >
+                               (char*)gps_uart->rx_buf) // at least one line was found
+                            {
+                                // clear parsed lines, and move any leftover bytes to the start of rx_buf
+                                rx_offset = 0;
+                                while(
+                                    *line_current) // stop when the original rx_offset terminator is reached
+                                {
+                                    gps_uart->rx_buf[rx_offset++] = *(line_current++);
+                                }
+                            }
+                            break; // go back to receiving bytes from the serial stream
+                        }
+                    }
+                }
+            } while(len > 0);
+        }
+    }
+
+    gps_uart_serial_deinit(gps_uart);
+    furi_stream_buffer_free(gps_uart->rx_stream);
+
+    return 0;
+}
+
+void gps_uart_init_thread(GpsUart* gps_uart) {
+    furi_assert(gps_uart);
+    gps_uart->status.valid = false;
+    gps_uart->status.latitude = 0.0;
+    gps_uart->status.longitude = 0.0;
+    gps_uart->status.speed = 0.0;
+    gps_uart->status.course = 0.0;
+    gps_uart->status.altitude = 0.0;
+    gps_uart->status.altitude_units = ' ';
+    gps_uart->status.fix_quality = 0;
+    gps_uart->status.satellites_tracked = 0;
+    gps_uart->status.time_hours = 0;
+    gps_uart->status.time_minutes = 0;
+    gps_uart->status.time_seconds = 0;
+
+    gps_uart->rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE * 5, 1);
+
+    gps_uart->thread = furi_thread_alloc();
+    furi_thread_set_name(gps_uart->thread, "GpsUartWorker");
+    furi_thread_set_stack_size(gps_uart->thread, 1024);
+    furi_thread_set_context(gps_uart->thread, gps_uart);
+    furi_thread_set_callback(gps_uart->thread, gps_uart_worker);
+
+    furi_thread_start(gps_uart->thread);
+
+    gps_uart_serial_init(gps_uart);
+}
+
+void gps_uart_deinit_thread(GpsUart* gps_uart) {
+    furi_assert(gps_uart);
+    furi_thread_flags_set(furi_thread_get_id(gps_uart->thread), WorkerEvtStop);
+    furi_thread_join(gps_uart->thread);
+    furi_thread_free(gps_uart->thread);
+}
+
+GpsUart* gps_uart_enable() {
+    GpsUart* gps_uart = malloc(sizeof(GpsUart));
+
+    gps_uart->notifications = furi_record_open(RECORD_NOTIFICATION);
+
+    gps_uart->baudrate = gps_baudrates[current_gps_baudrate];
+
+    gps_uart_init_thread(gps_uart);
+
+    return gps_uart;
+}
+
+void gps_uart_disable(GpsUart* gps_uart) {
+    furi_assert(gps_uart);
+    gps_uart_deinit_thread(gps_uart);
+    furi_record_close(RECORD_NOTIFICATION);
+
+    free(gps_uart);
+}

+ 46 - 0
main_apps_sources/gps_nmea_uart/gps_uart.h

@@ -0,0 +1,46 @@
+#pragma once
+
+#include <furi_hal.h>
+#include <notification/notification_messages.h>
+
+#define RX_BUF_SIZE 1024
+
+static const int gps_baudrates[5] = {9600, 19200, 38400, 57600, 115200};
+static int current_gps_baudrate = 0;
+
+typedef struct {
+    bool valid;
+    float latitude;
+    float longitude;
+    float speed;
+    float course;
+    float altitude;
+    char altitude_units;
+    int fix_quality;
+    int satellites_tracked;
+    int time_hours;
+    int time_minutes;
+    int time_seconds;
+} GpsStatus;
+
+typedef struct {
+    FuriMutex* mutex;
+    FuriThread* thread;
+    FuriStreamBuffer* rx_stream;
+    uint8_t rx_buf[RX_BUF_SIZE];
+
+    NotificationApp* notifications;
+    uint32_t baudrate;
+    bool changing_baudrate;
+    bool backlight_on;
+    bool speed_in_kms;
+
+    GpsStatus status;
+} GpsUart;
+
+void gps_uart_init_thread(GpsUart* gps_uart);
+void gps_uart_deinit_thread(GpsUart* gps_uart);
+
+GpsUart* gps_uart_enable();
+
+void gps_uart_disable(GpsUart* gps_uart);

BIN
main_apps_sources/gps_nmea_uart/img/1.png


BIN
main_apps_sources/gps_nmea_uart/img/2.png


BIN
main_apps_sources/gps_nmea_uart/img/3.png


+ 640 - 0
main_apps_sources/gps_nmea_uart/minmea.c

@@ -0,0 +1,640 @@
+/*
+ * 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: */

+ 295 - 0
main_apps_sources/gps_nmea_uart/minmea.h

@@ -0,0 +1,295 @@
+/*
+ * 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.
+ */
+
+#ifndef MINMEA_H
+#define MINMEA_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <ctype.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <time.h>
+#include <math.h>
+#ifdef MINMEA_INCLUDE_COMPAT
+#include <minmea_compat.h>
+#endif
+
+#ifndef MINMEA_MAX_SENTENCE_LENGTH
+#define MINMEA_MAX_SENTENCE_LENGTH 80
+#endif
+
+enum minmea_sentence_id {
+    MINMEA_INVALID = -1,
+    MINMEA_UNKNOWN = 0,
+    MINMEA_SENTENCE_GBS,
+    MINMEA_SENTENCE_GGA,
+    MINMEA_SENTENCE_GLL,
+    MINMEA_SENTENCE_GSA,
+    MINMEA_SENTENCE_GST,
+    MINMEA_SENTENCE_GSV,
+    MINMEA_SENTENCE_RMC,
+    MINMEA_SENTENCE_VTG,
+    MINMEA_SENTENCE_ZDA,
+};
+
+struct minmea_float {
+    int_least32_t value;
+    int_least32_t scale;
+};
+
+struct minmea_date {
+    int day;
+    int month;
+    int year;
+};
+
+struct minmea_time {
+    int hours;
+    int minutes;
+    int seconds;
+    int microseconds;
+};
+
+struct minmea_sentence_gbs {
+    struct minmea_time time;
+    struct minmea_float err_latitude;
+    struct minmea_float err_longitude;
+    struct minmea_float err_altitude;
+    int svid;
+    struct minmea_float prob;
+    struct minmea_float bias;
+    struct minmea_float stddev;
+};
+
+struct minmea_sentence_rmc {
+    struct minmea_time time;
+    bool valid;
+    struct minmea_float latitude;
+    struct minmea_float longitude;
+    struct minmea_float speed;
+    struct minmea_float course;
+    struct minmea_date date;
+    struct minmea_float variation;
+};
+
+struct minmea_sentence_gga {
+    struct minmea_time time;
+    struct minmea_float latitude;
+    struct minmea_float longitude;
+    int fix_quality;
+    int satellites_tracked;
+    struct minmea_float hdop;
+    struct minmea_float altitude;
+    char altitude_units;
+    struct minmea_float height;
+    char height_units;
+    struct minmea_float dgps_age;
+};
+
+enum minmea_gll_status {
+    MINMEA_GLL_STATUS_DATA_VALID = 'A',
+    MINMEA_GLL_STATUS_DATA_NOT_VALID = 'V',
+};
+
+// FAA mode added to some fields in NMEA 2.3.
+enum minmea_faa_mode {
+    MINMEA_FAA_MODE_AUTONOMOUS = 'A',
+    MINMEA_FAA_MODE_DIFFERENTIAL = 'D',
+    MINMEA_FAA_MODE_ESTIMATED = 'E',
+    MINMEA_FAA_MODE_MANUAL = 'M',
+    MINMEA_FAA_MODE_SIMULATED = 'S',
+    MINMEA_FAA_MODE_NOT_VALID = 'N',
+    MINMEA_FAA_MODE_PRECISE = 'P',
+};
+
+struct minmea_sentence_gll {
+    struct minmea_float latitude;
+    struct minmea_float longitude;
+    struct minmea_time time;
+    char status;
+    char mode;
+};
+
+struct minmea_sentence_gst {
+    struct minmea_time time;
+    struct minmea_float rms_deviation;
+    struct minmea_float semi_major_deviation;
+    struct minmea_float semi_minor_deviation;
+    struct minmea_float semi_major_orientation;
+    struct minmea_float latitude_error_deviation;
+    struct minmea_float longitude_error_deviation;
+    struct minmea_float altitude_error_deviation;
+};
+
+enum minmea_gsa_mode {
+    MINMEA_GPGSA_MODE_AUTO = 'A',
+    MINMEA_GPGSA_MODE_FORCED = 'M',
+};
+
+enum minmea_gsa_fix_type {
+    MINMEA_GPGSA_FIX_NONE = 1,
+    MINMEA_GPGSA_FIX_2D = 2,
+    MINMEA_GPGSA_FIX_3D = 3,
+};
+
+struct minmea_sentence_gsa {
+    char mode;
+    int fix_type;
+    int sats[12];
+    struct minmea_float pdop;
+    struct minmea_float hdop;
+    struct minmea_float vdop;
+};
+
+struct minmea_sat_info {
+    int nr;
+    int elevation;
+    int azimuth;
+    int snr;
+};
+
+struct minmea_sentence_gsv {
+    int total_msgs;
+    int msg_nr;
+    int total_sats;
+    struct minmea_sat_info sats[4];
+};
+
+struct minmea_sentence_vtg {
+    struct minmea_float true_track_degrees;
+    struct minmea_float magnetic_track_degrees;
+    struct minmea_float speed_knots;
+    struct minmea_float speed_kph;
+    enum minmea_faa_mode faa_mode;
+};
+
+struct minmea_sentence_zda {
+    struct minmea_time time;
+    struct minmea_date date;
+    int hour_offset;
+    int minute_offset;
+};
+
+/**
+ * Calculate raw sentence checksum. Does not check sentence integrity.
+ */
+uint8_t minmea_checksum(const char* sentence);
+
+/**
+ * Check sentence validity and checksum. Returns true for valid sentences.
+ */
+bool minmea_check(const char* sentence, bool strict);
+
+/**
+ * Determine talker identifier.
+ */
+bool minmea_talker_id(char talker[3], const char* sentence);
+
+/**
+ * Determine sentence identifier.
+ */
+enum minmea_sentence_id minmea_sentence_id(const char* sentence, bool strict);
+
+/**
+ * Scanf-like processor for NMEA sentences. Supports the following formats:
+ * c - single character (char *)
+ * d - direction, returned as 1/-1, default 0 (int *)
+ * f - fractional, returned as value + scale (struct minmea_float *)
+ * i - decimal, default zero (int *)
+ * s - string (char *)
+ * t - talker identifier and type (char *)
+ * D - date (struct minmea_date *)
+ * T - time stamp (struct minmea_time *)
+ * _ - ignore this field
+ * ; - following fields are optional
+ * Returns true on success. See library source code for details.
+ */
+bool minmea_scan(const char* sentence, const char* format, ...);
+
+/*
+ * Parse a specific type of sentence. Return true on success.
+ */
+bool minmea_parse_gbs(struct minmea_sentence_gbs* frame, const char* sentence);
+bool minmea_parse_rmc(struct minmea_sentence_rmc* frame, const char* sentence);
+bool minmea_parse_gga(struct minmea_sentence_gga* frame, const char* sentence);
+bool minmea_parse_gsa(struct minmea_sentence_gsa* frame, const char* sentence);
+bool minmea_parse_gll(struct minmea_sentence_gll* frame, const char* sentence);
+bool minmea_parse_gst(struct minmea_sentence_gst* frame, const char* sentence);
+bool minmea_parse_gsv(struct minmea_sentence_gsv* frame, const char* sentence);
+bool minmea_parse_vtg(struct minmea_sentence_vtg* frame, const char* sentence);
+bool minmea_parse_zda(struct minmea_sentence_zda* frame, const char* sentence);
+
+/**
+ * Convert GPS UTC date/time representation to a UNIX calendar time.
+ */
+int minmea_getdatetime(
+    struct tm* tm,
+    const struct minmea_date* date,
+    const struct minmea_time* time_);
+
+/**
+ * Convert GPS UTC date/time representation to a UNIX timestamp.
+ */
+int minmea_gettime(
+    struct timespec* ts,
+    const struct minmea_date* date,
+    const struct minmea_time* time_);
+
+/**
+ * Rescale a fixed-point value to a different scale. Rounds towards zero.
+ */
+static inline int_least32_t minmea_rescale(const struct minmea_float* f, int_least32_t new_scale) {
+    if(f->scale == 0) return 0;
+    if(f->scale == new_scale) return f->value;
+    if(f->scale > new_scale)
+        return (f->value + ((f->value > 0) - (f->value < 0)) * f->scale / new_scale / 2) /
+               (f->scale / new_scale);
+    else
+        return f->value * (new_scale / f->scale);
+}
+
+/**
+ * Convert a fixed-point value to a floating-point value.
+ * Returns NaN for "unknown" values.
+ */
+static inline float minmea_tofloat(const struct minmea_float* f) {
+    if(f->scale == 0) return NAN;
+    return (float)f->value / (float)f->scale;
+}
+
+/**
+ * Convert a raw coordinate to a floating point DD.DDD... value.
+ * Returns NaN for "unknown" values.
+ */
+static inline float minmea_tocoord(const struct minmea_float* f) {
+    if(f->scale == 0) return NAN;
+    if(f->scale > (INT_LEAST32_MAX / 100)) return NAN;
+    if(f->scale < (INT_LEAST32_MIN / 100)) return NAN;
+    int_least32_t degrees = f->value / (f->scale * 100);
+    int_least32_t minutes = f->value % (f->scale * 100);
+    return (float)degrees + (float)minutes / (60 * f->scale);
+}
+
+/**
+ * Check whether a character belongs to the set of characters allowed in a
+ * sentence data field.
+ */
+static inline bool minmea_isfield(char c) {
+    return isprint((unsigned char)c) && c != ',' && c != '*';
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MINMEA_H */
+
+/* vim: set ts=4 sw=4 et: */

BIN
main_apps_sources/gps_nmea_uart/ui.png


BIN
main_apps_sources/gps_nmea_uart/wiring.png


+ 18 - 0
main_apps_sources/pocsag_pager/README.md

@@ -0,0 +1,18 @@
+# Flipper POCSAG Receiver plugin
+
+App can capture POCSAG 1200 messages using internal or external CC1101 module
+
+Plugin based on Weather Station - https://github.com/flipperdevices/flipperzero-firmware/tree/dev/applications/plugins/weather_station
+
+Protocol implementation made by @Shmuma
+Icons by @Svaarich
+
+Includes new FM preset built into code - 2FSK with 9.5KHz freq deviation.
+
+Default frequency is set to DAPNET - 439987500
+
+To add new presets and frequencies create file - yourMicroSD/pocsag/settings.txt
+And put THIS - https://github.com/flipperdevices/flipperzero-firmware/blob/dev/assets/resources/subghz/assets/setting_user.example file contents into it, and edit this example for yourself, add needed frequencies
+
+
+All contributions are welcome!

+ 15 - 0
main_apps_sources/pocsag_pager/application.fam

@@ -0,0 +1,15 @@
+App(
+    appid="pocsag_pager",
+    name="POCSAG Pager",
+    apptype=FlipperAppType.EXTERNAL,
+    entry_point="pocsag_pager_app",
+    requires=["gui"],
+    stack_size=4 * 1024,
+    order=50,
+    fap_icon="pocsag_pager_10px.png",
+    fap_category="Sub-GHz",
+    fap_icon_assets="images",
+    fap_author="@xMasterX & @Shmuma",
+    fap_version="1.0",
+    fap_description="App can capture POCSAG 1200 messages on CC1101 supported frequencies.",
+)

+ 14 - 0
main_apps_sources/pocsag_pager/helpers/pocsag_pager_event.h

@@ -0,0 +1,14 @@
+#pragma once
+
+typedef enum {
+    //PCSGCustomEvent
+    PCSGCustomEventStartId = 100,
+
+    PCSGCustomEventSceneSettingLock,
+
+    PCSGCustomEventViewReceiverOK,
+    PCSGCustomEventViewReceiverConfig,
+    PCSGCustomEventViewReceiverBack,
+    PCSGCustomEventViewReceiverOffDisplay,
+    PCSGCustomEventViewReceiverUnlock,
+} PCSGCustomEvent;

+ 49 - 0
main_apps_sources/pocsag_pager/helpers/pocsag_pager_types.h

@@ -0,0 +1,49 @@
+#pragma once
+
+#include <furi.h>
+#include <furi_hal.h>
+
+#define PCSG_VERSION_APP "0.1"
+#define PCSG_DEVELOPED "@xMasterX & @Shmuma"
+#define PCSG_GITHUB "https://github.com/xMasterX/flipper-pager"
+
+#define PCSG_KEY_FILE_VERSION 1
+#define PCSG_KEY_FILE_TYPE "Flipper POCSAG Pager Key File"
+
+/** PCSGRxKeyState state */
+typedef enum {
+    PCSGRxKeyStateIDLE,
+    PCSGRxKeyStateBack,
+    PCSGRxKeyStateStart,
+    PCSGRxKeyStateAddKey,
+} PCSGRxKeyState;
+
+/** PCSGHopperState state */
+typedef enum {
+    PCSGHopperStateOFF,
+    PCSGHopperStateRunnig,
+    PCSGHopperStatePause,
+    PCSGHopperStateRSSITimeOut,
+} PCSGHopperState;
+
+/** PCSGLock */
+typedef enum {
+    PCSGLockOff,
+    PCSGLockOn,
+} PCSGLock;
+
+typedef enum {
+    POCSAGPagerViewVariableItemList,
+    POCSAGPagerViewSubmenu,
+    POCSAGPagerViewReceiver,
+    POCSAGPagerViewReceiverInfo,
+    POCSAGPagerViewWidget,
+} POCSAGPagerView;
+
+/** POCSAGPagerTxRx state */
+typedef enum {
+    PCSGTxRxStateIDLE,
+    PCSGTxRxStateRx,
+    PCSGTxRxStateTx,
+    PCSGTxRxStateSleep,
+} PCSGTxRxState;

+ 66 - 0
main_apps_sources/pocsag_pager/helpers/radio_device_loader.c

@@ -0,0 +1,66 @@
+#include "radio_device_loader.h"
+
+#include <applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.h>
+#include <lib/subghz/devices/cc1101_int/cc1101_int_interconnect.h>
+
+static void radio_device_loader_power_on() {
+    uint8_t attempts = 0;
+    while(!furi_hal_power_is_otg_enabled() && attempts++ < 5) {
+        furi_hal_power_enable_otg();
+        //CC1101 power-up time
+        furi_delay_ms(10);
+    }
+}
+
+static void radio_device_loader_power_off() {
+    if(furi_hal_power_is_otg_enabled()) furi_hal_power_disable_otg();
+}
+
+bool radio_device_loader_is_connect_external(const char* name) {
+    bool is_connect = false;
+    bool is_otg_enabled = furi_hal_power_is_otg_enabled();
+
+    if(!is_otg_enabled) {
+        radio_device_loader_power_on();
+    }
+
+    is_connect = subghz_devices_is_connect(subghz_devices_get_by_name(name));
+
+    if(!is_otg_enabled) {
+        radio_device_loader_power_off();
+    }
+    return is_connect;
+}
+
+const SubGhzDevice* radio_device_loader_set(
+    const SubGhzDevice* current_radio_device,
+    SubGhzRadioDeviceType radio_device_type) {
+    const SubGhzDevice* radio_device;
+
+    if(radio_device_type == SubGhzRadioDeviceTypeExternalCC1101 &&
+       radio_device_loader_is_connect_external(SUBGHZ_DEVICE_CC1101_EXT_NAME)) {
+        radio_device_loader_power_on();
+        radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_EXT_NAME);
+        subghz_devices_begin(radio_device);
+    } else if(current_radio_device == NULL) {
+        radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME);
+    } else {
+        radio_device_loader_end(current_radio_device);
+        radio_device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME);
+    }
+
+    return radio_device;
+}
+
+bool radio_device_loader_is_external(const SubGhzDevice* radio_device) {
+    furi_assert(radio_device);
+    return (radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME));
+}
+
+void radio_device_loader_end(const SubGhzDevice* radio_device) {
+    furi_assert(radio_device);
+    radio_device_loader_power_off();
+    if(radio_device != subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME)) {
+        subghz_devices_end(radio_device);
+    }
+}

+ 17 - 0
main_apps_sources/pocsag_pager/helpers/radio_device_loader.h

@@ -0,0 +1,17 @@
+#pragma once
+
+#include <lib/subghz/devices/devices.h>
+
+/** SubGhzRadioDeviceType */
+typedef enum {
+    SubGhzRadioDeviceTypeInternal,
+    SubGhzRadioDeviceTypeExternalCC1101,
+} SubGhzRadioDeviceType;
+
+const SubGhzDevice* radio_device_loader_set(
+    const SubGhzDevice* current_radio_device,
+    SubGhzRadioDeviceType radio_device_type);
+
+bool radio_device_loader_is_external(const SubGhzDevice* radio_device);
+
+void radio_device_loader_end(const SubGhzDevice* radio_device);

BIN
main_apps_sources/pocsag_pager/images/Fishing_123x52.png


BIN
main_apps_sources/pocsag_pager/images/Lock_7x8.png


BIN
main_apps_sources/pocsag_pager/images/Message_8x7.png


BIN
main_apps_sources/pocsag_pager/images/Pin_back_arrow_10x8.png


BIN
main_apps_sources/pocsag_pager/images/Quest_7x8.png


BIN
main_apps_sources/pocsag_pager/images/Scanning_123x52.png


BIN
main_apps_sources/pocsag_pager/images/Unlock_7x8.png


BIN
main_apps_sources/pocsag_pager/images/WarningDolphin_45x42.png


BIN
main_apps_sources/pocsag_pager/img/1.png


BIN
main_apps_sources/pocsag_pager/img/2.png


BIN
main_apps_sources/pocsag_pager/img/3.png


BIN
main_apps_sources/pocsag_pager/pocsag_pager_10px.png


+ 206 - 0
main_apps_sources/pocsag_pager/pocsag_pager_app.c

@@ -0,0 +1,206 @@
+#include "pocsag_pager_app_i.h"
+
+#include <furi.h>
+#include <furi_hal.h>
+#include <lib/flipper_format/flipper_format.h>
+#include "protocols/protocol_items.h"
+
+static bool pocsag_pager_app_custom_event_callback(void* context, uint32_t event) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    return scene_manager_handle_custom_event(app->scene_manager, event);
+}
+
+static bool pocsag_pager_app_back_event_callback(void* context) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    return scene_manager_handle_back_event(app->scene_manager);
+}
+
+static void pocsag_pager_app_tick_event_callback(void* context) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    scene_manager_handle_tick_event(app->scene_manager);
+}
+
+POCSAGPagerApp* pocsag_pager_app_alloc() {
+    POCSAGPagerApp* app = malloc(sizeof(POCSAGPagerApp));
+
+    // GUI
+    app->gui = furi_record_open(RECORD_GUI);
+
+    // View Dispatcher
+    app->view_dispatcher = view_dispatcher_alloc();
+    app->scene_manager = scene_manager_alloc(&pocsag_pager_scene_handlers, app);
+    view_dispatcher_enable_queue(app->view_dispatcher);
+
+    view_dispatcher_set_event_callback_context(app->view_dispatcher, app);
+    view_dispatcher_set_custom_event_callback(
+        app->view_dispatcher, pocsag_pager_app_custom_event_callback);
+    view_dispatcher_set_navigation_event_callback(
+        app->view_dispatcher, pocsag_pager_app_back_event_callback);
+    view_dispatcher_set_tick_event_callback(
+        app->view_dispatcher, pocsag_pager_app_tick_event_callback, 100);
+
+    view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
+
+    // Open Notification record
+    app->notifications = furi_record_open(RECORD_NOTIFICATION);
+
+    // Variable Item List
+    app->variable_item_list = variable_item_list_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher,
+        POCSAGPagerViewVariableItemList,
+        variable_item_list_get_view(app->variable_item_list));
+
+    // SubMenu
+    app->submenu = submenu_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher, POCSAGPagerViewSubmenu, submenu_get_view(app->submenu));
+
+    // Widget
+    app->widget = widget_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher, POCSAGPagerViewWidget, widget_get_view(app->widget));
+
+    // Receiver
+    app->pcsg_receiver = pcsg_view_receiver_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher,
+        POCSAGPagerViewReceiver,
+        pcsg_view_receiver_get_view(app->pcsg_receiver));
+
+    // Receiver Info
+    app->pcsg_receiver_info = pcsg_view_receiver_info_alloc();
+    view_dispatcher_add_view(
+        app->view_dispatcher,
+        POCSAGPagerViewReceiverInfo,
+        pcsg_view_receiver_info_get_view(app->pcsg_receiver_info));
+
+    //init setting
+    app->setting = subghz_setting_alloc();
+
+    //ToDo FIX  file name setting
+
+    subghz_setting_load(app->setting, EXT_PATH("pocsag/settings.txt"));
+
+    //init Worker & Protocol & History
+    app->lock = PCSGLockOff;
+    app->txrx = malloc(sizeof(POCSAGPagerTxRx));
+    app->txrx->preset = malloc(sizeof(SubGhzRadioPreset));
+    app->txrx->preset->name = furi_string_alloc();
+
+    furi_hal_power_suppress_charge_enter();
+
+    // Radio Devices init & load
+    subghz_devices_init();
+    app->txrx->radio_device =
+        radio_device_loader_set(app->txrx->radio_device, SubGhzRadioDeviceTypeExternalCC1101);
+
+    subghz_devices_reset(app->txrx->radio_device);
+    subghz_devices_idle(app->txrx->radio_device);
+
+    // Custom Presets load without using config file
+
+    FlipperFormat* temp_fm_preset = flipper_format_string_alloc();
+    flipper_format_write_string_cstr(
+        temp_fm_preset,
+        (const char*)"Custom_preset_data",
+        (const char*)"02 0D 0B 06 08 32 07 04 14 00 13 02 12 04 11 83 10 67 15 24 18 18 19 16 1D 91 1C 00 1B 07 20 FB 22 10 21 56 00 00 C0 00 00 00 00 00 00 00");
+    flipper_format_rewind(temp_fm_preset);
+    subghz_setting_load_custom_preset(app->setting, (const char*)"FM95", temp_fm_preset);
+
+    flipper_format_free(temp_fm_preset);
+
+    // custom presets loading - end
+
+    pcsg_preset_init(app, "FM95", 439987500, NULL, 0);
+
+    app->txrx->hopper_state = PCSGHopperStateOFF;
+    app->txrx->history = pcsg_history_alloc();
+    app->txrx->worker = subghz_worker_alloc();
+    app->txrx->environment = subghz_environment_alloc();
+    subghz_environment_set_protocol_registry(
+        app->txrx->environment, (void*)&pocsag_pager_protocol_registry);
+    app->txrx->receiver = subghz_receiver_alloc_init(app->txrx->environment);
+
+    subghz_receiver_set_filter(app->txrx->receiver, SubGhzProtocolFlag_Decodable);
+    subghz_worker_set_overrun_callback(
+        app->txrx->worker, (SubGhzWorkerOverrunCallback)subghz_receiver_reset);
+    subghz_worker_set_pair_callback(
+        app->txrx->worker, (SubGhzWorkerPairCallback)subghz_receiver_decode);
+    subghz_worker_set_context(app->txrx->worker, app->txrx->receiver);
+
+    scene_manager_next_scene(app->scene_manager, POCSAGPagerSceneStart);
+
+    return app;
+}
+
+void pocsag_pager_app_free(POCSAGPagerApp* app) {
+    furi_assert(app);
+
+    // Radio Devices sleep & off
+    pcsg_sleep(app);
+    radio_device_loader_end(app->txrx->radio_device);
+
+    subghz_devices_deinit();
+
+    // Submenu
+    view_dispatcher_remove_view(app->view_dispatcher, POCSAGPagerViewSubmenu);
+    submenu_free(app->submenu);
+
+    // Variable Item List
+    view_dispatcher_remove_view(app->view_dispatcher, POCSAGPagerViewVariableItemList);
+    variable_item_list_free(app->variable_item_list);
+
+    //  Widget
+    view_dispatcher_remove_view(app->view_dispatcher, POCSAGPagerViewWidget);
+    widget_free(app->widget);
+
+    // Receiver
+    view_dispatcher_remove_view(app->view_dispatcher, POCSAGPagerViewReceiver);
+    pcsg_view_receiver_free(app->pcsg_receiver);
+
+    // Receiver Info
+    view_dispatcher_remove_view(app->view_dispatcher, POCSAGPagerViewReceiverInfo);
+    pcsg_view_receiver_info_free(app->pcsg_receiver_info);
+
+    //setting
+    subghz_setting_free(app->setting);
+
+    //Worker & Protocol & History
+    subghz_receiver_free(app->txrx->receiver);
+    subghz_environment_free(app->txrx->environment);
+    pcsg_history_free(app->txrx->history);
+    subghz_worker_free(app->txrx->worker);
+    furi_string_free(app->txrx->preset->name);
+    free(app->txrx->preset);
+    free(app->txrx);
+
+    // View dispatcher
+    view_dispatcher_free(app->view_dispatcher);
+    scene_manager_free(app->scene_manager);
+
+    // Notifications
+    furi_record_close(RECORD_NOTIFICATION);
+    app->notifications = NULL;
+
+    // Close records
+    furi_record_close(RECORD_GUI);
+
+    furi_hal_power_suppress_charge_exit();
+
+    free(app);
+}
+
+int32_t pocsag_pager_app(void* p) {
+    UNUSED(p);
+    POCSAGPagerApp* pocsag_pager_app = pocsag_pager_app_alloc();
+
+    view_dispatcher_run(pocsag_pager_app->view_dispatcher);
+
+    pocsag_pager_app_free(pocsag_pager_app);
+
+    return 0;
+}

+ 146 - 0
main_apps_sources/pocsag_pager/pocsag_pager_app_i.c

@@ -0,0 +1,146 @@
+#include "pocsag_pager_app_i.h"
+
+#define TAG "POCSAGPager"
+#include <flipper_format/flipper_format_i.h>
+
+void pcsg_preset_init(
+    void* context,
+    const char* preset_name,
+    uint32_t frequency,
+    uint8_t* preset_data,
+    size_t preset_data_size) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    furi_string_set(app->txrx->preset->name, preset_name);
+    app->txrx->preset->frequency = frequency;
+    app->txrx->preset->data = preset_data;
+    app->txrx->preset->data_size = preset_data_size;
+}
+
+void pcsg_get_frequency_modulation(
+    POCSAGPagerApp* app,
+    FuriString* frequency,
+    FuriString* modulation) {
+    furi_assert(app);
+    if(frequency != NULL) {
+        furi_string_printf(
+            frequency,
+            "%03ld.%02ld",
+            app->txrx->preset->frequency / 1000000 % 1000,
+            app->txrx->preset->frequency / 10000 % 100);
+    }
+    if(modulation != NULL) {
+        furi_string_printf(modulation, "%.2s", furi_string_get_cstr(app->txrx->preset->name));
+    }
+}
+
+void pcsg_begin(POCSAGPagerApp* app, uint8_t* preset_data) {
+    furi_assert(app);
+
+    subghz_devices_reset(app->txrx->radio_device);
+    subghz_devices_idle(app->txrx->radio_device);
+    subghz_devices_load_preset(app->txrx->radio_device, FuriHalSubGhzPresetCustom, preset_data);
+
+    // furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow);
+    app->txrx->txrx_state = PCSGTxRxStateIDLE;
+}
+
+uint32_t pcsg_rx(POCSAGPagerApp* app, uint32_t frequency) {
+    furi_assert(app);
+    if(!subghz_devices_is_frequency_valid(app->txrx->radio_device, frequency)) {
+        furi_crash("POCSAGPager: Incorrect RX frequency.");
+    }
+    furi_assert(
+        app->txrx->txrx_state != PCSGTxRxStateRx && app->txrx->txrx_state != PCSGTxRxStateSleep);
+
+    subghz_devices_idle(app->txrx->radio_device);
+    uint32_t value = subghz_devices_set_frequency(app->txrx->radio_device, frequency);
+
+    // Not need. init in subghz_devices_start_async_tx
+    // furi_hal_gpio_init(furi_hal_subghz.cc1101_g0_pin, GpioModeInput, GpioPullNo, GpioSpeedLow);
+
+    subghz_devices_flush_rx(app->txrx->radio_device);
+    subghz_devices_set_rx(app->txrx->radio_device);
+
+    subghz_devices_start_async_rx(
+        app->txrx->radio_device, subghz_worker_rx_callback, app->txrx->worker);
+    subghz_worker_start(app->txrx->worker);
+    app->txrx->txrx_state = PCSGTxRxStateRx;
+    return value;
+}
+
+void pcsg_idle(POCSAGPagerApp* app) {
+    furi_assert(app);
+    furi_assert(app->txrx->txrx_state != PCSGTxRxStateSleep);
+    subghz_devices_idle(app->txrx->radio_device);
+    app->txrx->txrx_state = PCSGTxRxStateIDLE;
+}
+
+void pcsg_rx_end(POCSAGPagerApp* app) {
+    furi_assert(app);
+    furi_assert(app->txrx->txrx_state == PCSGTxRxStateRx);
+    if(subghz_worker_is_running(app->txrx->worker)) {
+        subghz_worker_stop(app->txrx->worker);
+        subghz_devices_stop_async_rx(app->txrx->radio_device);
+    }
+    subghz_devices_idle(app->txrx->radio_device);
+    app->txrx->txrx_state = PCSGTxRxStateIDLE;
+}
+
+void pcsg_sleep(POCSAGPagerApp* app) {
+    furi_assert(app);
+    subghz_devices_sleep(app->txrx->radio_device);
+    app->txrx->txrx_state = PCSGTxRxStateSleep;
+}
+
+void pcsg_hopper_update(POCSAGPagerApp* app) {
+    furi_assert(app);
+
+    switch(app->txrx->hopper_state) {
+    case PCSGHopperStateOFF:
+        return;
+        break;
+    case PCSGHopperStatePause:
+        return;
+        break;
+    case PCSGHopperStateRSSITimeOut:
+        if(app->txrx->hopper_timeout != 0) {
+            app->txrx->hopper_timeout--;
+            return;
+        }
+        break;
+    default:
+        break;
+    }
+    float rssi = -127.0f;
+    if(app->txrx->hopper_state != PCSGHopperStateRSSITimeOut) {
+        // See RSSI Calculation timings in CC1101 17.3 RSSI
+        rssi = subghz_devices_get_rssi(app->txrx->radio_device);
+
+        // Stay if RSSI is high enough
+        if(rssi > -90.0f) {
+            app->txrx->hopper_timeout = 10;
+            app->txrx->hopper_state = PCSGHopperStateRSSITimeOut;
+            return;
+        }
+    } else {
+        app->txrx->hopper_state = PCSGHopperStateRunnig;
+    }
+    // Select next frequency
+    if(app->txrx->hopper_idx_frequency <
+       subghz_setting_get_hopper_frequency_count(app->setting) - 1) {
+        app->txrx->hopper_idx_frequency++;
+    } else {
+        app->txrx->hopper_idx_frequency = 0;
+    }
+
+    if(app->txrx->txrx_state == PCSGTxRxStateRx) {
+        pcsg_rx_end(app);
+    };
+    if(app->txrx->txrx_state == PCSGTxRxStateIDLE) {
+        subghz_receiver_reset(app->txrx->receiver);
+        app->txrx->preset->frequency =
+            subghz_setting_get_hopper_frequency(app->setting, app->txrx->hopper_idx_frequency);
+        pcsg_rx(app, app->txrx->preset->frequency);
+    }
+}

+ 76 - 0
main_apps_sources/pocsag_pager/pocsag_pager_app_i.h

@@ -0,0 +1,76 @@
+#pragma once
+
+#include "helpers/pocsag_pager_types.h"
+#include "helpers/radio_device_loader.h"
+
+#include "scenes/pocsag_pager_scene.h"
+#include <gui/gui.h>
+#include <gui/view_dispatcher.h>
+#include <gui/scene_manager.h>
+#include <gui/modules/submenu.h>
+#include <gui/modules/variable_item_list.h>
+#include <gui/modules/widget.h>
+#include <notification/notification_messages.h>
+#include "views/pocsag_pager_receiver.h"
+#include "views/pocsag_pager_receiver_info.h"
+#include "pocsag_pager_history.h"
+
+#include <lib/subghz/subghz_setting.h>
+#include <lib/subghz/subghz_worker.h>
+#include <lib/subghz/receiver.h>
+#include <lib/subghz/transmitter.h>
+#include <lib/subghz/registry.h>
+#include <lib/subghz/devices/devices.h>
+
+typedef struct POCSAGPagerApp POCSAGPagerApp;
+
+struct POCSAGPagerTxRx {
+    SubGhzWorker* worker;
+
+    SubGhzEnvironment* environment;
+    SubGhzReceiver* receiver;
+    SubGhzRadioPreset* preset;
+    PCSGHistory* history;
+    uint16_t idx_menu_chosen;
+    PCSGTxRxState txrx_state;
+    PCSGHopperState hopper_state;
+    uint8_t hopper_timeout;
+    uint8_t hopper_idx_frequency;
+    PCSGRxKeyState rx_key_state;
+
+    const SubGhzDevice* radio_device;
+};
+
+typedef struct POCSAGPagerTxRx POCSAGPagerTxRx;
+
+struct POCSAGPagerApp {
+    Gui* gui;
+    ViewDispatcher* view_dispatcher;
+    POCSAGPagerTxRx* txrx;
+    SceneManager* scene_manager;
+    NotificationApp* notifications;
+    VariableItemList* variable_item_list;
+    Submenu* submenu;
+    Widget* widget;
+    PCSGReceiver* pcsg_receiver;
+    PCSGReceiverInfo* pcsg_receiver_info;
+    PCSGLock lock;
+    SubGhzSetting* setting;
+};
+
+void pcsg_preset_init(
+    void* context,
+    const char* preset_name,
+    uint32_t frequency,
+    uint8_t* preset_data,
+    size_t preset_data_size);
+void pcsg_get_frequency_modulation(
+    POCSAGPagerApp* app,
+    FuriString* frequency,
+    FuriString* modulation);
+void pcsg_begin(POCSAGPagerApp* app, uint8_t* preset_data);
+uint32_t pcsg_rx(POCSAGPagerApp* app, uint32_t frequency);
+void pcsg_idle(POCSAGPagerApp* app);
+void pcsg_rx_end(POCSAGPagerApp* app);
+void pcsg_sleep(POCSAGPagerApp* app);
+void pcsg_hopper_update(POCSAGPagerApp* app);

+ 223 - 0
main_apps_sources/pocsag_pager/pocsag_pager_history.c

@@ -0,0 +1,223 @@
+#include "pocsag_pager_history.h"
+#include <flipper_format/flipper_format_i.h>
+#include <lib/toolbox/stream/stream.h>
+#include <lib/subghz/receiver.h>
+#include "protocols/pcsg_generic.h"
+
+#include <furi.h>
+
+#define PCSG_HISTORY_MAX 50
+#define TAG "PCSGHistory"
+
+typedef struct {
+    FuriString* item_str;
+    FlipperFormat* flipper_string;
+    uint8_t type;
+    SubGhzRadioPreset* preset;
+} PCSGHistoryItem;
+
+ARRAY_DEF(PCSGHistoryItemArray, PCSGHistoryItem, M_POD_OPLIST)
+
+#define M_OPL_PCSGHistoryItemArray_t() ARRAY_OPLIST(PCSGHistoryItemArray, M_POD_OPLIST)
+
+typedef struct {
+    PCSGHistoryItemArray_t data;
+} PCSGHistoryStruct;
+
+struct PCSGHistory {
+    uint32_t last_update_timestamp;
+    uint16_t last_index_write;
+    uint8_t code_last_hash_data;
+    FuriString* tmp_string;
+    PCSGHistoryStruct* history;
+};
+
+PCSGHistory* pcsg_history_alloc(void) {
+    PCSGHistory* instance = malloc(sizeof(PCSGHistory));
+    instance->tmp_string = furi_string_alloc();
+    instance->history = malloc(sizeof(PCSGHistoryStruct));
+    PCSGHistoryItemArray_init(instance->history->data);
+    return instance;
+}
+
+void pcsg_history_free(PCSGHistory* instance) {
+    furi_assert(instance);
+    furi_string_free(instance->tmp_string);
+    for
+        M_EACH(item, instance->history->data, PCSGHistoryItemArray_t) {
+            furi_string_free(item->item_str);
+            furi_string_free(item->preset->name);
+            free(item->preset);
+            flipper_format_free(item->flipper_string);
+            item->type = 0;
+        }
+    PCSGHistoryItemArray_clear(instance->history->data);
+    free(instance->history);
+    free(instance);
+}
+
+uint32_t pcsg_history_get_frequency(PCSGHistory* instance, uint16_t idx) {
+    furi_assert(instance);
+    PCSGHistoryItem* item = PCSGHistoryItemArray_get(instance->history->data, idx);
+    return item->preset->frequency;
+}
+
+SubGhzRadioPreset* pcsg_history_get_radio_preset(PCSGHistory* instance, uint16_t idx) {
+    furi_assert(instance);
+    PCSGHistoryItem* item = PCSGHistoryItemArray_get(instance->history->data, idx);
+    return item->preset;
+}
+
+const char* pcsg_history_get_preset(PCSGHistory* instance, uint16_t idx) {
+    furi_assert(instance);
+    PCSGHistoryItem* item = PCSGHistoryItemArray_get(instance->history->data, idx);
+    return furi_string_get_cstr(item->preset->name);
+}
+
+void pcsg_history_reset(PCSGHistory* instance) {
+    furi_assert(instance);
+    furi_string_reset(instance->tmp_string);
+    for
+        M_EACH(item, instance->history->data, PCSGHistoryItemArray_t) {
+            furi_string_free(item->item_str);
+            furi_string_free(item->preset->name);
+            free(item->preset);
+            flipper_format_free(item->flipper_string);
+            item->type = 0;
+        }
+    PCSGHistoryItemArray_reset(instance->history->data);
+    instance->last_index_write = 0;
+    instance->code_last_hash_data = 0;
+}
+
+uint16_t pcsg_history_get_item(PCSGHistory* instance) {
+    furi_assert(instance);
+    return instance->last_index_write;
+}
+
+uint8_t pcsg_history_get_type_protocol(PCSGHistory* instance, uint16_t idx) {
+    furi_assert(instance);
+    PCSGHistoryItem* item = PCSGHistoryItemArray_get(instance->history->data, idx);
+    return item->type;
+}
+
+const char* pcsg_history_get_protocol_name(PCSGHistory* instance, uint16_t idx) {
+    furi_assert(instance);
+    PCSGHistoryItem* item = PCSGHistoryItemArray_get(instance->history->data, idx);
+    flipper_format_rewind(item->flipper_string);
+    if(!flipper_format_read_string(item->flipper_string, "Protocol", instance->tmp_string)) {
+        FURI_LOG_E(TAG, "Missing Protocol");
+        furi_string_reset(instance->tmp_string);
+    }
+    return furi_string_get_cstr(instance->tmp_string);
+}
+
+FlipperFormat* pcsg_history_get_raw_data(PCSGHistory* instance, uint16_t idx) {
+    furi_assert(instance);
+    PCSGHistoryItem* item = PCSGHistoryItemArray_get(instance->history->data, idx);
+    if(item->flipper_string) {
+        return item->flipper_string;
+    } else {
+        return NULL;
+    }
+}
+bool pcsg_history_get_text_space_left(PCSGHistory* instance, FuriString* output) {
+    furi_assert(instance);
+    if(instance->last_index_write == PCSG_HISTORY_MAX) {
+        if(output != NULL) furi_string_printf(output, "Memory is FULL");
+        return true;
+    }
+    if(output != NULL)
+        furi_string_printf(output, "%02u/%02u", instance->last_index_write, PCSG_HISTORY_MAX);
+    return false;
+}
+
+void pcsg_history_get_text_item_menu(PCSGHistory* instance, FuriString* output, uint16_t idx) {
+    PCSGHistoryItem* item = PCSGHistoryItemArray_get(instance->history->data, idx);
+    furi_string_set(output, item->item_str);
+}
+
+PCSGHistoryStateAddKey
+    pcsg_history_add_to_history(PCSGHistory* instance, void* context, SubGhzRadioPreset* preset) {
+    furi_assert(instance);
+    furi_assert(context);
+
+    if(instance->last_index_write >= PCSG_HISTORY_MAX) return PCSGHistoryStateAddKeyOverflow;
+
+    SubGhzProtocolDecoderBase* decoder_base = context;
+    if((instance->code_last_hash_data ==
+        subghz_protocol_decoder_base_get_hash_data(decoder_base)) &&
+       ((furi_get_tick() - instance->last_update_timestamp) < 500)) {
+        instance->last_update_timestamp = furi_get_tick();
+        return PCSGHistoryStateAddKeyTimeOut;
+    }
+
+    instance->code_last_hash_data = subghz_protocol_decoder_base_get_hash_data(decoder_base);
+    instance->last_update_timestamp = furi_get_tick();
+
+    FlipperFormat* fff = flipper_format_string_alloc();
+    subghz_protocol_decoder_base_serialize(decoder_base, fff, preset);
+
+    do {
+        if(!flipper_format_rewind(fff)) {
+            FURI_LOG_E(TAG, "Rewind error");
+            break;
+        }
+
+    } while(false);
+    flipper_format_free(fff);
+
+    PCSGHistoryItem* item = PCSGHistoryItemArray_push_raw(instance->history->data);
+    item->preset = malloc(sizeof(SubGhzRadioPreset));
+    item->type = decoder_base->protocol->type;
+    item->preset->frequency = preset->frequency;
+    item->preset->name = furi_string_alloc();
+    furi_string_set(item->preset->name, preset->name);
+    item->preset->data = preset->data;
+    item->preset->data_size = preset->data_size;
+
+    item->item_str = furi_string_alloc();
+    item->flipper_string = flipper_format_string_alloc();
+    subghz_protocol_decoder_base_serialize(decoder_base, item->flipper_string, preset);
+
+    do {
+        if(!flipper_format_rewind(item->flipper_string)) {
+            FURI_LOG_E(TAG, "Rewind error");
+            break;
+        }
+        if(!flipper_format_read_string(item->flipper_string, "Protocol", instance->tmp_string)) {
+            FURI_LOG_E(TAG, "Missing Protocol");
+            break;
+        }
+
+        if(!flipper_format_rewind(item->flipper_string)) {
+            FURI_LOG_E(TAG, "Rewind error");
+            break;
+        }
+        FuriString* temp_ric = furi_string_alloc();
+        if(!flipper_format_read_string(item->flipper_string, "Ric", temp_ric)) {
+            FURI_LOG_E(TAG, "Missing Ric");
+            break;
+        }
+
+        FuriString* temp_message = furi_string_alloc();
+        if(!flipper_format_read_string(item->flipper_string, "Message", temp_message)) {
+            FURI_LOG_E(TAG, "Missing Message");
+            break;
+        }
+
+        furi_string_printf(
+            item->item_str,
+            "%s%s",
+            furi_string_get_cstr(temp_ric),
+            furi_string_get_cstr(temp_message));
+
+        furi_string_free(temp_message);
+        furi_string_free(temp_ric);
+
+    } while(false);
+    instance->last_index_write++;
+    return PCSGHistoryStateAddKeyNewDada;
+
+    return PCSGHistoryStateAddKeyUnknown;
+}

+ 112 - 0
main_apps_sources/pocsag_pager/pocsag_pager_history.h

@@ -0,0 +1,112 @@
+
+#pragma once
+
+#include <math.h>
+#include <furi.h>
+#include <furi_hal.h>
+#include <lib/flipper_format/flipper_format.h>
+#include <lib/subghz/types.h>
+
+typedef struct PCSGHistory PCSGHistory;
+
+/** History state add key */
+typedef enum {
+    PCSGHistoryStateAddKeyUnknown,
+    PCSGHistoryStateAddKeyTimeOut,
+    PCSGHistoryStateAddKeyNewDada,
+    PCSGHistoryStateAddKeyUpdateData,
+    PCSGHistoryStateAddKeyOverflow,
+} PCSGHistoryStateAddKey;
+
+/** Allocate PCSGHistory
+ * 
+ * @return PCSGHistory* 
+ */
+PCSGHistory* pcsg_history_alloc(void);
+
+/** Free PCSGHistory
+ * 
+ * @param instance - PCSGHistory instance
+ */
+void pcsg_history_free(PCSGHistory* instance);
+
+/** Clear history
+ * 
+ * @param instance - PCSGHistory instance
+ */
+void pcsg_history_reset(PCSGHistory* instance);
+
+/** Get frequency to history[idx]
+ * 
+ * @param instance  - PCSGHistory instance
+ * @param idx       - record index  
+ * @return frequency - frequency Hz
+ */
+uint32_t pcsg_history_get_frequency(PCSGHistory* instance, uint16_t idx);
+
+SubGhzRadioPreset* pcsg_history_get_radio_preset(PCSGHistory* instance, uint16_t idx);
+
+/** Get preset to history[idx]
+ * 
+ * @param instance  - PCSGHistory instance
+ * @param idx       - record index  
+ * @return preset   - preset name
+ */
+const char* pcsg_history_get_preset(PCSGHistory* instance, uint16_t idx);
+
+/** Get history index write 
+ * 
+ * @param instance  - PCSGHistory instance
+ * @return idx      - current record index  
+ */
+uint16_t pcsg_history_get_item(PCSGHistory* instance);
+
+/** Get type protocol to history[idx]
+ * 
+ * @param instance  - PCSGHistory instance
+ * @param idx       - record index  
+ * @return type      - type protocol  
+ */
+uint8_t pcsg_history_get_type_protocol(PCSGHistory* instance, uint16_t idx);
+
+/** Get name protocol to history[idx]
+ * 
+ * @param instance  - PCSGHistory instance
+ * @param idx       - record index  
+ * @return name      - const char* name protocol  
+ */
+const char* pcsg_history_get_protocol_name(PCSGHistory* instance, uint16_t idx);
+
+/** Get string item menu to history[idx]
+ * 
+ * @param instance  - PCSGHistory instance
+ * @param output    - FuriString* output
+ * @param idx       - record index
+ */
+void pcsg_history_get_text_item_menu(PCSGHistory* instance, FuriString* output, uint16_t idx);
+
+/** Get string the remaining number of records to history
+ * 
+ * @param instance  - PCSGHistory instance
+ * @param output    - FuriString* output
+ * @return bool - is FUUL
+ */
+bool pcsg_history_get_text_space_left(PCSGHistory* instance, FuriString* output);
+
+/** Add protocol to history
+ * 
+ * @param instance  - PCSGHistory instance
+ * @param context    - SubGhzProtocolCommon context
+ * @param preset    - SubGhzRadioPreset preset
+ * @return PCSGHistoryStateAddKey;
+ */
+PCSGHistoryStateAddKey
+    pcsg_history_add_to_history(PCSGHistory* instance, void* context, SubGhzRadioPreset* preset);
+
+/** Get SubGhzProtocolCommonLoad to load into the protocol decoder bin data
+ * 
+ * @param instance  - PCSGHistory instance
+ * @param idx       - record index
+ * @return SubGhzProtocolCommonLoad*
+ */
+FlipperFormat* pcsg_history_get_raw_data(PCSGHistory* instance, uint16_t idx);

+ 124 - 0
main_apps_sources/pocsag_pager/protocols/pcsg_generic.c

@@ -0,0 +1,124 @@
+#include "pcsg_generic.h"
+#include <lib/toolbox/stream/stream.h>
+#include <lib/flipper_format/flipper_format_i.h>
+#include "../helpers/pocsag_pager_types.h"
+
+#define TAG "PCSGBlockGeneric"
+
+void pcsg_block_generic_get_preset_name(const char* preset_name, FuriString* preset_str) {
+    const char* preset_name_temp;
+    if(!strcmp(preset_name, "AM270")) {
+        preset_name_temp = "FuriHalSubGhzPresetOok270Async";
+    } else if(!strcmp(preset_name, "AM650")) {
+        preset_name_temp = "FuriHalSubGhzPresetOok650Async";
+    } else if(!strcmp(preset_name, "FM238")) {
+        preset_name_temp = "FuriHalSubGhzPreset2FSKDev238Async";
+    } else if(!strcmp(preset_name, "FM476")) {
+        preset_name_temp = "FuriHalSubGhzPreset2FSKDev476Async";
+    } else {
+        preset_name_temp = "FuriHalSubGhzPresetCustom";
+    }
+    furi_string_set(preset_str, preset_name_temp);
+}
+
+SubGhzProtocolStatus pcsg_block_generic_serialize(
+    PCSGBlockGeneric* instance,
+    FlipperFormat* flipper_format,
+    SubGhzRadioPreset* preset) {
+    furi_assert(instance);
+    SubGhzProtocolStatus res = SubGhzProtocolStatusError;
+    FuriString* temp_str;
+    temp_str = furi_string_alloc();
+    do {
+        stream_clean(flipper_format_get_raw_stream(flipper_format));
+        if(!flipper_format_write_header_cstr(
+               flipper_format, PCSG_KEY_FILE_TYPE, PCSG_KEY_FILE_VERSION)) {
+            FURI_LOG_E(TAG, "Unable to add header");
+            break;
+        }
+
+        if(!flipper_format_write_uint32(flipper_format, "Frequency", &preset->frequency, 1)) {
+            FURI_LOG_E(TAG, "Unable to add Frequency");
+            break;
+        }
+
+        pcsg_block_generic_get_preset_name(furi_string_get_cstr(preset->name), temp_str);
+        if(!flipper_format_write_string_cstr(
+               flipper_format, "Preset", furi_string_get_cstr(temp_str))) {
+            FURI_LOG_E(TAG, "Unable to add Preset");
+            break;
+        }
+        if(!strcmp(furi_string_get_cstr(temp_str), "FuriHalSubGhzPresetCustom")) {
+            if(!flipper_format_write_string_cstr(
+                   flipper_format, "Custom_preset_module", "CC1101")) {
+                FURI_LOG_E(TAG, "Unable to add Custom_preset_module");
+                break;
+            }
+            if(!flipper_format_write_hex(
+                   flipper_format, "Custom_preset_data", preset->data, preset->data_size)) {
+                FURI_LOG_E(TAG, "Unable to add Custom_preset_data");
+                break;
+            }
+        }
+        if(!flipper_format_write_string_cstr(flipper_format, "Protocol", instance->protocol_name)) {
+            FURI_LOG_E(TAG, "Unable to add Protocol");
+            break;
+        }
+
+        if(!flipper_format_write_string(flipper_format, "Ric", instance->result_ric)) {
+            FURI_LOG_E(TAG, "Unable to add Ric");
+            break;
+        }
+
+        if(!flipper_format_write_string(flipper_format, "Message", instance->result_msg)) {
+            FURI_LOG_E(TAG, "Unable to add Message");
+            break;
+        }
+
+        res = SubGhzProtocolStatusOk;
+    } while(false);
+    furi_string_free(temp_str);
+    return res;
+}
+
+SubGhzProtocolStatus
+    pcsg_block_generic_deserialize(PCSGBlockGeneric* instance, FlipperFormat* flipper_format) {
+    furi_assert(instance);
+    SubGhzProtocolStatus res = SubGhzProtocolStatusError;
+    FuriString* temp_data = furi_string_alloc();
+    FuriString* temp_data2 = furi_string_alloc();
+
+    do {
+        if(!flipper_format_rewind(flipper_format)) {
+            FURI_LOG_E(TAG, "Rewind error");
+            break;
+        }
+
+        if(!flipper_format_read_string(flipper_format, "Ric", temp_data2)) {
+            FURI_LOG_E(TAG, "Missing Ric");
+            break;
+        }
+        if(instance->result_ric != NULL) {
+            furi_string_set(instance->result_ric, temp_data2);
+        } else {
+            instance->result_ric = furi_string_alloc_set(temp_data2);
+        }
+
+        if(!flipper_format_read_string(flipper_format, "Message", temp_data)) {
+            FURI_LOG_E(TAG, "Missing Message");
+            break;
+        }
+        if(instance->result_msg != NULL) {
+            furi_string_set(instance->result_msg, temp_data);
+        } else {
+            instance->result_msg = furi_string_alloc_set(temp_data);
+        }
+
+        res = SubGhzProtocolStatusOk;
+    } while(0);
+
+    furi_string_free(temp_data);
+    furi_string_free(temp_data2);
+
+    return res;
+}

+ 56 - 0
main_apps_sources/pocsag_pager/protocols/pcsg_generic.h

@@ -0,0 +1,56 @@
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stddef.h>
+
+#include <lib/flipper_format/flipper_format.h>
+#include "furi.h"
+#include "furi_hal.h"
+#include <lib/subghz/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct PCSGBlockGeneric PCSGBlockGeneric;
+
+struct PCSGBlockGeneric {
+    const char* protocol_name;
+    FuriString* result_ric;
+    FuriString* result_msg;
+};
+
+/**
+ * Get name preset.
+ * @param preset_name name preset
+ * @param preset_str Output name preset
+ */
+void pcsg_block_generic_get_preset_name(const char* preset_name, FuriString* preset_str);
+
+/**
+ * Serialize data PCSGBlockGeneric.
+ * @param instance Pointer to a PCSGBlockGeneric instance
+ * @param flipper_format Pointer to a FlipperFormat instance
+ * @param preset The modulation on which the signal was received, SubGhzRadioPreset
+ * @return true On success
+ */
+SubGhzProtocolStatus pcsg_block_generic_serialize(
+    PCSGBlockGeneric* instance,
+    FlipperFormat* flipper_format,
+    SubGhzRadioPreset* preset);
+
+/**
+ * Deserialize data PCSGBlockGeneric.
+ * @param instance Pointer to a PCSGBlockGeneric instance
+ * @param flipper_format Pointer to a FlipperFormat instance
+ * @return true On success
+ */
+SubGhzProtocolStatus
+    pcsg_block_generic_deserialize(PCSGBlockGeneric* instance, FlipperFormat* flipper_format);
+
+float pcsg_block_generic_fahrenheit_to_celsius(float fahrenheit);
+
+#ifdef __cplusplus
+}
+#endif

+ 374 - 0
main_apps_sources/pocsag_pager/protocols/pocsag.c

@@ -0,0 +1,374 @@
+#include "pocsag.h"
+
+#include <inttypes.h>
+#include <lib/flipper_format/flipper_format_i.h>
+#include <furi/core/string.h>
+
+#define TAG "POCSAG"
+
+static const SubGhzBlockConst pocsag_const = {
+    .te_short = 833,
+    .te_delta = 100,
+};
+
+// Minimal amount of sync bits (interleaving zeros and ones)
+#define POCSAG_MIN_SYNC_BITS 32
+#define POCSAG_CW_BITS 32
+#define POCSAG_CW_MASK 0xFFFFFFFF
+#define POCSAG_FRAME_SYNC_CODE 0x7CD215D8
+#define POCSAG_IDLE_CODE_WORD 0x7A89C197
+
+#define POCSAG_FUNC_NUM 0
+#define POCSAG_FUNC_ALERT1 1
+#define POCSAG_FUNC_ALERT2 2
+#define POCSAG_FUNC_ALPHANUM 3
+
+static const char* func_msg[] = {"\e#Num:\e# ", "\e#Alert\e#", "\e#Alert:\e# ", "\e#Msg:\e# "};
+static const char* bcd_chars = "*U -)(";
+
+struct SubGhzProtocolDecoderPocsag {
+    SubGhzProtocolDecoderBase base;
+
+    SubGhzBlockDecoder decoder;
+    PCSGBlockGeneric generic;
+
+    uint8_t codeword_idx;
+    uint32_t ric;
+    uint8_t func;
+
+    // partially decoded character
+    uint8_t char_bits;
+    uint8_t char_data;
+
+    // message being decoded
+    FuriString* msg;
+
+    // Done messages, ready to be serialized/deserialized
+    FuriString* done_msg;
+};
+
+typedef struct SubGhzProtocolDecoderPocsag SubGhzProtocolDecoderPocsag;
+
+typedef enum {
+    PocsagDecoderStepReset = 0,
+    PocsagDecoderStepFoundSync,
+    PocsagDecoderStepFoundPreamble,
+    PocsagDecoderStepMessage,
+} PocsagDecoderStep;
+
+void* subghz_protocol_decoder_pocsag_alloc(SubGhzEnvironment* environment) {
+    UNUSED(environment);
+
+    SubGhzProtocolDecoderPocsag* instance = malloc(sizeof(SubGhzProtocolDecoderPocsag));
+    instance->base.protocol = &subghz_protocol_pocsag;
+    instance->generic.protocol_name = instance->base.protocol->name;
+    instance->msg = furi_string_alloc();
+    instance->done_msg = furi_string_alloc();
+    if(instance->generic.result_msg == NULL) {
+        instance->generic.result_msg = furi_string_alloc();
+    }
+    if(instance->generic.result_ric == NULL) {
+        instance->generic.result_ric = furi_string_alloc();
+    }
+
+    return instance;
+}
+
+void subghz_protocol_decoder_pocsag_free(void* context) {
+    furi_assert(context);
+    SubGhzProtocolDecoderPocsag* instance = context;
+    furi_string_free(instance->msg);
+    furi_string_free(instance->done_msg);
+    free(instance);
+}
+
+void subghz_protocol_decoder_pocsag_reset(void* context) {
+    furi_assert(context);
+    SubGhzProtocolDecoderPocsag* instance = context;
+
+    instance->decoder.parser_step = PocsagDecoderStepReset;
+    instance->decoder.decode_data = 0UL;
+    instance->decoder.decode_count_bit = 0;
+    instance->codeword_idx = 0;
+    instance->char_bits = 0;
+    instance->char_data = 0;
+    furi_string_reset(instance->msg);
+    furi_string_reset(instance->done_msg);
+    furi_string_reset(instance->generic.result_msg);
+    furi_string_reset(instance->generic.result_ric);
+}
+
+static void pocsag_decode_address_word(SubGhzProtocolDecoderPocsag* instance, uint32_t data) {
+    instance->ric = (data >> 13);
+    instance->ric = (instance->ric << 3) | (instance->codeword_idx >> 1);
+    instance->func = (data >> 11) & 0b11;
+}
+
+static bool decode_message_alphanumeric(SubGhzProtocolDecoderPocsag* instance, uint32_t data) {
+    for(uint8_t i = 0; i < 20; i++) {
+        instance->char_data >>= 1;
+        if(data & (1 << 30)) {
+            instance->char_data |= 1 << 6;
+        }
+        instance->char_bits++;
+        if(instance->char_bits == 7) {
+            if(instance->char_data == 0) return false;
+            furi_string_push_back(instance->msg, instance->char_data);
+            instance->char_data = 0;
+            instance->char_bits = 0;
+        }
+        data <<= 1;
+    }
+    return true;
+}
+
+static void decode_message_numeric(SubGhzProtocolDecoderPocsag* instance, uint32_t data) {
+    // 5 groups with 4 bits each
+    uint8_t val;
+    for(uint8_t i = 0; i < 5; i++) {
+        val = (data >> (27 - i * 4)) & 0b1111;
+        // reverse the order of 4 bits
+        val = (val & 0x5) << 1 | (val & 0xA) >> 1;
+        val = (val & 0x3) << 2 | (val & 0xC) >> 2;
+
+        if(val <= 9)
+            val += '0';
+        else
+            val = bcd_chars[val - 10];
+        furi_string_push_back(instance->msg, val);
+    }
+}
+
+// decode message word, maintaining instance state for partial decoding. Return true if more data
+// might follow or false if end of message reached.
+static bool pocsag_decode_message_word(SubGhzProtocolDecoderPocsag* instance, uint32_t data) {
+    switch(instance->func) {
+    case POCSAG_FUNC_ALERT2:
+    case POCSAG_FUNC_ALPHANUM:
+        return decode_message_alphanumeric(instance, data);
+
+    case POCSAG_FUNC_NUM:
+        decode_message_numeric(instance, data);
+        return true;
+    }
+    return false;
+}
+
+// Function called when current message got decoded, but other messages might follow
+static void pocsag_message_done(SubGhzProtocolDecoderPocsag* instance) {
+    // append the message to the long-term storage string
+    furi_string_printf(instance->generic.result_ric, "\e#RIC: %" PRIu32 "\e# | ", instance->ric);
+    furi_string_cat_str(instance->generic.result_ric, func_msg[instance->func]);
+    if(instance->func != POCSAG_FUNC_ALERT1) {
+        furi_string_cat(instance->done_msg, instance->msg);
+    }
+    furi_string_cat_str(instance->done_msg, " ");
+
+    furi_string_cat(instance->generic.result_msg, instance->done_msg);
+
+    // reset the state
+    instance->char_bits = 0;
+    instance->char_data = 0;
+    furi_string_reset(instance->msg);
+}
+
+void subghz_protocol_decoder_pocsag_feed(void* context, bool level, uint32_t duration) {
+    furi_assert(context);
+    SubGhzProtocolDecoderPocsag* instance = context;
+
+    // reset state - waiting for 32 bits of interleaving 1s and 0s
+    if(instance->decoder.parser_step == PocsagDecoderStepReset) {
+        if(DURATION_DIFF(duration, pocsag_const.te_short) < pocsag_const.te_delta) {
+            // POCSAG signals are inverted
+            subghz_protocol_blocks_add_bit(&instance->decoder, !level);
+
+            if(instance->decoder.decode_count_bit == POCSAG_MIN_SYNC_BITS) {
+                instance->decoder.parser_step = PocsagDecoderStepFoundSync;
+            }
+        } else if(instance->decoder.decode_count_bit > 0) {
+            subghz_protocol_decoder_pocsag_reset(context);
+        }
+        return;
+    }
+
+    int bits_count = duration / pocsag_const.te_short;
+    uint32_t extra = duration - pocsag_const.te_short * bits_count;
+
+    if(DURATION_DIFF(extra, pocsag_const.te_short) < pocsag_const.te_delta)
+        bits_count++;
+    else if(extra > pocsag_const.te_delta) {
+        // in non-reset state we faced the error signal - we reached the end of the packet, flush data
+        if(furi_string_size(instance->done_msg) > 0) {
+            if(instance->base.callback)
+                instance->base.callback(&instance->base, instance->base.context);
+        }
+        subghz_protocol_decoder_pocsag_reset(context);
+        return;
+    }
+
+    uint32_t codeword;
+
+    // handle state machine for every incoming bit
+    while(bits_count-- > 0) {
+        subghz_protocol_blocks_add_bit(&instance->decoder, !level);
+
+        switch(instance->decoder.parser_step) {
+        case PocsagDecoderStepFoundSync:
+            if((instance->decoder.decode_data & POCSAG_CW_MASK) == POCSAG_FRAME_SYNC_CODE) {
+                instance->decoder.parser_step = PocsagDecoderStepFoundPreamble;
+                instance->decoder.decode_count_bit = 0;
+                instance->decoder.decode_data = 0UL;
+            }
+            break;
+        case PocsagDecoderStepFoundPreamble:
+            // handle codewords
+            if(instance->decoder.decode_count_bit == POCSAG_CW_BITS) {
+                codeword = (uint32_t)(instance->decoder.decode_data & POCSAG_CW_MASK);
+                switch(codeword) {
+                case POCSAG_IDLE_CODE_WORD:
+                    instance->codeword_idx++;
+                    break;
+                case POCSAG_FRAME_SYNC_CODE:
+                    instance->codeword_idx = 0;
+                    break;
+                default:
+                    // Here we expect only address messages
+                    if(codeword >> 31 == 0) {
+                        pocsag_decode_address_word(instance, codeword);
+                        instance->decoder.parser_step = PocsagDecoderStepMessage;
+                    }
+                    instance->codeword_idx++;
+                }
+                instance->decoder.decode_count_bit = 0;
+                instance->decoder.decode_data = 0UL;
+            }
+            break;
+
+        case PocsagDecoderStepMessage:
+            if(instance->decoder.decode_count_bit == POCSAG_CW_BITS) {
+                codeword = (uint32_t)(instance->decoder.decode_data & POCSAG_CW_MASK);
+                switch(codeword) {
+                case POCSAG_IDLE_CODE_WORD:
+                    // Idle during the message stops the message
+                    instance->codeword_idx++;
+                    instance->decoder.parser_step = PocsagDecoderStepFoundPreamble;
+                    pocsag_message_done(instance);
+                    break;
+                case POCSAG_FRAME_SYNC_CODE:
+                    instance->codeword_idx = 0;
+                    break;
+                default:
+                    // In this state, both address and message words can arrive
+                    if(codeword >> 31 == 0) {
+                        pocsag_message_done(instance);
+                        pocsag_decode_address_word(instance, codeword);
+                    } else {
+                        if(!pocsag_decode_message_word(instance, codeword)) {
+                            instance->decoder.parser_step = PocsagDecoderStepFoundPreamble;
+                            pocsag_message_done(instance);
+                        }
+                    }
+                    instance->codeword_idx++;
+                }
+                instance->decoder.decode_count_bit = 0;
+                instance->decoder.decode_data = 0UL;
+            }
+            break;
+        }
+    }
+}
+
+uint8_t subghz_protocol_decoder_pocsag_get_hash_data(void* context) {
+    furi_assert(context);
+    SubGhzProtocolDecoderPocsag* instance = context;
+    uint8_t hash = 0;
+    for(size_t i = 0; i < furi_string_size(instance->done_msg); i++)
+        hash ^= furi_string_get_char(instance->done_msg, i);
+    return hash;
+}
+
+SubGhzProtocolStatus subghz_protocol_decoder_pocsag_serialize(
+    void* context,
+    FlipperFormat* flipper_format,
+    SubGhzRadioPreset* preset) {
+    furi_assert(context);
+    SubGhzProtocolDecoderPocsag* instance = context;
+    uint32_t msg_len;
+
+    if(SubGhzProtocolStatusOk !=
+       pcsg_block_generic_serialize(&instance->generic, flipper_format, preset))
+        return SubGhzProtocolStatusError;
+
+    msg_len = furi_string_size(instance->done_msg);
+    if(!flipper_format_write_uint32(flipper_format, "MsgLen", &msg_len, 1)) {
+        FURI_LOG_E(TAG, "Error adding MsgLen");
+        return SubGhzProtocolStatusError;
+    }
+
+    uint8_t* s = (uint8_t*)furi_string_get_cstr(instance->done_msg);
+    if(!flipper_format_write_hex(flipper_format, "Msg", s, msg_len)) {
+        FURI_LOG_E(TAG, "Error adding Msg");
+        return SubGhzProtocolStatusError;
+    }
+    return SubGhzProtocolStatusOk;
+}
+
+SubGhzProtocolStatus
+    subghz_protocol_decoder_pocsag_deserialize(void* context, FlipperFormat* flipper_format) {
+    furi_assert(context);
+    SubGhzProtocolDecoderPocsag* instance = context;
+    SubGhzProtocolStatus ret = SubGhzProtocolStatusError;
+    uint32_t msg_len;
+    uint8_t* buf;
+
+    do {
+        if(SubGhzProtocolStatusOk !=
+           pcsg_block_generic_deserialize(&instance->generic, flipper_format)) {
+            break;
+        }
+
+        if(!flipper_format_read_uint32(flipper_format, "MsgLen", &msg_len, 1)) {
+            FURI_LOG_E(TAG, "Missing MsgLen");
+            break;
+        }
+
+        buf = malloc(msg_len);
+        if(!flipper_format_read_hex(flipper_format, "Msg", buf, msg_len)) {
+            FURI_LOG_E(TAG, "Missing Msg");
+            free(buf);
+            break;
+        }
+        furi_string_set_strn(instance->done_msg, (const char*)buf, msg_len);
+        free(buf);
+
+        ret = SubGhzProtocolStatusOk;
+    } while(false);
+    return ret;
+}
+
+void subhz_protocol_decoder_pocsag_get_string(void* context, FuriString* output) {
+    furi_assert(context);
+    SubGhzProtocolDecoderPocsag* instance = context;
+    furi_string_cat_printf(output, "%s\r\n", instance->generic.protocol_name);
+    furi_string_cat(output, instance->done_msg);
+}
+
+const SubGhzProtocolDecoder subghz_protocol_pocsag_decoder = {
+    .alloc = subghz_protocol_decoder_pocsag_alloc,
+    .free = subghz_protocol_decoder_pocsag_free,
+    .reset = subghz_protocol_decoder_pocsag_reset,
+    .feed = subghz_protocol_decoder_pocsag_feed,
+    .get_hash_data = subghz_protocol_decoder_pocsag_get_hash_data,
+    .serialize = subghz_protocol_decoder_pocsag_serialize,
+    .deserialize = subghz_protocol_decoder_pocsag_deserialize,
+    .get_string = subhz_protocol_decoder_pocsag_get_string,
+};
+
+const SubGhzProtocol subghz_protocol_pocsag = {
+    .name = SUBGHZ_PROTOCOL_POCSAG_NAME,
+    .type = SubGhzProtocolTypeStatic,
+    .flag = SubGhzProtocolFlag_FM | SubGhzProtocolFlag_Decodable | SubGhzProtocolFlag_Save |
+            SubGhzProtocolFlag_Load,
+
+    .decoder = &subghz_protocol_pocsag_decoder,
+};

+ 13 - 0
main_apps_sources/pocsag_pager/protocols/pocsag.h

@@ -0,0 +1,13 @@
+#pragma once
+
+#include <lib/subghz/protocols/base.h>
+
+#include <lib/subghz/blocks/const.h>
+#include <lib/subghz/blocks/decoder.h>
+#include <lib/subghz/blocks/encoder.h>
+#include "pcsg_generic.h"
+#include <lib/subghz/blocks/math.h>
+
+#define SUBGHZ_PROTOCOL_POCSAG_NAME "POCSAG"
+
+extern const SubGhzProtocol subghz_protocol_pocsag;

+ 9 - 0
main_apps_sources/pocsag_pager/protocols/protocol_items.c

@@ -0,0 +1,9 @@
+#include "protocol_items.h"
+
+const SubGhzProtocol* pocsag_pager_protocol_registry_items[] = {
+    &subghz_protocol_pocsag,
+};
+
+const SubGhzProtocolRegistry pocsag_pager_protocol_registry = {
+    .items = pocsag_pager_protocol_registry_items,
+    .size = COUNT_OF(pocsag_pager_protocol_registry_items)};

+ 6 - 0
main_apps_sources/pocsag_pager/protocols/protocol_items.h

@@ -0,0 +1,6 @@
+#pragma once
+#include "../pocsag_pager_app_i.h"
+
+#include "pocsag.h"
+
+extern const SubGhzProtocolRegistry pocsag_pager_protocol_registry;

+ 214 - 0
main_apps_sources/pocsag_pager/scenes/pocsag_pager_receiver.c

@@ -0,0 +1,214 @@
+#include "../pocsag_pager_app_i.h"
+#include "../views/pocsag_pager_receiver.h"
+
+static const NotificationSequence subghs_sequence_rx = {
+    &message_green_255,
+
+    &message_vibro_on,
+    &message_note_c6,
+    &message_delay_50,
+    &message_sound_off,
+    &message_vibro_off,
+
+    &message_delay_50,
+    NULL,
+};
+
+static const NotificationSequence subghs_sequence_rx_locked = {
+    &message_green_255,
+
+    &message_display_backlight_on,
+
+    &message_vibro_on,
+    &message_note_c6,
+    &message_delay_50,
+    &message_sound_off,
+    &message_vibro_off,
+
+    &message_delay_500,
+
+    &message_display_backlight_off,
+    NULL,
+};
+
+static void pocsag_pager_scene_receiver_update_statusbar(void* context) {
+    POCSAGPagerApp* app = context;
+    FuriString* history_stat_str;
+    history_stat_str = furi_string_alloc();
+    if(!pcsg_history_get_text_space_left(app->txrx->history, history_stat_str)) {
+        FuriString* frequency_str;
+        FuriString* modulation_str;
+
+        frequency_str = furi_string_alloc();
+        modulation_str = furi_string_alloc();
+
+        pcsg_get_frequency_modulation(app, frequency_str, modulation_str);
+
+        pcsg_view_receiver_add_data_statusbar(
+            app->pcsg_receiver,
+            furi_string_get_cstr(frequency_str),
+            furi_string_get_cstr(modulation_str),
+            furi_string_get_cstr(history_stat_str));
+
+        furi_string_free(frequency_str);
+        furi_string_free(modulation_str);
+    } else {
+        pcsg_view_receiver_add_data_statusbar(
+            app->pcsg_receiver, furi_string_get_cstr(history_stat_str), "", "");
+    }
+    furi_string_free(history_stat_str);
+}
+
+void pocsag_pager_scene_receiver_callback(PCSGCustomEvent event, void* context) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    view_dispatcher_send_custom_event(app->view_dispatcher, event);
+}
+
+static void pocsag_pager_scene_receiver_add_to_history_callback(
+    SubGhzReceiver* receiver,
+    SubGhzProtocolDecoderBase* decoder_base,
+    void* context) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    FuriString* str_buff;
+    str_buff = furi_string_alloc();
+
+    if(pcsg_history_add_to_history(app->txrx->history, decoder_base, app->txrx->preset) ==
+       PCSGHistoryStateAddKeyNewDada) {
+        furi_string_reset(str_buff);
+
+        pcsg_history_get_text_item_menu(
+            app->txrx->history, str_buff, pcsg_history_get_item(app->txrx->history) - 1);
+        pcsg_view_receiver_add_item_to_menu(
+            app->pcsg_receiver,
+            furi_string_get_cstr(str_buff),
+            pcsg_history_get_type_protocol(
+                app->txrx->history, pcsg_history_get_item(app->txrx->history) - 1));
+
+        pocsag_pager_scene_receiver_update_statusbar(app);
+        notification_message(app->notifications, &sequence_blink_green_10);
+        if(app->lock != PCSGLockOn) {
+            notification_message(app->notifications, &subghs_sequence_rx);
+        } else {
+            notification_message(app->notifications, &subghs_sequence_rx_locked);
+        }
+    }
+    subghz_receiver_reset(receiver);
+    furi_string_free(str_buff);
+    app->txrx->rx_key_state = PCSGRxKeyStateAddKey;
+}
+
+void pocsag_pager_scene_receiver_on_enter(void* context) {
+    POCSAGPagerApp* app = context;
+
+    FuriString* str_buff;
+    str_buff = furi_string_alloc();
+
+    if(app->txrx->rx_key_state == PCSGRxKeyStateIDLE) {
+        pcsg_preset_init(app, "FM95", 439987500, NULL, 0);
+        pcsg_history_reset(app->txrx->history);
+        app->txrx->rx_key_state = PCSGRxKeyStateStart;
+    }
+
+    pcsg_view_receiver_set_lock(app->pcsg_receiver, app->lock);
+    pcsg_view_receiver_set_ext_module_state(
+        app->pcsg_receiver, radio_device_loader_is_external(app->txrx->radio_device));
+
+    //Load history to receiver
+    pcsg_view_receiver_exit(app->pcsg_receiver);
+    for(uint8_t i = 0; i < pcsg_history_get_item(app->txrx->history); i++) {
+        furi_string_reset(str_buff);
+        pcsg_history_get_text_item_menu(app->txrx->history, str_buff, i);
+        pcsg_view_receiver_add_item_to_menu(
+            app->pcsg_receiver,
+            furi_string_get_cstr(str_buff),
+            pcsg_history_get_type_protocol(app->txrx->history, i));
+        app->txrx->rx_key_state = PCSGRxKeyStateAddKey;
+    }
+    furi_string_free(str_buff);
+    pocsag_pager_scene_receiver_update_statusbar(app);
+
+    pcsg_view_receiver_set_callback(app->pcsg_receiver, pocsag_pager_scene_receiver_callback, app);
+    subghz_receiver_set_rx_callback(
+        app->txrx->receiver, pocsag_pager_scene_receiver_add_to_history_callback, app);
+
+    if(app->txrx->txrx_state == PCSGTxRxStateRx) {
+        pcsg_rx_end(app);
+    };
+    if((app->txrx->txrx_state == PCSGTxRxStateIDLE) ||
+       (app->txrx->txrx_state == PCSGTxRxStateSleep)) {
+        // Start RX
+        pcsg_begin(
+            app,
+            subghz_setting_get_preset_data_by_name(
+                app->setting, furi_string_get_cstr(app->txrx->preset->name)));
+
+        pcsg_rx(app, app->txrx->preset->frequency);
+    }
+
+    pcsg_view_receiver_set_idx_menu(app->pcsg_receiver, app->txrx->idx_menu_chosen);
+    view_dispatcher_switch_to_view(app->view_dispatcher, POCSAGPagerViewReceiver);
+}
+
+bool pocsag_pager_scene_receiver_on_event(void* context, SceneManagerEvent event) {
+    POCSAGPagerApp* app = context;
+    bool consumed = false;
+    if(event.type == SceneManagerEventTypeCustom) {
+        switch(event.event) {
+        case PCSGCustomEventViewReceiverBack:
+            // Stop CC1101 Rx
+            if(app->txrx->txrx_state == PCSGTxRxStateRx) {
+                pcsg_rx_end(app);
+                pcsg_idle(app);
+            };
+            app->txrx->hopper_state = PCSGHopperStateOFF;
+            app->txrx->idx_menu_chosen = 0;
+            subghz_receiver_set_rx_callback(app->txrx->receiver, NULL, app);
+
+            app->txrx->rx_key_state = PCSGRxKeyStateIDLE;
+            pcsg_preset_init(app, "FM95", 439987500, NULL, 0);
+            scene_manager_search_and_switch_to_previous_scene(
+                app->scene_manager, POCSAGPagerSceneStart);
+            consumed = true;
+            break;
+        case PCSGCustomEventViewReceiverOK:
+            app->txrx->idx_menu_chosen = pcsg_view_receiver_get_idx_menu(app->pcsg_receiver);
+            scene_manager_next_scene(app->scene_manager, POCSAGPagerSceneReceiverInfo);
+            consumed = true;
+            break;
+        case PCSGCustomEventViewReceiverConfig:
+            app->txrx->idx_menu_chosen = pcsg_view_receiver_get_idx_menu(app->pcsg_receiver);
+            scene_manager_next_scene(app->scene_manager, POCSAGPagerSceneReceiverConfig);
+            consumed = true;
+            break;
+        case PCSGCustomEventViewReceiverOffDisplay:
+            notification_message(app->notifications, &sequence_display_backlight_off);
+            consumed = true;
+            break;
+        case PCSGCustomEventViewReceiverUnlock:
+            app->lock = PCSGLockOff;
+            consumed = true;
+            break;
+        default:
+            break;
+        }
+    } else if(event.type == SceneManagerEventTypeTick) {
+        if(app->txrx->hopper_state != PCSGHopperStateOFF) {
+            pcsg_hopper_update(app);
+            pocsag_pager_scene_receiver_update_statusbar(app);
+        }
+        // Get current RSSI
+        float rssi = subghz_devices_get_rssi(app->txrx->radio_device);
+        pcsg_receiver_rssi(app->pcsg_receiver, rssi);
+
+        if(app->txrx->txrx_state == PCSGTxRxStateRx) {
+            notification_message(app->notifications, &sequence_blink_cyan_10);
+        }
+    }
+    return consumed;
+}
+
+void pocsag_pager_scene_receiver_on_exit(void* context) {
+    UNUSED(context);
+}

+ 30 - 0
main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene.c

@@ -0,0 +1,30 @@
+#include "../pocsag_pager_app_i.h"
+
+// Generate scene on_enter handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter,
+void (*const pocsag_pager_scene_on_enter_handlers[])(void*) = {
+#include "pocsag_pager_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Generate scene on_event handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event,
+bool (*const pocsag_pager_scene_on_event_handlers[])(void* context, SceneManagerEvent event) = {
+#include "pocsag_pager_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Generate scene on_exit handlers array
+#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit,
+void (*const pocsag_pager_scene_on_exit_handlers[])(void* context) = {
+#include "pocsag_pager_scene_config.h"
+};
+#undef ADD_SCENE
+
+// Initialize scene handlers configuration structure
+const SceneManagerHandlers pocsag_pager_scene_handlers = {
+    .on_enter_handlers = pocsag_pager_scene_on_enter_handlers,
+    .on_event_handlers = pocsag_pager_scene_on_event_handlers,
+    .on_exit_handlers = pocsag_pager_scene_on_exit_handlers,
+    .scene_num = POCSAGPagerSceneNum,
+};

+ 29 - 0
main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene.h

@@ -0,0 +1,29 @@
+#pragma once
+
+#include <gui/scene_manager.h>
+
+// Generate scene id and total number
+#define ADD_SCENE(prefix, name, id) POCSAGPagerScene##id,
+typedef enum {
+#include "pocsag_pager_scene_config.h"
+    POCSAGPagerSceneNum,
+} POCSAGPagerScene;
+#undef ADD_SCENE
+
+extern const SceneManagerHandlers pocsag_pager_scene_handlers;
+
+// Generate scene on_enter handlers declaration
+#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*);
+#include "pocsag_pager_scene_config.h"
+#undef ADD_SCENE
+
+// Generate scene on_event handlers declaration
+#define ADD_SCENE(prefix, name, id) \
+    bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event);
+#include "pocsag_pager_scene_config.h"
+#undef ADD_SCENE
+
+// Generate scene on_exit handlers declaration
+#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context);
+#include "pocsag_pager_scene_config.h"
+#undef ADD_SCENE

+ 74 - 0
main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_about.c

@@ -0,0 +1,74 @@
+#include "../pocsag_pager_app_i.h"
+#include "../helpers/pocsag_pager_types.h"
+
+void pocsag_pager_scene_about_widget_callback(GuiButtonType result, InputType type, void* context) {
+    POCSAGPagerApp* app = context;
+    if(type == InputTypeShort) {
+        view_dispatcher_send_custom_event(app->view_dispatcher, result);
+    }
+}
+
+void pocsag_pager_scene_about_on_enter(void* context) {
+    POCSAGPagerApp* app = context;
+
+    FuriString* temp_str;
+    temp_str = furi_string_alloc();
+    furi_string_printf(temp_str, "\e#%s\n", "Information");
+
+    furi_string_cat_printf(temp_str, "Version: %s\n", PCSG_VERSION_APP);
+    furi_string_cat_printf(temp_str, "Developed by:\n%s\n\n", PCSG_DEVELOPED);
+    furi_string_cat_printf(temp_str, "Github: %s\n\n", PCSG_GITHUB);
+
+    furi_string_cat_printf(temp_str, "\e#%s\n", "Description");
+    furi_string_cat_printf(temp_str, "Receiving POCSAG Pager \nmessages\n\n");
+
+    furi_string_cat_printf(temp_str, "Supported protocols:\n");
+    size_t i = 0;
+    const char* protocol_name =
+        subghz_environment_get_protocol_name_registry(app->txrx->environment, i++);
+    do {
+        furi_string_cat_printf(temp_str, "%s\n", protocol_name);
+        protocol_name = subghz_environment_get_protocol_name_registry(app->txrx->environment, i++);
+    } while(protocol_name != NULL);
+
+    widget_add_text_box_element(
+        app->widget,
+        0,
+        0,
+        128,
+        14,
+        AlignCenter,
+        AlignBottom,
+        "\e#\e!                                                      \e!\n",
+        false);
+    widget_add_text_box_element(
+        app->widget,
+        0,
+        2,
+        128,
+        14,
+        AlignCenter,
+        AlignBottom,
+        "\e#\e!        POCSAG Pager       \e!\n",
+        false);
+    widget_add_text_scroll_element(app->widget, 0, 16, 128, 50, furi_string_get_cstr(temp_str));
+    furi_string_free(temp_str);
+
+    view_dispatcher_switch_to_view(app->view_dispatcher, POCSAGPagerViewWidget);
+}
+
+bool pocsag_pager_scene_about_on_event(void* context, SceneManagerEvent event) {
+    POCSAGPagerApp* app = context;
+    bool consumed = false;
+    UNUSED(app);
+    UNUSED(event);
+
+    return consumed;
+}
+
+void pocsag_pager_scene_about_on_exit(void* context) {
+    POCSAGPagerApp* app = context;
+
+    // Clear views
+    widget_reset(app->widget);
+}

+ 5 - 0
main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_config.h

@@ -0,0 +1,5 @@
+ADD_SCENE(pocsag_pager, start, Start)
+ADD_SCENE(pocsag_pager, about, About)
+ADD_SCENE(pocsag_pager, receiver, Receiver)
+ADD_SCENE(pocsag_pager, receiver_config, ReceiverConfig)
+ADD_SCENE(pocsag_pager, receiver_info, ReceiverInfo)

+ 221 - 0
main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_receiver_config.c

@@ -0,0 +1,221 @@
+#include "../pocsag_pager_app_i.h"
+
+enum PCSGSettingIndex {
+    PCSGSettingIndexFrequency,
+    PCSGSettingIndexHopping,
+    PCSGSettingIndexModulation,
+    PCSGSettingIndexLock,
+};
+
+#define HOPPING_COUNT 2
+const char* const hopping_text[HOPPING_COUNT] = {
+    "OFF",
+    "ON",
+};
+const uint32_t hopping_value[HOPPING_COUNT] = {
+    PCSGHopperStateOFF,
+    PCSGHopperStateRunnig,
+};
+
+uint8_t pocsag_pager_scene_receiver_config_next_frequency(const uint32_t value, void* context) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    uint8_t index = 0;
+    for(uint8_t i = 0; i < subghz_setting_get_frequency_count(app->setting); i++) {
+        if(value == subghz_setting_get_frequency(app->setting, i)) {
+            index = i;
+            break;
+        } else {
+            index = subghz_setting_get_frequency_default_index(app->setting);
+        }
+    }
+    return index;
+}
+
+uint8_t pocsag_pager_scene_receiver_config_next_preset(const char* preset_name, void* context) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    uint8_t index = 0;
+    for(uint8_t i = 0; i < subghz_setting_get_preset_count(app->setting); i++) {
+        if(!strcmp(subghz_setting_get_preset_name(app->setting, i), preset_name)) {
+            index = i;
+            break;
+        } else {
+            //  index = subghz_setting_get_frequency_default_index(app ->setting);
+        }
+    }
+    return index;
+}
+
+uint8_t pocsag_pager_scene_receiver_config_hopper_value_index(
+    const uint32_t value,
+    const uint32_t values[],
+    uint8_t values_count,
+    void* context) {
+    furi_assert(context);
+    UNUSED(values_count);
+    POCSAGPagerApp* app = context;
+
+    if(value == values[0]) {
+        return 0;
+    } else {
+        variable_item_set_current_value_text(
+            (VariableItem*)scene_manager_get_scene_state(
+                app->scene_manager, POCSAGPagerSceneReceiverConfig),
+            " -----");
+        return 1;
+    }
+}
+
+static void pocsag_pager_scene_receiver_config_set_frequency(VariableItem* item) {
+    POCSAGPagerApp* app = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+
+    if(app->txrx->hopper_state == PCSGHopperStateOFF) {
+        char text_buf[10] = {0};
+        snprintf(
+            text_buf,
+            sizeof(text_buf),
+            "%lu.%02lu",
+            subghz_setting_get_frequency(app->setting, index) / 1000000,
+            (subghz_setting_get_frequency(app->setting, index) % 1000000) / 10000);
+        variable_item_set_current_value_text(item, text_buf);
+        app->txrx->preset->frequency = subghz_setting_get_frequency(app->setting, index);
+    } else {
+        variable_item_set_current_value_index(
+            item, subghz_setting_get_frequency_default_index(app->setting));
+    }
+}
+
+static void pocsag_pager_scene_receiver_config_set_preset(VariableItem* item) {
+    POCSAGPagerApp* app = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+    variable_item_set_current_value_text(
+        item, subghz_setting_get_preset_name(app->setting, index));
+    pcsg_preset_init(
+        app,
+        subghz_setting_get_preset_name(app->setting, index),
+        app->txrx->preset->frequency,
+        subghz_setting_get_preset_data(app->setting, index),
+        subghz_setting_get_preset_data_size(app->setting, index));
+}
+
+static void pocsag_pager_scene_receiver_config_set_hopping_running(VariableItem* item) {
+    POCSAGPagerApp* app = variable_item_get_context(item);
+    uint8_t index = variable_item_get_current_value_index(item);
+
+    variable_item_set_current_value_text(item, hopping_text[index]);
+    if(hopping_value[index] == PCSGHopperStateOFF) {
+        char text_buf[10] = {0};
+        snprintf(
+            text_buf,
+            sizeof(text_buf),
+            "%lu.%02lu",
+            subghz_setting_get_default_frequency(app->setting) / 1000000,
+            (subghz_setting_get_default_frequency(app->setting) % 1000000) / 10000);
+        variable_item_set_current_value_text(
+            (VariableItem*)scene_manager_get_scene_state(
+                app->scene_manager, POCSAGPagerSceneReceiverConfig),
+            text_buf);
+        app->txrx->preset->frequency = subghz_setting_get_default_frequency(app->setting);
+        variable_item_set_current_value_index(
+            (VariableItem*)scene_manager_get_scene_state(
+                app->scene_manager, POCSAGPagerSceneReceiverConfig),
+            subghz_setting_get_frequency_default_index(app->setting));
+    } else {
+        variable_item_set_current_value_text(
+            (VariableItem*)scene_manager_get_scene_state(
+                app->scene_manager, POCSAGPagerSceneReceiverConfig),
+            " -----");
+        variable_item_set_current_value_index(
+            (VariableItem*)scene_manager_get_scene_state(
+                app->scene_manager, POCSAGPagerSceneReceiverConfig),
+            subghz_setting_get_frequency_default_index(app->setting));
+    }
+
+    app->txrx->hopper_state = hopping_value[index];
+}
+
+static void
+    pocsag_pager_scene_receiver_config_var_list_enter_callback(void* context, uint32_t index) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    if(index == PCSGSettingIndexLock) {
+        view_dispatcher_send_custom_event(app->view_dispatcher, PCSGCustomEventSceneSettingLock);
+    }
+}
+
+void pocsag_pager_scene_receiver_config_on_enter(void* context) {
+    POCSAGPagerApp* app = context;
+    VariableItem* item;
+    uint8_t value_index;
+
+    item = variable_item_list_add(
+        app->variable_item_list,
+        "Frequency:",
+        subghz_setting_get_frequency_count(app->setting),
+        pocsag_pager_scene_receiver_config_set_frequency,
+        app);
+    value_index =
+        pocsag_pager_scene_receiver_config_next_frequency(app->txrx->preset->frequency, app);
+    scene_manager_set_scene_state(
+        app->scene_manager, POCSAGPagerSceneReceiverConfig, (uint32_t)item);
+    variable_item_set_current_value_index(item, value_index);
+    char text_buf[10] = {0};
+    snprintf(
+        text_buf,
+        sizeof(text_buf),
+        "%lu.%02lu",
+        subghz_setting_get_frequency(app->setting, value_index) / 1000000,
+        (subghz_setting_get_frequency(app->setting, value_index) % 1000000) / 10000);
+    variable_item_set_current_value_text(item, text_buf);
+
+    item = variable_item_list_add(
+        app->variable_item_list,
+        "Hopping:",
+        HOPPING_COUNT,
+        pocsag_pager_scene_receiver_config_set_hopping_running,
+        app);
+    value_index = pocsag_pager_scene_receiver_config_hopper_value_index(
+        app->txrx->hopper_state, hopping_value, HOPPING_COUNT, app);
+    variable_item_set_current_value_index(item, value_index);
+    variable_item_set_current_value_text(item, hopping_text[value_index]);
+
+    item = variable_item_list_add(
+        app->variable_item_list,
+        "Modulation:",
+        subghz_setting_get_preset_count(app->setting),
+        pocsag_pager_scene_receiver_config_set_preset,
+        app);
+    value_index = pocsag_pager_scene_receiver_config_next_preset(
+        furi_string_get_cstr(app->txrx->preset->name), app);
+    variable_item_set_current_value_index(item, value_index);
+    variable_item_set_current_value_text(
+        item, subghz_setting_get_preset_name(app->setting, value_index));
+
+    variable_item_list_add(app->variable_item_list, "Lock Keyboard", 1, NULL, NULL);
+    variable_item_list_set_enter_callback(
+        app->variable_item_list, pocsag_pager_scene_receiver_config_var_list_enter_callback, app);
+
+    view_dispatcher_switch_to_view(app->view_dispatcher, POCSAGPagerViewVariableItemList);
+}
+
+bool pocsag_pager_scene_receiver_config_on_event(void* context, SceneManagerEvent event) {
+    POCSAGPagerApp* app = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == PCSGCustomEventSceneSettingLock) {
+            app->lock = PCSGLockOn;
+            scene_manager_previous_scene(app->scene_manager);
+            consumed = true;
+        }
+    }
+    return consumed;
+}
+
+void pocsag_pager_scene_receiver_config_on_exit(void* context) {
+    POCSAGPagerApp* app = context;
+    variable_item_list_set_selected_item(app->variable_item_list, 0);
+    variable_item_list_reset(app->variable_item_list);
+}

+ 50 - 0
main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_receiver_info.c

@@ -0,0 +1,50 @@
+#include "../pocsag_pager_app_i.h"
+#include "../views/pocsag_pager_receiver.h"
+
+void pocsag_pager_scene_receiver_info_callback(PCSGCustomEvent event, void* context) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+    view_dispatcher_send_custom_event(app->view_dispatcher, event);
+}
+
+static void pocsag_pager_scene_receiver_info_add_to_history_callback(
+    SubGhzReceiver* receiver,
+    SubGhzProtocolDecoderBase* decoder_base,
+    void* context) {
+    furi_assert(context);
+    POCSAGPagerApp* app = context;
+
+    if(pcsg_history_add_to_history(app->txrx->history, decoder_base, app->txrx->preset) ==
+       PCSGHistoryStateAddKeyUpdateData) {
+        pcsg_view_receiver_info_update(
+            app->pcsg_receiver_info,
+            pcsg_history_get_raw_data(app->txrx->history, app->txrx->idx_menu_chosen));
+        subghz_receiver_reset(receiver);
+
+        notification_message(app->notifications, &sequence_blink_green_10);
+        app->txrx->rx_key_state = PCSGRxKeyStateAddKey;
+    }
+}
+
+void pocsag_pager_scene_receiver_info_on_enter(void* context) {
+    POCSAGPagerApp* app = context;
+
+    subghz_receiver_set_rx_callback(
+        app->txrx->receiver, pocsag_pager_scene_receiver_info_add_to_history_callback, app);
+    pcsg_view_receiver_info_update(
+        app->pcsg_receiver_info,
+        pcsg_history_get_raw_data(app->txrx->history, app->txrx->idx_menu_chosen));
+    view_dispatcher_switch_to_view(app->view_dispatcher, POCSAGPagerViewReceiverInfo);
+}
+
+bool pocsag_pager_scene_receiver_info_on_event(void* context, SceneManagerEvent event) {
+    POCSAGPagerApp* app = context;
+    bool consumed = false;
+    UNUSED(app);
+    UNUSED(event);
+    return consumed;
+}
+
+void pocsag_pager_scene_receiver_info_on_exit(void* context) {
+    UNUSED(context);
+}

+ 58 - 0
main_apps_sources/pocsag_pager/scenes/pocsag_pager_scene_start.c

@@ -0,0 +1,58 @@
+#include "../pocsag_pager_app_i.h"
+
+typedef enum {
+    SubmenuIndexPOCSAGPagerReceiver,
+    SubmenuIndexPOCSAGPagerAbout,
+} SubmenuIndex;
+
+void pocsag_pager_scene_start_submenu_callback(void* context, uint32_t index) {
+    POCSAGPagerApp* app = context;
+    view_dispatcher_send_custom_event(app->view_dispatcher, index);
+}
+
+void pocsag_pager_scene_start_on_enter(void* context) {
+    UNUSED(context);
+    POCSAGPagerApp* app = context;
+    Submenu* submenu = app->submenu;
+
+    submenu_add_item(
+        submenu,
+        "Receive messages",
+        SubmenuIndexPOCSAGPagerReceiver,
+        pocsag_pager_scene_start_submenu_callback,
+        app);
+    submenu_add_item(
+        submenu,
+        "About",
+        SubmenuIndexPOCSAGPagerAbout,
+        pocsag_pager_scene_start_submenu_callback,
+        app);
+
+    submenu_set_selected_item(
+        submenu, scene_manager_get_scene_state(app->scene_manager, POCSAGPagerSceneStart));
+
+    view_dispatcher_switch_to_view(app->view_dispatcher, POCSAGPagerViewSubmenu);
+}
+
+bool pocsag_pager_scene_start_on_event(void* context, SceneManagerEvent event) {
+    POCSAGPagerApp* app = context;
+    bool consumed = false;
+
+    if(event.type == SceneManagerEventTypeCustom) {
+        if(event.event == SubmenuIndexPOCSAGPagerAbout) {
+            scene_manager_next_scene(app->scene_manager, POCSAGPagerSceneAbout);
+            consumed = true;
+        } else if(event.event == SubmenuIndexPOCSAGPagerReceiver) {
+            scene_manager_next_scene(app->scene_manager, POCSAGPagerSceneReceiver);
+            consumed = true;
+        }
+        scene_manager_set_scene_state(app->scene_manager, POCSAGPagerSceneStart, event.event);
+    }
+
+    return consumed;
+}
+
+void pocsag_pager_scene_start_on_exit(void* context) {
+    POCSAGPagerApp* app = context;
+    submenu_reset(app->submenu);
+}

+ 478 - 0
main_apps_sources/pocsag_pager/views/pocsag_pager_receiver.c

@@ -0,0 +1,478 @@
+#include "pocsag_pager_receiver.h"
+#include "../pocsag_pager_app_i.h"
+#include <pocsag_pager_icons.h>
+#include <math.h>
+
+#include <input/input.h>
+#include <gui/elements.h>
+#include <m-array.h>
+
+#define FRAME_HEIGHT 12
+#define MAX_LEN_PX 112
+#define MENU_ITEMS 4u
+#define UNLOCK_CNT 3
+
+#define SUBGHZ_RAW_THRESHOLD_MIN -90.0f
+
+typedef struct {
+    FuriString* item_str;
+    uint8_t type;
+} PCSGReceiverMenuItem;
+
+ARRAY_DEF(PCSGReceiverMenuItemArray, PCSGReceiverMenuItem, M_POD_OPLIST)
+
+#define M_OPL_PCSGReceiverMenuItemArray_t() ARRAY_OPLIST(PCSGReceiverMenuItemArray, M_POD_OPLIST)
+
+struct PCSGReceiverHistory {
+    PCSGReceiverMenuItemArray_t data;
+};
+
+typedef struct PCSGReceiverHistory PCSGReceiverHistory;
+
+static const Icon* ReceiverItemIcons[] = {
+    [SubGhzProtocolTypeUnknown] = &I_Quest_7x8,
+    [SubGhzProtocolTypeStatic] = &I_Message_8x7,
+    [SubGhzProtocolTypeDynamic] = &I_Lock_7x8,
+};
+
+typedef enum {
+    PCSGReceiverBarShowDefault,
+    PCSGReceiverBarShowLock,
+    PCSGReceiverBarShowToUnlockPress,
+    PCSGReceiverBarShowUnlock,
+} PCSGReceiverBarShow;
+
+struct PCSGReceiver {
+    PCSGLock lock;
+    uint8_t lock_count;
+    FuriTimer* timer;
+    View* view;
+    PCSGReceiverCallback callback;
+    void* context;
+};
+
+typedef struct {
+    FuriString* frequency_str;
+    FuriString* preset_str;
+    FuriString* history_stat_str;
+    PCSGReceiverHistory* history;
+    uint16_t idx;
+    uint16_t list_offset;
+    uint16_t history_item;
+    PCSGReceiverBarShow bar_show;
+    uint8_t u_rssi;
+    bool ext_module;
+} PCSGReceiverModel;
+
+void pcsg_receiver_rssi(PCSGReceiver* instance, float rssi) {
+    furi_assert(instance);
+    with_view_model(
+        instance->view,
+        PCSGReceiverModel * model,
+        {
+            if(rssi < SUBGHZ_RAW_THRESHOLD_MIN) {
+                model->u_rssi = 0;
+            } else {
+                model->u_rssi = (uint8_t)(rssi - SUBGHZ_RAW_THRESHOLD_MIN);
+            }
+        },
+        true);
+}
+
+void pcsg_view_receiver_set_lock(PCSGReceiver* pcsg_receiver, PCSGLock lock) {
+    furi_assert(pcsg_receiver);
+    pcsg_receiver->lock_count = 0;
+    if(lock == PCSGLockOn) {
+        pcsg_receiver->lock = lock;
+        with_view_model(
+            pcsg_receiver->view,
+            PCSGReceiverModel * model,
+            { model->bar_show = PCSGReceiverBarShowLock; },
+            true);
+        furi_timer_start(pcsg_receiver->timer, pdMS_TO_TICKS(1000));
+    } else {
+        with_view_model(
+            pcsg_receiver->view,
+            PCSGReceiverModel * model,
+            { model->bar_show = PCSGReceiverBarShowDefault; },
+            true);
+    }
+}
+
+void pcsg_view_receiver_set_ext_module_state(PCSGReceiver* pcsg_receiver, bool is_external) {
+    furi_assert(pcsg_receiver);
+    with_view_model(
+        pcsg_receiver->view, PCSGReceiverModel * model, { model->ext_module = is_external; }, true);
+}
+
+void pcsg_view_receiver_set_callback(
+    PCSGReceiver* pcsg_receiver,
+    PCSGReceiverCallback callback,
+    void* context) {
+    furi_assert(pcsg_receiver);
+    furi_assert(callback);
+    pcsg_receiver->callback = callback;
+    pcsg_receiver->context = context;
+}
+
+static void pcsg_view_receiver_update_offset(PCSGReceiver* pcsg_receiver) {
+    furi_assert(pcsg_receiver);
+
+    with_view_model(
+        pcsg_receiver->view,
+        PCSGReceiverModel * model,
+        {
+            size_t history_item = model->history_item;
+            uint16_t bounds = history_item > 3 ? 2 : history_item;
+
+            if(history_item > 3 && model->idx >= (int16_t)(history_item - 1)) {
+                model->list_offset = model->idx - 3;
+            } else if(model->list_offset < model->idx - bounds) {
+                model->list_offset =
+                    CLAMP(model->list_offset + 1, (int16_t)(history_item - bounds), 0);
+            } else if(model->list_offset > model->idx - bounds) {
+                model->list_offset = CLAMP(model->idx - 1, (int16_t)(history_item - bounds), 0);
+            }
+        },
+        true);
+}
+
+void pcsg_view_receiver_add_item_to_menu(
+    PCSGReceiver* pcsg_receiver,
+    const char* name,
+    uint8_t type) {
+    furi_assert(pcsg_receiver);
+    with_view_model(
+        pcsg_receiver->view,
+        PCSGReceiverModel * model,
+        {
+            PCSGReceiverMenuItem* item_menu =
+                PCSGReceiverMenuItemArray_push_raw(model->history->data);
+            item_menu->item_str = furi_string_alloc_set(name);
+            item_menu->type = type;
+            if((model->idx == model->history_item - 1)) {
+                model->history_item++;
+                model->idx++;
+            } else {
+                model->history_item++;
+            }
+        },
+        true);
+    pcsg_view_receiver_update_offset(pcsg_receiver);
+}
+
+void pcsg_view_receiver_add_data_statusbar(
+    PCSGReceiver* pcsg_receiver,
+    const char* frequency_str,
+    const char* preset_str,
+    const char* history_stat_str) {
+    furi_assert(pcsg_receiver);
+    with_view_model(
+        pcsg_receiver->view,
+        PCSGReceiverModel * model,
+        {
+            furi_string_set_str(model->frequency_str, frequency_str);
+            furi_string_set_str(model->preset_str, preset_str);
+            furi_string_set_str(model->history_stat_str, history_stat_str);
+        },
+        true);
+}
+
+static void pcsg_view_receiver_draw_frame(Canvas* canvas, uint16_t idx, bool scrollbar) {
+    canvas_set_color(canvas, ColorBlack);
+    canvas_draw_box(canvas, 0, 0 + idx * FRAME_HEIGHT, scrollbar ? 122 : 127, FRAME_HEIGHT);
+
+    canvas_set_color(canvas, ColorWhite);
+    canvas_draw_dot(canvas, 0, 0 + idx * FRAME_HEIGHT);
+    canvas_draw_dot(canvas, 1, 0 + idx * FRAME_HEIGHT);
+    canvas_draw_dot(canvas, 0, (0 + idx * FRAME_HEIGHT) + 1);
+
+    canvas_draw_dot(canvas, 0, (0 + idx * FRAME_HEIGHT) + 11);
+    canvas_draw_dot(canvas, scrollbar ? 121 : 126, 0 + idx * FRAME_HEIGHT);
+    canvas_draw_dot(canvas, scrollbar ? 121 : 126, (0 + idx * FRAME_HEIGHT) + 11);
+}
+
+static void pcsg_view_rssi_draw(Canvas* canvas, PCSGReceiverModel* model) {
+    for(uint8_t i = 1; i < model->u_rssi; i++) {
+        if(i % 5) {
+            canvas_draw_dot(canvas, 46 + i, 50);
+            canvas_draw_dot(canvas, 47 + i, 51);
+            canvas_draw_dot(canvas, 46 + i, 52);
+        }
+    }
+}
+
+void pcsg_view_receiver_draw(Canvas* canvas, PCSGReceiverModel* model) {
+    canvas_clear(canvas);
+    canvas_set_color(canvas, ColorBlack);
+    canvas_set_font(canvas, FontSecondary);
+
+    elements_button_left(canvas, "Config");
+    //canvas_draw_line(canvas, 46, 51, 125, 51);
+
+    bool scrollbar = model->history_item > 4;
+    FuriString* str_buff;
+    str_buff = furi_string_alloc();
+
+    PCSGReceiverMenuItem* item_menu;
+
+    for(size_t i = 0; i < MIN(model->history_item, MENU_ITEMS); ++i) {
+        size_t idx = CLAMP((uint16_t)(i + model->list_offset), model->history_item, 0);
+        item_menu = PCSGReceiverMenuItemArray_get(model->history->data, idx);
+        furi_string_set(str_buff, item_menu->item_str);
+        furi_string_replace_all(str_buff, "#", "");
+        elements_string_fit_width(canvas, str_buff, scrollbar ? MAX_LEN_PX - 7 : MAX_LEN_PX);
+        if(model->idx == idx) {
+            pcsg_view_receiver_draw_frame(canvas, i, scrollbar);
+        } else {
+            canvas_set_color(canvas, ColorBlack);
+        }
+        canvas_draw_icon(canvas, 4, 2 + i * FRAME_HEIGHT, ReceiverItemIcons[item_menu->type]);
+        canvas_draw_str(canvas, 15, 9 + i * FRAME_HEIGHT, furi_string_get_cstr(str_buff));
+        furi_string_reset(str_buff);
+    }
+    if(scrollbar) {
+        elements_scrollbar_pos(canvas, 128, 0, 49, model->idx, model->history_item);
+    }
+    furi_string_free(str_buff);
+
+    canvas_set_color(canvas, ColorBlack);
+
+    if(model->history_item == 0) {
+        canvas_draw_icon(canvas, 0, 0, model->ext_module ? &I_Fishing_123x52 : &I_Scanning_123x52);
+        canvas_set_font(canvas, FontPrimary);
+        canvas_draw_str(canvas, 63, 46, "Scanning...");
+        canvas_set_font(canvas, FontSecondary);
+        canvas_draw_str(canvas, 44, 10, model->ext_module ? "Ext" : "Int");
+    }
+
+    // Draw RSSI
+    pcsg_view_rssi_draw(canvas, model);
+
+    switch(model->bar_show) {
+    case PCSGReceiverBarShowLock:
+        canvas_draw_icon(canvas, 64, 55, &I_Lock_7x8);
+        canvas_draw_str(canvas, 74, 62, "Locked");
+        break;
+    case PCSGReceiverBarShowToUnlockPress:
+        canvas_draw_str(canvas, 44, 62, furi_string_get_cstr(model->frequency_str));
+        canvas_draw_str(canvas, 79, 62, furi_string_get_cstr(model->preset_str));
+        canvas_draw_str(canvas, 96, 62, furi_string_get_cstr(model->history_stat_str));
+        canvas_set_font(canvas, FontSecondary);
+        elements_bold_rounded_frame(canvas, 14, 8, 99, 48);
+        elements_multiline_text(canvas, 65, 26, "To unlock\npress:");
+        canvas_draw_icon(canvas, 65, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 80, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 95, 42, &I_Pin_back_arrow_10x8);
+        canvas_draw_icon(canvas, 16, 13, &I_WarningDolphin_45x42);
+        canvas_draw_dot(canvas, 17, 61);
+        break;
+    case PCSGReceiverBarShowUnlock:
+        canvas_draw_icon(canvas, 64, 55, &I_Unlock_7x8);
+        canvas_draw_str(canvas, 74, 62, "Unlocked");
+        break;
+    default:
+        canvas_draw_str(canvas, 44, 62, furi_string_get_cstr(model->frequency_str));
+        canvas_draw_str(canvas, 79, 62, furi_string_get_cstr(model->preset_str));
+        canvas_draw_str(canvas, 96, 62, furi_string_get_cstr(model->history_stat_str));
+        break;
+    }
+}
+
+static void pcsg_view_receiver_timer_callback(void* context) {
+    furi_assert(context);
+    PCSGReceiver* pcsg_receiver = context;
+    with_view_model(
+        pcsg_receiver->view,
+        PCSGReceiverModel * model,
+        { model->bar_show = PCSGReceiverBarShowDefault; },
+        true);
+    if(pcsg_receiver->lock_count < UNLOCK_CNT) {
+        pcsg_receiver->callback(PCSGCustomEventViewReceiverOffDisplay, pcsg_receiver->context);
+    } else {
+        pcsg_receiver->lock = PCSGLockOff;
+        pcsg_receiver->callback(PCSGCustomEventViewReceiverUnlock, pcsg_receiver->context);
+    }
+    pcsg_receiver->lock_count = 0;
+}
+
+bool pcsg_view_receiver_input(InputEvent* event, void* context) {
+    furi_assert(context);
+    PCSGReceiver* pcsg_receiver = context;
+
+    if(pcsg_receiver->lock == PCSGLockOn) {
+        with_view_model(
+            pcsg_receiver->view,
+            PCSGReceiverModel * model,
+            { model->bar_show = PCSGReceiverBarShowToUnlockPress; },
+            true);
+        if(pcsg_receiver->lock_count == 0) {
+            furi_timer_start(pcsg_receiver->timer, pdMS_TO_TICKS(1000));
+        }
+        if(event->key == InputKeyBack && event->type == InputTypeShort) {
+            pcsg_receiver->lock_count++;
+        }
+        if(pcsg_receiver->lock_count >= UNLOCK_CNT) {
+            pcsg_receiver->callback(PCSGCustomEventViewReceiverUnlock, pcsg_receiver->context);
+            with_view_model(
+                pcsg_receiver->view,
+                PCSGReceiverModel * model,
+                { model->bar_show = PCSGReceiverBarShowUnlock; },
+                true);
+            pcsg_receiver->lock = PCSGLockOff;
+            furi_timer_start(pcsg_receiver->timer, pdMS_TO_TICKS(650));
+        }
+
+        return true;
+    }
+
+    if(event->key == InputKeyBack && event->type == InputTypeShort) {
+        pcsg_receiver->callback(PCSGCustomEventViewReceiverBack, pcsg_receiver->context);
+    } else if(
+        event->key == InputKeyUp &&
+        (event->type == InputTypeShort || event->type == InputTypeRepeat)) {
+        with_view_model(
+            pcsg_receiver->view,
+            PCSGReceiverModel * model,
+            {
+                if(model->idx != 0) model->idx--;
+            },
+            true);
+    } else if(
+        event->key == InputKeyDown &&
+        (event->type == InputTypeShort || event->type == InputTypeRepeat)) {
+        with_view_model(
+            pcsg_receiver->view,
+            PCSGReceiverModel * model,
+            {
+                if(model->history_item && model->idx != model->history_item - 1) model->idx++;
+            },
+            true);
+    } else if(event->key == InputKeyLeft && event->type == InputTypeShort) {
+        pcsg_receiver->callback(PCSGCustomEventViewReceiverConfig, pcsg_receiver->context);
+    } else if(event->key == InputKeyOk && event->type == InputTypeShort) {
+        with_view_model(
+            pcsg_receiver->view,
+            PCSGReceiverModel * model,
+            {
+                if(model->history_item != 0) {
+                    pcsg_receiver->callback(PCSGCustomEventViewReceiverOK, pcsg_receiver->context);
+                }
+            },
+            false);
+    }
+
+    pcsg_view_receiver_update_offset(pcsg_receiver);
+
+    return true;
+}
+
+void pcsg_view_receiver_enter(void* context) {
+    furi_assert(context);
+}
+
+void pcsg_view_receiver_exit(void* context) {
+    furi_assert(context);
+    PCSGReceiver* pcsg_receiver = context;
+    with_view_model(
+        pcsg_receiver->view,
+        PCSGReceiverModel * model,
+        {
+            furi_string_reset(model->frequency_str);
+            furi_string_reset(model->preset_str);
+            furi_string_reset(model->history_stat_str);
+                for
+                    M_EACH(item_menu, model->history->data, PCSGReceiverMenuItemArray_t) {
+                        furi_string_free(item_menu->item_str);
+                        item_menu->type = 0;
+                    }
+                PCSGReceiverMenuItemArray_reset(model->history->data);
+                model->idx = 0;
+                model->list_offset = 0;
+                model->history_item = 0;
+        },
+        false);
+    furi_timer_stop(pcsg_receiver->timer);
+}
+
+PCSGReceiver* pcsg_view_receiver_alloc() {
+    PCSGReceiver* pcsg_receiver = malloc(sizeof(PCSGReceiver));
+
+    // View allocation and configuration
+    pcsg_receiver->view = view_alloc();
+
+    pcsg_receiver->lock = PCSGLockOff;
+    pcsg_receiver->lock_count = 0;
+    view_allocate_model(pcsg_receiver->view, ViewModelTypeLocking, sizeof(PCSGReceiverModel));
+    view_set_context(pcsg_receiver->view, pcsg_receiver);
+    view_set_draw_callback(pcsg_receiver->view, (ViewDrawCallback)pcsg_view_receiver_draw);
+    view_set_input_callback(pcsg_receiver->view, pcsg_view_receiver_input);
+    view_set_enter_callback(pcsg_receiver->view, pcsg_view_receiver_enter);
+    view_set_exit_callback(pcsg_receiver->view, pcsg_view_receiver_exit);
+
+    with_view_model(
+        pcsg_receiver->view,
+        PCSGReceiverModel * model,
+        {
+            model->frequency_str = furi_string_alloc();
+            model->preset_str = furi_string_alloc();
+            model->history_stat_str = furi_string_alloc();
+            model->bar_show = PCSGReceiverBarShowDefault;
+            model->history = malloc(sizeof(PCSGReceiverHistory));
+            PCSGReceiverMenuItemArray_init(model->history->data);
+        },
+        true);
+    pcsg_receiver->timer =
+        furi_timer_alloc(pcsg_view_receiver_timer_callback, FuriTimerTypeOnce, pcsg_receiver);
+    return pcsg_receiver;
+}
+
+void pcsg_view_receiver_free(PCSGReceiver* pcsg_receiver) {
+    furi_assert(pcsg_receiver);
+
+    with_view_model(
+        pcsg_receiver->view,
+        PCSGReceiverModel * model,
+        {
+            furi_string_free(model->frequency_str);
+            furi_string_free(model->preset_str);
+            furi_string_free(model->history_stat_str);
+                for
+                    M_EACH(item_menu, model->history->data, PCSGReceiverMenuItemArray_t) {
+                        furi_string_free(item_menu->item_str);
+                        item_menu->type = 0;
+                    }
+                PCSGReceiverMenuItemArray_clear(model->history->data);
+                free(model->history);
+        },
+        false);
+    furi_timer_free(pcsg_receiver->timer);
+    view_free(pcsg_receiver->view);
+    free(pcsg_receiver);
+}
+
+View* pcsg_view_receiver_get_view(PCSGReceiver* pcsg_receiver) {
+    furi_assert(pcsg_receiver);
+    return pcsg_receiver->view;
+}
+
+uint16_t pcsg_view_receiver_get_idx_menu(PCSGReceiver* pcsg_receiver) {
+    furi_assert(pcsg_receiver);
+    uint32_t idx = 0;
+    with_view_model(
+        pcsg_receiver->view, PCSGReceiverModel * model, { idx = model->idx; }, false);
+    return idx;
+}
+
+void pcsg_view_receiver_set_idx_menu(PCSGReceiver* pcsg_receiver, uint16_t idx) {
+    furi_assert(pcsg_receiver);
+    with_view_model(
+        pcsg_receiver->view,
+        PCSGReceiverModel * model,
+        {
+            model->idx = idx;
+            if(model->idx > 2) model->list_offset = idx - 2;
+        },
+        true);
+    pcsg_view_receiver_update_offset(pcsg_receiver);
+}

+ 43 - 0
main_apps_sources/pocsag_pager/views/pocsag_pager_receiver.h

@@ -0,0 +1,43 @@
+#pragma once
+
+#include <gui/view.h>
+#include "../helpers/pocsag_pager_types.h"
+#include "../helpers/pocsag_pager_event.h"
+
+typedef struct PCSGReceiver PCSGReceiver;
+
+typedef void (*PCSGReceiverCallback)(PCSGCustomEvent event, void* context);
+
+void pcsg_receiver_rssi(PCSGReceiver* instance, float rssi);
+
+void pcsg_view_receiver_set_lock(PCSGReceiver* pcsg_receiver, PCSGLock keyboard);
+
+void pcsg_view_receiver_set_ext_module_state(PCSGReceiver* pcsg_receiver, bool is_external);
+
+void pcsg_view_receiver_set_callback(
+    PCSGReceiver* pcsg_receiver,
+    PCSGReceiverCallback callback,
+    void* context);
+
+PCSGReceiver* pcsg_view_receiver_alloc();
+
+void pcsg_view_receiver_free(PCSGReceiver* pcsg_receiver);
+
+View* pcsg_view_receiver_get_view(PCSGReceiver* pcsg_receiver);
+
+void pcsg_view_receiver_add_data_statusbar(
+    PCSGReceiver* pcsg_receiver,
+    const char* frequency_str,
+    const char* preset_str,
+    const char* history_stat_str);
+
+void pcsg_view_receiver_add_item_to_menu(
+    PCSGReceiver* pcsg_receiver,
+    const char* name,
+    uint8_t type);
+
+uint16_t pcsg_view_receiver_get_idx_menu(PCSGReceiver* pcsg_receiver);
+
+void pcsg_view_receiver_set_idx_menu(PCSGReceiver* pcsg_receiver, uint16_t idx);
+
+void pcsg_view_receiver_exit(void* context);

+ 137 - 0
main_apps_sources/pocsag_pager/views/pocsag_pager_receiver_info.c

@@ -0,0 +1,137 @@
+#include "pocsag_pager_receiver.h"
+#include "../pocsag_pager_app_i.h"
+#include "pocsag_pager_icons.h"
+#include "../protocols/pcsg_generic.h"
+#include <input/input.h>
+#include <gui/elements.h>
+
+#define abs(x) ((x) > 0 ? (x) : -(x))
+
+struct PCSGReceiverInfo {
+    View* view;
+};
+
+typedef struct {
+    FuriString* protocol_name;
+    PCSGBlockGeneric* generic;
+} PCSGReceiverInfoModel;
+
+void pcsg_view_receiver_info_update(PCSGReceiverInfo* pcsg_receiver_info, FlipperFormat* fff) {
+    furi_assert(pcsg_receiver_info);
+    furi_assert(fff);
+
+    with_view_model(
+        pcsg_receiver_info->view,
+        PCSGReceiverInfoModel * model,
+        {
+            flipper_format_rewind(fff);
+            flipper_format_read_string(fff, "Protocol", model->protocol_name);
+
+            pcsg_block_generic_deserialize(model->generic, fff);
+        },
+        true);
+}
+
+void pcsg_view_receiver_info_draw(Canvas* canvas, PCSGReceiverInfoModel* model) {
+    canvas_clear(canvas);
+    canvas_set_color(canvas, ColorBlack);
+    canvas_set_font(canvas, FontSecondary);
+    if(model->generic->result_ric != NULL) {
+        elements_text_box(
+            canvas,
+            0,
+            0,
+            128,
+            64,
+            AlignLeft,
+            AlignTop,
+            furi_string_get_cstr(model->generic->result_ric),
+            false);
+    }
+    if(model->generic->result_msg != NULL) {
+        elements_text_box(
+            canvas,
+            0,
+            12,
+            128,
+            64,
+            AlignLeft,
+            AlignTop,
+            furi_string_get_cstr(model->generic->result_msg),
+            false);
+    }
+}
+
+bool pcsg_view_receiver_info_input(InputEvent* event, void* context) {
+    furi_assert(context);
+    //PCSGReceiverInfo* pcsg_receiver_info = context;
+
+    if(event->key == InputKeyBack) {
+        return false;
+    }
+
+    return true;
+}
+
+void pcsg_view_receiver_info_enter(void* context) {
+    furi_assert(context);
+}
+
+void pcsg_view_receiver_info_exit(void* context) {
+    furi_assert(context);
+    PCSGReceiverInfo* pcsg_receiver_info = context;
+
+    with_view_model(
+        pcsg_receiver_info->view,
+        PCSGReceiverInfoModel * model,
+        { furi_string_reset(model->protocol_name); },
+        false);
+}
+
+PCSGReceiverInfo* pcsg_view_receiver_info_alloc() {
+    PCSGReceiverInfo* pcsg_receiver_info = malloc(sizeof(PCSGReceiverInfo));
+
+    // View allocation and configuration
+    pcsg_receiver_info->view = view_alloc();
+
+    view_allocate_model(
+        pcsg_receiver_info->view, ViewModelTypeLocking, sizeof(PCSGReceiverInfoModel));
+    view_set_context(pcsg_receiver_info->view, pcsg_receiver_info);
+    view_set_draw_callback(
+        pcsg_receiver_info->view, (ViewDrawCallback)pcsg_view_receiver_info_draw);
+    view_set_input_callback(pcsg_receiver_info->view, pcsg_view_receiver_info_input);
+    view_set_enter_callback(pcsg_receiver_info->view, pcsg_view_receiver_info_enter);
+    view_set_exit_callback(pcsg_receiver_info->view, pcsg_view_receiver_info_exit);
+
+    with_view_model(
+        pcsg_receiver_info->view,
+        PCSGReceiverInfoModel * model,
+        {
+            model->generic = malloc(sizeof(PCSGBlockGeneric));
+            model->protocol_name = furi_string_alloc();
+        },
+        true);
+
+    return pcsg_receiver_info;
+}
+
+void pcsg_view_receiver_info_free(PCSGReceiverInfo* pcsg_receiver_info) {
+    furi_assert(pcsg_receiver_info);
+
+    with_view_model(
+        pcsg_receiver_info->view,
+        PCSGReceiverInfoModel * model,
+        {
+            furi_string_free(model->protocol_name);
+            free(model->generic);
+        },
+        false);
+
+    view_free(pcsg_receiver_info->view);
+    free(pcsg_receiver_info);
+}
+
+View* pcsg_view_receiver_info_get_view(PCSGReceiverInfo* pcsg_receiver_info) {
+    furi_assert(pcsg_receiver_info);
+    return pcsg_receiver_info->view;
+}

+ 16 - 0
main_apps_sources/pocsag_pager/views/pocsag_pager_receiver_info.h

@@ -0,0 +1,16 @@
+#pragma once
+
+#include <gui/view.h>
+#include "../helpers/pocsag_pager_types.h"
+#include "../helpers/pocsag_pager_event.h"
+#include <lib/flipper_format/flipper_format.h>
+
+typedef struct PCSGReceiverInfo PCSGReceiverInfo;
+
+void pcsg_view_receiver_info_update(PCSGReceiverInfo* pcsg_receiver_info, FlipperFormat* fff);
+
+PCSGReceiverInfo* pcsg_view_receiver_info_alloc();
+
+void pcsg_view_receiver_info_free(PCSGReceiverInfo* pcsg_receiver_info);
+
+View* pcsg_view_receiver_info_get_view(PCSGReceiverInfo* pcsg_receiver_info);

+ 24 - 0
main_apps_sources/protoview/LICENSE

@@ -0,0 +1,24 @@
+Copyright (c) 2022-2023 Salvatore Sanfilippo <antirez at gmail dot com>
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice,
+  this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 159 - 0
main_apps_sources/protoview/README.md

@@ -0,0 +1,159 @@
+ProtoView is a digital signal detection, visualization, editing and reply tool for the Flipper Zero. The Flipper default application, called Subghz, is able to identify certain RF protocols, but when the exact protocol is not implemented (and there are many undocumented and unimplemented ones, such as the ones in use in TPMS systems, car keys and many others), the curious person is left wondering what the device is sending at all. Using ProtoView she or he can visualize the high and low pulses  
+This is often enough to make an initial idea about the encoding used
+and if the selected modulation is correct. For example, in the signal above
+you can see a set of regular pulses and gaps used for synchronization, and then
+a sequence of bits encoded in Manchester - https://en.wikipedia.org/wiki/Manchester_code line code. If you study these things for five minutes, you'll find yourself able to decode the bits with naked eyes.
+
+## Decoding capabilities
+
+Other than showing the raw signal, ProtoView is able to decode a few interesting protocols:
+
+* TPMS sensors: Renault, Toyota, Schrader, Citroen, Ford.
+* Microchip HSC200/300/301 Keeloq protocol.
+* Oregon thermometer protocol 2.
+* PT2262, SC5262 based remotes.
+* ... more will be implemented soon, hopefully. Send PRs
+
+
+The app implements a framework that makes adding and experimenting with new
+protocols very simple. Check the (protocols) directory to see how the
+API works, or read the full documentation at the end of (README) file.
+The gist of it is that the decoder receives the signal already converted into
+a bitmap, where each bit represents a short pulse duration. Then there are
+functions to seek specific sync/preamble sequences inside the bitmap, to decode
+from different line codes, to compute checksums and so forth.
+
+## Signals transmission capabilities
+
+Once ProtoView decodes a given message, it is able to *resample* it
+in pulses and gaps of the theoretical duration, and send the signal again
+via the Flipper TX capabilities. The captured signal can be sent
+to different frequencies and modulations than the ones it was captured
+from.
+
+For selected protocols, that implement the message creation methods,
+ProtoView is also able to edit the message received, modify fields,
+and finally re-detect the new produced signal and resend it. Signals
+can also be produced from scratch, by setting all the fields to appropriate
+values.
+
+## A well-documented app for the Flipper
+
+The secondary goal of ProtoView is to provide a well-documented application for the Flipper (even if ProtoView is a pretty atypical application: it doesn't make use of the standard widgets and other abstractions provided by the framework).
+Most apps dealing with the *subghz subsystem* of the Flipper (the abstraction used to work with the CC1101 chip - https://www.ti.com/product/CC1101) tend to be complicated and completely undocumented.
+Unfortunately, this is also true for the firmware of the device.
+It's a shame, because especially in the case of code that talks with hardware peripherals there are tons of assumptions and hard-gained lessons that can only be captured by comments and are in the code only implicitly - http://antirez.com/news/124
+
+However, the Flipper firmware source code is well written even if it
+lacks comments and documentation (and sometimes makes use of abstractions more convoluted than needed), so it is possible to make some ideas of how things work just grepping inside. In order to develop this application, I ended reading most parts of the firmware of the device.
+
+## Detection algorithm
+
+In order to detect and show unknown signals, the application attempts to understand if the samples obtained by the Flipper API (a series of pulses that are high
+or low, and with different duration in microseconds) look like belonging to
+a legitimate signal, and aren't just noise.
+
+We can't make assumptions about
+the encoding and the data rate of the communication, so we use a simple
+but relatively effective algorithm. As we check the signal, we try to detect
+long parts of it that are composed of pulses roughly classifiable into
+a maximum of three different duration classes, plus or minus a given percentage.
+Most encodings are somewhat self-clocked, so they tend to have just two or
+three classes of pulse lengths.
+
+However, often, pulses of the same theoretical
+length have slightly different lengths in the case of high and low level
+(RF on or off), so the detector classifies them separately for robustness.
+
+Once the raw signal is detected, the registered protocol decoders are called
+against it, in the hope some of the decoders will make sense of the signal.
+
+# Usage
+
+In the main screen, the application shows the longest coherent signal detected so far. The user can switch to other views pressing the LEFT and RIGHT keys. The BACK key will return back to the main screen. Long pressing BACK will quit the application.
+
+## Main raw signal screen
+
+* A long press of the OK button resets the current signal, in order to capture a new one.
+* The UP and DOWN buttons change the scale. Default is 100us per pixel, but it will be adapted to the signal just captured.
+* A long press of the LEFT and RIGHT keys will pan the signal, to see what was transmitted before/after the current shown range.
+* A short press to OK will recenter the signal and set the scale back to the default for the specific pulse duration detected.
+
+Under the detected sequence, you will see a small triangle marking a
+specific sample. This mark means that the sequence looked coherent up
+to that point, and starting from there it could be just noise. However the
+signal decoders will not get just up to this point, but will get more:
+sometimes the low level detector can't make sense of a signal that the
+protocol-specific decoder can understand fully.
+
+If the protocol is decoded, the bottom-left corner of the screen
+will show the name of the protocol, and going in the next screen
+with the right arrow will show information about the decoded signal.
+
+In the bottom-right corner the application displays an amount of time
+in microseconds. This is the average length of the shortest pulse length
+detected among the three classes. Usually the *data rate* of the protocol
+is something like (1000000/this-number*2), but it depends on the encoding
+and could actually be (1000000/this-number*N) with (N > 2) (here 1000000
+is the number of microseconds in one second, and N is the number of clock
+cycles needed to represent a bit).
+
+## Info screen
+
+If a signal was detected, the info view will show the details about the signal. If the signal has more data that a single screen can fit, pressing OK will show the next fields. Pressing DOWN will go to a sub-view with an oscilloscope-alike representation of the signal, from there you can:
+
+1. Resend the signal, by pressing OK.
+2. Save the signal as (.sub) file, by long pressing OK.
+
+When resending, you can select a different frequency and modulation if you
+wish.
+
+## Frequency and modulation screen
+
+In this view you can just set the frequency and modulation you want to use.
+There are special modulations for TPMS signals: they need an higher data
+rate.
+
+* Many cheap remotes (gate openers, remotes, ...) are on the 433.92Mhz or nearby and use OOK modulation.
+* Weather stations are often too in the 433.92Mhz OOK.
+* For car keys, try 433.92 OOK650 and 868.35 Mhz in OOK or 2FSK.
+* For TPMS try 433.92 in TPMS1 or TPMS2 modulations (FSK and OOK custom modulations optimized for these signals, that have a relatively high data rate).
+
+## Signal creator
+
+In this view, you can do two things:
+
+1. Select one of the protocols supporting message creation, and create a signal from scratch.
+2. If there is already a detected signal, you can modify the signal.
+
+This is how it works:
+
+1. Select one of the protocols (the one of the currently detected signal will be already provided as default, if any, and if it supports message creation).
+2. Fill the fields. Use LEFT and RIGHT to change the values of integers, or just press OK and enter the new value with the Fliper keyboard widget.
+3. When you are done, long press OK to build the message. Then press BACK in order to see it.
+4. Go to the INFO view, and then DOWN to the signal sending/saving subview in order to send or save it.
+
+## Direct sampling screen
+
+This final screen shows in real time the high and low level that the Flipper
+RF chip, the CC1101, is receiving. This will makes very easy to understand
+if a given frequency is targeted by something other than noise. This mode is
+fun to watch, resembling an old CRT TV set.
+
+# License
+
+The code is released under the BSD license.
+
+# Disclaimer
+
+This application is only provided as an educational tool. The author is not liable in case the application is used to reverse engineer protocols protected by IP or for any other illegal purpose.
+
+# Credits
+
+A big thank you to the RTL433 author, Benjamin Larsson - https://github.com/merbanan I used the code and tools he developed in many ways:
+* To capture TPMS data with rtl433 and save to a file, to later play the IQ files and speedup the development.
+* As a sourve of documentation for protocols.
+* As an awesome way to visualize and understand protocols, via these great web tools - https://triq.org/
+* To have tons of fun with RTLSDR in general, now and in the past.
+
+The application icon was designed by Stefano Liuzzo.

+ 400 - 0
main_apps_sources/protoview/app.c

@@ -0,0 +1,400 @@
+/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved
+ * See the LICENSE file for information about the license. */
+
+#include "app.h"
+
+RawSamplesBuffer *RawSamples, *DetectedSamples;
+extern const SubGhzProtocolRegistry protoview_protocol_registry;
+
+/* Draw some text with a border. If the outside color is black and the inside
+ * color is white, it just writes the border of the text, but the function can
+ * also be used to write a bold variation of the font setting both the
+ * colors to black, or alternatively to write a black text with a white
+ * border so that it is visible if there are black stuff on the background. */
+/* The callback actually just passes the control to the actual active
+ * view callback, after setting up basic stuff like cleaning the screen
+ * and setting color to black. */
+static void render_callback(Canvas* const canvas, void* ctx) {
+    ProtoViewApp* app = ctx;
+    furi_mutex_acquire(app->view_updating_mutex, FuriWaitForever);
+
+    /* Clear screen. */
+    canvas_set_color(canvas, ColorWhite);
+    canvas_draw_box(canvas, 0, 0, 127, 63);
+    canvas_set_color(canvas, ColorBlack);
+    canvas_set_font(canvas, FontPrimary);
+
+    /* Call who is in charge right now. */
+    switch(app->current_view) {
+    case ViewRawPulses:
+        render_view_raw_pulses(canvas, app);
+        break;
+    case ViewInfo:
+        render_view_info(canvas, app);
+        break;
+    case ViewFrequencySettings:
+    case ViewModulationSettings:
+        render_view_settings(canvas, app);
+        break;
+    case ViewDirectSampling:
+        render_view_direct_sampling(canvas, app);
+        break;
+    case ViewBuildMessage:
+        render_view_build_message(canvas, app);
+        break;
+    default:
+        furi_crash(TAG "Invalid view selected");
+        break;
+    }
+
+    /* Draw the alert box if set. */
+    ui_draw_alert_if_needed(canvas, app);
+    furi_mutex_release(app->view_updating_mutex);
+}
+
+/* Here all we do is putting the events into the queue that will be handled
+ * in the while() loop of the app entry point function. */
+static void input_callback(InputEvent* input_event, void* ctx) {
+    ProtoViewApp* app = ctx;
+    furi_message_queue_put(app->event_queue, input_event, FuriWaitForever);
+}
+
+/* Called to switch view (when left/right is pressed). Handles
+ * changing the current view ID and calling the enter/exit view
+ * callbacks if needed.
+ *
+ * The 'switchto' parameter can be the identifier of a view, or the
+ * special views ViewGoNext and ViewGoPrev in order to move to
+ * the logical next/prev view. */
+static void app_switch_view(ProtoViewApp* app, ProtoViewCurrentView switchto) {
+    furi_mutex_acquire(app->view_updating_mutex, FuriWaitForever);
+
+    /* Switch to the specified view. */
+    ProtoViewCurrentView old = app->current_view;
+    if(switchto == ViewGoNext) {
+        app->current_view++;
+        if(app->current_view == ViewLast) app->current_view = 0;
+    } else if(switchto == ViewGoPrev) {
+        if(app->current_view == 0)
+            app->current_view = ViewLast - 1;
+        else
+            app->current_view--;
+    } else {
+        app->current_view = switchto;
+    }
+    ProtoViewCurrentView new = app->current_view;
+
+    /* Call the exit view callbacks. */
+    if(old == ViewDirectSampling) view_exit_direct_sampling(app);
+    if(old == ViewBuildMessage) view_exit_build_message(app);
+    if(old == ViewInfo) view_exit_info(app);
+    /* The frequency/modulation settings are actually a single view:
+     * as long as the user stays between the two modes of this view we
+     * don't need to call the exit-view callback. */
+    if((old == ViewFrequencySettings && new != ViewModulationSettings) ||
+       (old == ViewModulationSettings && new != ViewFrequencySettings))
+        view_exit_settings(app);
+
+    /* Reset the view private data each time, before calling the enter
+     * callbacks that may want to setup some state. */
+    memset(app->view_privdata, 0, PROTOVIEW_VIEW_PRIVDATA_LEN);
+
+    /* Call the enter view callbacks after all the exit callback
+     * of the old view was already executed. */
+    if(new == ViewDirectSampling) view_enter_direct_sampling(app);
+    if(new == ViewBuildMessage) view_enter_build_message(app);
+
+    /* Set the current subview of the view we just left to zero. This is
+     * the main subview of the old view. When we re-enter the view we are
+     * lefting, we want to see the main thing again. */
+    app->current_subview[old] = 0;
+
+    /* If there is an alert on screen, dismiss it: if the user is
+     * switching view she already read it. */
+    ui_dismiss_alert(app);
+    furi_mutex_release(app->view_updating_mutex);
+}
+
+/* Allocate the application state and initialize a number of stuff.
+ * This is called in the entry point to create the application state. */
+ProtoViewApp* protoview_app_alloc() {
+    furi_hal_power_suppress_charge_enter();
+
+    ProtoViewApp* app = malloc(sizeof(ProtoViewApp));
+
+    // Init shared data structures
+    RawSamples = raw_samples_alloc();
+    DetectedSamples = raw_samples_alloc();
+
+    //init setting
+    app->setting = subghz_setting_alloc();
+    subghz_setting_load(app->setting, EXT_PATH("subghz/assets/setting_user"));
+
+    // GUI
+    app->gui = furi_record_open(RECORD_GUI);
+    app->notification = furi_record_open(RECORD_NOTIFICATION);
+    app->view_port = view_port_alloc();
+    view_port_draw_callback_set(app->view_port, render_callback, app);
+    view_port_input_callback_set(app->view_port, input_callback, app);
+    gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
+    app->event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
+    app->view_dispatcher = NULL;
+    app->text_input = NULL;
+    app->show_text_input = false;
+    app->alert_dismiss_time = 0;
+    app->current_view = ViewRawPulses;
+    app->view_updating_mutex = furi_mutex_alloc(FuriMutexTypeNormal);
+    for(int j = 0; j < ViewLast; j++) app->current_subview[j] = 0;
+    app->direct_sampling_enabled = false;
+    app->view_privdata = malloc(PROTOVIEW_VIEW_PRIVDATA_LEN);
+    memset(app->view_privdata, 0, PROTOVIEW_VIEW_PRIVDATA_LEN);
+
+    // Signal found and visualization defaults
+    app->signal_bestlen = 0;
+    app->signal_last_scan_idx = 0;
+    app->signal_decoded = false;
+    app->us_scale = PROTOVIEW_RAW_VIEW_DEFAULT_SCALE;
+    app->signal_offset = 0;
+    app->msg_info = NULL;
+
+    // Init Worker & Protocol
+    app->txrx = malloc(sizeof(ProtoViewTxRx));
+
+    /* Setup rx state. */
+    app->txrx->freq_mod_changed = false;
+    app->txrx->debug_timer_sampling = false;
+    app->txrx->last_g0_change_time = DWT->CYCCNT;
+    app->txrx->last_g0_value = false;
+
+    app->frequency = subghz_setting_get_default_frequency(app->setting);
+    app->modulation = 0; /* Defaults to ProtoViewModulations[0]. */
+
+    // Init & set radio_device
+    subghz_devices_init();
+    app->radio_device =
+        radio_device_loader_set(app->radio_device, SubGhzRadioDeviceTypeExternalCC1101);
+
+    subghz_devices_reset(app->radio_device);
+    subghz_devices_idle(app->radio_device);
+
+    app->running = 1;
+
+    return app;
+}
+
+/* Free what the application allocated. It is not clear to me if the
+ * Flipper OS, once the application exits, will be able to reclaim space
+ * even if we forget to free something here. */
+void protoview_app_free(ProtoViewApp* app) {
+    furi_assert(app);
+
+    subghz_devices_sleep(app->radio_device);
+    radio_device_loader_end(app->radio_device);
+
+    subghz_devices_deinit();
+
+    // View related.
+    view_port_enabled_set(app->view_port, false);
+    gui_remove_view_port(app->gui, app->view_port);
+    view_port_free(app->view_port);
+    furi_record_close(RECORD_GUI);
+    furi_record_close(RECORD_NOTIFICATION);
+    furi_message_queue_free(app->event_queue);
+    furi_mutex_free(app->view_updating_mutex);
+    app->gui = NULL;
+
+    // Frequency setting.
+    subghz_setting_free(app->setting);
+
+    // Worker stuff.
+    free(app->txrx);
+
+    // Raw samples buffers.
+    raw_samples_free(RawSamples);
+    raw_samples_free(DetectedSamples);
+    furi_hal_power_suppress_charge_exit();
+
+    free(app);
+}
+
+/* Called periodically. Do signal processing here. Data we process here
+ * will be later displayed by the render callback. The side effect of this
+ * function is to scan for signals and set DetectedSamples. */
+static void timer_callback(void* ctx) {
+    ProtoViewApp* app = ctx;
+    uint32_t delta, lastidx = app->signal_last_scan_idx;
+
+    /* scan_for_signal(), called by this function, deals with a
+     * circular buffer. To never miss anything, even if a signal spawns
+     * cross-boundaries, it is enough if we scan each time the buffer fills
+     * for 50% more compared to the last scan. Thanks to this check we
+     * can avoid scanning too many times to just find the same data. */
+    if(lastidx < RawSamples->idx) {
+        delta = RawSamples->idx - lastidx;
+    } else {
+        delta = RawSamples->total - lastidx + RawSamples->idx;
+    }
+    if(delta < RawSamples->total / 2) return;
+    app->signal_last_scan_idx = RawSamples->idx;
+    scan_for_signal(app, RawSamples, ProtoViewModulations[app->modulation].duration_filter);
+}
+
+/* This is the navigation callback we use in the view dispatcher used
+ * to display the "text input" widget, that is the keyboard to get text.
+ * The text input view is implemented to ignore the "back" short press,
+ * so the event is not consumed and is handled by the view dispatcher.
+ * However the view dispatcher implementation has the strange behavior that
+ * if no navigation callback is set, it will not stop when handling back.
+ *
+ * We just need a dummy callback returning false. We believe the
+ * implementation should be changed and if no callback is set, it should be
+ * the same as returning false. */
+static bool keyboard_view_dispatcher_navigation_callback(void* ctx) {
+    UNUSED(ctx);
+    return false;
+}
+
+/* App entry point, as specified in application.fam. */
+int32_t protoview_app_entry(void* p) {
+    UNUSED(p);
+    ProtoViewApp* app = protoview_app_alloc();
+
+    /* Create a timer. We do data analysis in the callback. */
+    FuriTimer* timer = furi_timer_alloc(timer_callback, FuriTimerTypePeriodic, app);
+    furi_timer_start(timer, furi_kernel_get_tick_frequency() / 8);
+
+    /* Start listening to signals immediately. */
+    radio_begin(app);
+    radio_rx(app);
+
+    /* This is the main event loop: here we get the events that are pushed
+     * in the queue by input_callback(), and process them one after the
+     * other. The timeout is 100 milliseconds, so if not input is received
+     * before such time, we exit the queue_get() function and call
+     * view_port_update() in order to refresh our screen content. */
+    InputEvent input;
+    while(app->running) {
+        FuriStatus qstat = furi_message_queue_get(app->event_queue, &input, 100);
+        if(qstat == FuriStatusOk) {
+            if(DEBUG_MSG)
+                FURI_LOG_E(TAG, "Main Loop - Input: type %d key %u", input.type, input.key);
+
+            /* Handle navigation here. Then handle view-specific inputs
+             * in the view specific handling function. */
+            if(input.type == InputTypeShort && input.key == InputKeyBack) {
+                if(app->current_view != ViewRawPulses) {
+                    /* If this is not the main app view, go there. */
+                    app_switch_view(app, ViewRawPulses);
+                } else {
+                    /* If we are in the main app view, warn the user
+                     * they needs to long press to really quit. */
+                    ui_show_alert(app, "Long press to exit", 1000);
+                }
+            } else if(input.type == InputTypeLong && input.key == InputKeyBack) {
+                app->running = 0;
+            } else if(
+                input.type == InputTypeShort && input.key == InputKeyRight &&
+                ui_get_current_subview(app) == 0) {
+                /* Go to the next view. */
+                app_switch_view(app, ViewGoNext);
+            } else if(
+                input.type == InputTypeShort && input.key == InputKeyLeft &&
+                ui_get_current_subview(app) == 0) {
+                /* Go to the previous view. */
+                app_switch_view(app, ViewGoPrev);
+            } else {
+                /* This is where we pass the control to the currently
+                 * active view input processing. */
+                switch(app->current_view) {
+                case ViewRawPulses:
+                    process_input_raw_pulses(app, input);
+                    break;
+                case ViewInfo:
+                    process_input_info(app, input);
+                    break;
+                case ViewFrequencySettings:
+                case ViewModulationSettings:
+                    process_input_settings(app, input);
+                    break;
+                case ViewDirectSampling:
+                    process_input_direct_sampling(app, input);
+                    break;
+                case ViewBuildMessage:
+                    process_input_build_message(app, input);
+                    break;
+                default:
+                    furi_crash(TAG "Invalid view selected");
+                    break;
+                }
+            }
+        } else {
+            /* Useful to understand if the app is still alive when it
+             * does not respond because of bugs. */
+            if(DEBUG_MSG) {
+                static int c = 0;
+                c++;
+                if(!(c % 20)) FURI_LOG_E(TAG, "Loop timeout");
+            }
+        }
+        if(app->show_text_input) {
+            /* Remove our viewport: we need to use a view dispatcher
+             * in order to show the standard Flipper keyboard. */
+            gui_remove_view_port(app->gui, app->view_port);
+
+            /* Allocate a view dispatcher, add a text input view to it,
+             * and activate it. */
+            app->view_dispatcher = view_dispatcher_alloc();
+            view_dispatcher_enable_queue(app->view_dispatcher);
+            /* We need to set a navigation callback for the view dispatcher
+             * otherwise when the user presses back on the keyboard to
+             * abort, the dispatcher will not stop. */
+            view_dispatcher_set_navigation_event_callback(
+                app->view_dispatcher, keyboard_view_dispatcher_navigation_callback);
+            app->text_input = text_input_alloc();
+            view_dispatcher_set_event_callback_context(app->view_dispatcher, app);
+            view_dispatcher_add_view(
+                app->view_dispatcher, 0, text_input_get_view(app->text_input));
+            view_dispatcher_switch_to_view(app->view_dispatcher, 0);
+
+            /* Setup the text input view. The different parameters are set
+             * in the app structure by the view that wanted to show the
+             * input text. The callback, buffer and buffer len must be set.  */
+            text_input_set_header_text(app->text_input, "Save signal filename");
+            text_input_set_result_callback(
+                app->text_input,
+                app->text_input_done_callback,
+                app,
+                app->text_input_buffer,
+                app->text_input_buffer_len,
+                false);
+
+            /* Run the dispatcher with the keyboard. */
+            view_dispatcher_attach_to_gui(
+                app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
+            view_dispatcher_run(app->view_dispatcher);
+
+            /* Undo all it: remove the view from the dispatcher, free it
+             * so that it removes itself from the current gui, finally
+             * restore our viewport. */
+            view_dispatcher_remove_view(app->view_dispatcher, 0);
+            text_input_free(app->text_input);
+            view_dispatcher_free(app->view_dispatcher);
+            app->view_dispatcher = NULL;
+            gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
+            app->show_text_input = false;
+        } else {
+            view_port_update(app->view_port);
+        }
+    }
+
+    /* App no longer running. Shut down and free. */
+    if(app->txrx->txrx_state == TxRxStateRx) {
+        FURI_LOG_E(TAG, "Putting CC1101 to sleep before exiting.");
+        radio_rx_end(app);
+        radio_sleep(app);
+    }
+
+    furi_timer_free(timer);
+    protoview_app_free(app);
+    return 0;
+}

+ 377 - 0
main_apps_sources/protoview/app.h

@@ -0,0 +1,377 @@
+/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved
+ * See the LICENSE file for information about the license. */
+
+#pragma once
+
+#include <furi.h>
+#include <furi_hal.h>
+#include <input/input.h>
+#include <gui/gui.h>
+#include <stdlib.h>
+#include <gui/gui.h>
+#include <gui/view_dispatcher.h>
+#include <gui/scene_manager.h>
+#include <gui/modules/submenu.h>
+#include <gui/modules/variable_item_list.h>
+#include <gui/modules/widget.h>
+#include <gui/modules/text_input.h>
+#include <notification/notification_messages.h>
+#include <lib/subghz/subghz_setting.h>
+#include <lib/subghz/registry.h>
+#include "raw_samples.h"
+#include "helpers/radio_device_loader.h"
+
+#define TAG "ProtoView"
+#define PROTOVIEW_RAW_VIEW_DEFAULT_SCALE 100 // 100us is 1 pixel by default
+#define BITMAP_SEEK_NOT_FOUND UINT32_MAX // Returned by function as sentinel
+#define PROTOVIEW_VIEW_PRIVDATA_LEN 64 // View specific private data len
+
+#define DEBUG_MSG 0
+
+/* Forward declarations. */
+
+typedef struct ProtoViewApp ProtoViewApp;
+typedef struct ProtoViewMsgInfo ProtoViewMsgInfo;
+typedef struct ProtoViewFieldSet ProtoViewFieldSet;
+typedef struct ProtoViewDecoder ProtoViewDecoder;
+
+/* ============================== enumerations ============================== */
+
+/* Subghz system state */
+typedef enum {
+    TxRxStateIDLE,
+    TxRxStateRx,
+    TxRxStateTx,
+    TxRxStateSleep,
+} TxRxState;
+
+/* Currently active view. */
+typedef enum {
+    ViewRawPulses,
+    ViewInfo,
+    ViewFrequencySettings,
+    ViewModulationSettings,
+    ViewBuildMessage,
+    ViewDirectSampling,
+    ViewLast, /* Just a sentinel to wrap around. */
+
+    /* The following are special views that are not iterated, but
+     * have meaning for the API. */
+    ViewGoNext,
+    ViewGoPrev,
+} ProtoViewCurrentView;
+
+/* ================================== RX/TX ================================= */
+
+typedef struct {
+    const char* name; // Name to show to the user.
+    const char* id; // Identifier in the Flipper API/file.
+    FuriHalSubGhzPreset preset; // The preset ID.
+    uint8_t* custom; /* If not null, a set of registers for
+                                       the CC1101, specifying a custom preset.*/
+    uint32_t duration_filter; /* Ignore pulses and gaps that are less
+                                       than the specified microseconds. This
+                                       depends on the data rate. */
+} ProtoViewModulation;
+
+extern ProtoViewModulation ProtoViewModulations[]; /* In app_subghz.c */
+
+/* This is the context of our subghz worker and associated thread.
+ * It receives data and we get our protocol "feed" callback called
+ * with the level (1 or 0) and duration. */
+struct ProtoViewTxRx {
+    bool freq_mod_changed; /* The user changed frequency and/or modulation
+                                   from the interface. There is to restart the
+                                   radio with the right parameters. */
+    TxRxState txrx_state; /* Receiving, idle or sleeping? */
+
+    /* Timer sampling mode state. */
+    bool debug_timer_sampling; /* Read data from GDO0 in a busy loop. Only
+                                   for testing. */
+    uint32_t last_g0_change_time; /* Last high->low (or reverse) switch. */
+    bool last_g0_value; /* Current value (high or low): we are
+                                     checking the duration in the timer
+                                     handler. */
+};
+
+typedef struct ProtoViewTxRx ProtoViewTxRx;
+
+/* ============================== Main app state ============================ */
+
+#define ALERT_MAX_LEN 32
+struct ProtoViewApp {
+    /* GUI */
+    Gui* gui;
+    NotificationApp* notification;
+    ViewPort* view_port; /* We just use a raw viewport and we render
+                                everything into the low level canvas. */
+    ProtoViewCurrentView current_view; /* Active left-right view ID. */
+    FuriMutex* view_updating_mutex; /* The Flipper GUI calls the screen redraw
+                                       callback in a different thread. We
+                                       use this mutex to protect the redraw
+                                       from changes in app->view_privdata. */
+    int current_subview[ViewLast]; /* Active up-down subview ID. */
+    FuriMessageQueue* event_queue; /* Keypress events go here. */
+
+    /* Input text state. */
+    ViewDispatcher* view_dispatcher; /* Used only when we want to show
+                                        the text_input view for a moment.
+                                        Otherwise it is set to null. */
+    TextInput* text_input;
+    bool show_text_input;
+    char* text_input_buffer;
+    uint32_t text_input_buffer_len;
+    void (*text_input_done_callback)(void*);
+
+    /* Alert state. */
+    uint32_t alert_dismiss_time; /* Millisecond when the alert will be
+                                       no longer shown. Or zero if the alert
+                                       is currently not set at all. */
+    char alert_text[ALERT_MAX_LEN]; /* Alert content. */
+
+    /* Radio related. */
+    ProtoViewTxRx* txrx; /* Radio state. */
+    SubGhzSetting* setting; /* A list of valid frequencies. */
+
+    const SubGhzDevice* radio_device;
+
+    /* Generic app state. */
+    int running; /* Once false exists the app. */
+    uint32_t signal_bestlen; /* Longest coherent signal observed so far. */
+    uint32_t signal_last_scan_idx; /* Index of the buffer last time we
+                                      performed the scan. */
+    bool signal_decoded; /* Was the current signal decoded? */
+    ProtoViewMsgInfo* msg_info; /* Decoded message info if not NULL. */
+    bool direct_sampling_enabled; /* This special view needs an explicit
+                                     acknowledge to work. */
+    void* view_privdata; /* This is a piece of memory of total size
+                               PROTOVIEW_VIEW_PRIVDATA_LEN that it is
+                               initialized to zero when we switch to
+                               a a new view. While the view we are using
+                               is the same, it can be used by the view to
+                               store any kind of info inside, just casting
+                               the pointer to a few specific-data structure. */
+
+    /* Raw view apps state. */
+    uint32_t us_scale; /* microseconds per pixel. */
+    uint32_t signal_offset; /* Long press left/right panning in raw view. */
+
+    /* Configuration view app state. */
+    uint32_t frequency; /* Current frequency. */
+    uint8_t modulation; /* Current modulation ID, array index in the
+                                ProtoViewModulations table. */
+};
+
+/* =========================== Protocols decoders =========================== */
+
+/* This stucture is filled by the decoder for specific protocols with the
+ * informations about the message. ProtoView will display such information
+ * in the message info view. */
+#define PROTOVIEW_MSG_STR_LEN 32
+typedef struct ProtoViewMsgInfo {
+    ProtoViewDecoder* decoder; /* The decoder that decoded the message. */
+    ProtoViewFieldSet* fieldset; /* Decoded fields. */
+    /* Low level information of the detected signal: the following are filled
+     * by the protocol decoding function: */
+    uint32_t start_off; /* Pulses start offset in the bitmap. */
+    uint32_t pulses_count; /* Number of pulses of the full message. */
+    /* The following are passed already filled to the decoder. */
+    uint32_t short_pulse_dur; /* Microseconds duration of the short pulse. */
+    /* The following are filled by ProtoView core after the decoder returned
+     * success. */
+    uint8_t* bits; /* Bitmap with the signal. */
+    uint32_t bits_bytes; /* Number of full bytes in the bitmap, that
+                                   is 'pulses_count/8' rounded to the next
+                                   integer. */
+} ProtoViewMsgInfo;
+
+/* This structures describe a set of protocol fields. It is used by decoders
+ * supporting message building to receive and return information about the
+ * protocol. */
+typedef enum {
+    FieldTypeStr,
+    FieldTypeSignedInt,
+    FieldTypeUnsignedInt,
+    FieldTypeBinary,
+    FieldTypeHex,
+    FieldTypeBytes,
+    FieldTypeFloat,
+} ProtoViewFieldType;
+
+typedef struct {
+    ProtoViewFieldType type;
+    uint32_t len; // Depends on type:
+        // Bits for integers (signed,unsigned,binary,hex).
+        // Number of characters for strings.
+        // Number of nibbles for bytes (1 for each 4 bits).
+        // Number of digits after dot for floats.
+    char* name; // Field name.
+    union {
+        char* str; // String type.
+        int64_t value; // Signed integer type.
+        uint64_t uvalue; // Unsigned integer type.
+        uint8_t* bytes; // Raw bytes type.
+        float fvalue; // Float type.
+    };
+} ProtoViewField;
+
+typedef struct ProtoViewFieldSet {
+    ProtoViewField** fields;
+    uint32_t numfields;
+} ProtoViewFieldSet;
+
+typedef struct ProtoViewDecoder {
+    const char* name; /* Protocol name. */
+    /* The decode function takes a buffer that is actually a bitmap, with
+     * high and low levels represented as 0 and 1. The number of high/low
+     * pulses represented by the bitmap is passed as the 'numbits' argument,
+     * while 'numbytes' represents the total size of the bitmap pointed by
+     * 'bits'. So 'numbytes' is mainly useful to pass as argument to other
+     * functions that perform bit extraction with bound checking, such as
+     * bitmap_get() and so forth. */
+    bool (*decode)(uint8_t* bits, uint32_t numbytes, uint32_t numbits, ProtoViewMsgInfo* info);
+    /* This method is used by the decoder to return the fields it needs
+     * in order to build a new message. This way the message builder view
+     * can ask the user to fill the right set of fields of the specified
+     * type. */
+    void (*get_fields)(ProtoViewFieldSet* fields);
+    /* This method takes the fields supported by the decoder, and
+     * renders a message in 'samples'. */
+    void (*build_message)(RawSamplesBuffer* samples, ProtoViewFieldSet* fields);
+} ProtoViewDecoder;
+
+extern RawSamplesBuffer *RawSamples, *DetectedSamples;
+
+/* app_subghz.c */
+void radio_begin(ProtoViewApp* app);
+uint32_t radio_rx(ProtoViewApp* app);
+void radio_idle(ProtoViewApp* app);
+void radio_rx_end(ProtoViewApp* app);
+void radio_sleep(ProtoViewApp* app);
+void raw_sampling_worker_start(ProtoViewApp* app);
+void raw_sampling_worker_stop(ProtoViewApp* app);
+void radio_tx_signal(ProtoViewApp* app, FuriHalSubGhzAsyncTxCallback data_feeder, void* ctx);
+void protoview_rx_callback(bool level, uint32_t duration, void* context);
+
+/* signal.c */
+uint32_t duration_delta(uint32_t a, uint32_t b);
+void reset_current_signal(ProtoViewApp* app);
+void scan_for_signal(ProtoViewApp* app, RawSamplesBuffer* source, uint32_t min_duration);
+bool bitmap_get(uint8_t* b, uint32_t blen, uint32_t bitpos);
+void bitmap_set(uint8_t* b, uint32_t blen, uint32_t bitpos, bool val);
+void bitmap_copy(
+    uint8_t* d,
+    uint32_t dlen,
+    uint32_t doff,
+    uint8_t* s,
+    uint32_t slen,
+    uint32_t soff,
+    uint32_t count);
+void bitmap_set_pattern(uint8_t* b, uint32_t blen, uint32_t off, const char* pat);
+void bitmap_reverse_bytes_bits(uint8_t* p, uint32_t len);
+bool bitmap_match_bits(uint8_t* b, uint32_t blen, uint32_t bitpos, const char* bits);
+uint32_t bitmap_seek_bits(
+    uint8_t* b,
+    uint32_t blen,
+    uint32_t startpos,
+    uint32_t maxbits,
+    const char* bits);
+bool bitmap_match_bitmap(
+    uint8_t* b1,
+    uint32_t b1len,
+    uint32_t b1off,
+    uint8_t* b2,
+    uint32_t b2len,
+    uint32_t b2off,
+    uint32_t cmplen);
+void bitmap_to_string(char* dst, uint8_t* b, uint32_t blen, uint32_t off, uint32_t len);
+uint32_t convert_from_line_code(
+    uint8_t* buf,
+    uint64_t buflen,
+    uint8_t* bits,
+    uint32_t len,
+    uint32_t offset,
+    const char* zero_pattern,
+    const char* one_pattern);
+uint32_t convert_from_diff_manchester(
+    uint8_t* buf,
+    uint64_t buflen,
+    uint8_t* bits,
+    uint32_t len,
+    uint32_t off,
+    bool previous);
+void init_msg_info(ProtoViewMsgInfo* i, ProtoViewApp* app);
+void free_msg_info(ProtoViewMsgInfo* i);
+
+/* signal_file.c */
+bool save_signal(ProtoViewApp* app, const char* filename);
+
+/* view_*.c */
+void render_view_raw_pulses(Canvas* const canvas, ProtoViewApp* app);
+void process_input_raw_pulses(ProtoViewApp* app, InputEvent input);
+void render_view_settings(Canvas* const canvas, ProtoViewApp* app);
+void process_input_settings(ProtoViewApp* app, InputEvent input);
+void render_view_info(Canvas* const canvas, ProtoViewApp* app);
+void process_input_info(ProtoViewApp* app, InputEvent input);
+void render_view_direct_sampling(Canvas* const canvas, ProtoViewApp* app);
+void process_input_direct_sampling(ProtoViewApp* app, InputEvent input);
+void render_view_build_message(Canvas* const canvas, ProtoViewApp* app);
+void process_input_build_message(ProtoViewApp* app, InputEvent input);
+void view_enter_build_message(ProtoViewApp* app);
+void view_exit_build_message(ProtoViewApp* app);
+void view_enter_direct_sampling(ProtoViewApp* app);
+void view_exit_direct_sampling(ProtoViewApp* app);
+void view_exit_settings(ProtoViewApp* app);
+void view_exit_info(ProtoViewApp* app);
+void adjust_raw_view_scale(ProtoViewApp* app, uint32_t short_pulse_dur);
+
+/* ui.c */
+int ui_get_current_subview(ProtoViewApp* app);
+void ui_show_available_subviews(Canvas* canvas, ProtoViewApp* app, int last_subview);
+bool ui_process_subview_updown(ProtoViewApp* app, InputEvent input, int last_subview);
+void ui_show_keyboard(
+    ProtoViewApp* app,
+    char* buffer,
+    uint32_t buflen,
+    void (*done_callback)(void*));
+void ui_dismiss_keyboard(ProtoViewApp* app);
+void ui_show_alert(ProtoViewApp* app, const char* text, uint32_t ttl);
+void ui_dismiss_alert(ProtoViewApp* app);
+void ui_draw_alert_if_needed(Canvas* canvas, ProtoViewApp* app);
+void canvas_draw_str_with_border(
+    Canvas* canvas,
+    uint8_t x,
+    uint8_t y,
+    const char* str,
+    Color text_color,
+    Color border_color);
+
+/* fields.c */
+void fieldset_free(ProtoViewFieldSet* fs);
+ProtoViewFieldSet* fieldset_new(void);
+void fieldset_add_int(ProtoViewFieldSet* fs, const char* name, int64_t val, uint8_t bits);
+void fieldset_add_uint(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits);
+void fieldset_add_hex(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits);
+void fieldset_add_bin(ProtoViewFieldSet* fs, const char* name, uint64_t uval, uint8_t bits);
+void fieldset_add_str(ProtoViewFieldSet* fs, const char* name, const char* s, size_t len);
+void fieldset_add_bytes(
+    ProtoViewFieldSet* fs,
+    const char* name,
+    const uint8_t* bytes,
+    uint32_t count);
+void fieldset_add_float(
+    ProtoViewFieldSet* fs,
+    const char* name,
+    float val,
+    uint32_t digits_after_dot);
+const char* field_get_type_name(ProtoViewField* f);
+int field_to_string(char* buf, size_t len, ProtoViewField* f);
+bool field_set_from_string(ProtoViewField* f, char* buf, size_t len);
+bool field_incr_value(ProtoViewField* f, int incr);
+void fieldset_copy_matching_fields(ProtoViewFieldSet* dst, ProtoViewFieldSet* src);
+void field_set_from_field(ProtoViewField* dst, ProtoViewField* src);
+
+/* crc.c */
+uint8_t crc8(const uint8_t* data, size_t len, uint8_t init, uint8_t poly);
+uint8_t sum_bytes(const uint8_t* data, size_t len, uint8_t init);
+uint8_t xor_bytes(const uint8_t* data, size_t len, uint8_t init);

+ 206 - 0
main_apps_sources/protoview/app_subghz.c

@@ -0,0 +1,206 @@
+/* Copyright (C) 2022-2023 Salvatore Sanfilippo -- All Rights Reserved
+ * See the LICENSE file for information about the license. */
+
+#include "app.h"
+#include "custom_presets.h"
+
+#include <flipper_format/flipper_format_i.h>
+#include <furi_hal_rtc.h>
+#include <furi_hal_spi.h>
+#include <furi_hal_interrupt.h>
+
+void raw_sampling_timer_start(ProtoViewApp* app);
+void raw_sampling_timer_stop(ProtoViewApp* app);
+
+ProtoViewModulation ProtoViewModulations[] = {
+    {"OOK 650Khz", "FuriHalSubGhzPresetOok650Async", FuriHalSubGhzPresetOok650Async, NULL, 30},
+    {"OOK 270Khz", "FuriHalSubGhzPresetOok270Async", FuriHalSubGhzPresetOok270Async, NULL, 30},
+    {"2FSK 2.38Khz",
+     "FuriHalSubGhzPreset2FSKDev238Async",
+     FuriHalSubGhzPreset2FSKDev238Async,
+     NULL,
+     30},
+    {"2FSK 47.6Khz",
+     "FuriHalSubGhzPreset2FSKDev476Async",
+     FuriHalSubGhzPreset2FSKDev476Async,
+     NULL,
+     30},
+    {"TPMS 1 (FSK)", NULL, 0, (uint8_t*)protoview_subghz_tpms1_fsk_async_regs, 30},
+    {"TPMS 2 (OOK)", NULL, 0, (uint8_t*)protoview_subghz_tpms2_ook_async_regs, 30},
+    {"TPMS 3 (GFSK)", NULL, 0, (uint8_t*)protoview_subghz_tpms3_gfsk_async_regs, 30},
+    {"OOK 40kBaud", NULL, 0, (uint8_t*)protoview_subghz_40k_ook_async_regs, 15},
+    {"FSK 40kBaud", NULL, 0, (uint8_t*)protoview_subghz_40k_fsk_async_regs, 15},
+    {NULL, NULL, 0, NULL, 0} /* End of list sentinel. */
+};
+
+/* Called after the application initialization in order to setup the
+ * subghz system and put it into idle state. */
+void radio_begin(ProtoViewApp* app) {
+    furi_assert(app);
+    subghz_devices_reset(app->radio_device);
+    subghz_devices_idle(app->radio_device);
+
+    /* The CC1101 preset can be either one of the standard presets, if
+     * the modulation "custom" field is NULL, or a custom preset we
+     * defined in custom_presets.h. */
+    if(ProtoViewModulations[app->modulation].custom == NULL) {
+        subghz_devices_load_preset(
+            app->radio_device, ProtoViewModulations[app->modulation].preset, NULL);
+    } else {
+        subghz_devices_load_preset(
+            app->radio_device,
+            FuriHalSubGhzPresetCustom,
+            ProtoViewModulations[app->modulation].custom);
+    }
+    furi_hal_gpio_init(
+        subghz_devices_get_data_gpio(app->radio_device), GpioModeInput, GpioPullNo, GpioSpeedLow);
+    app->txrx->txrx_state = TxRxStateIDLE;
+}
+
+/* ================================= Reception ============================== */
+
+/* We avoid the subghz provided abstractions and put the data in our
+ * simple abstraction: the RawSamples circular buffer. */
+void protoview_rx_callback(bool level, uint32_t duration, void* context) {
+    UNUSED(context);
+    /* Add data to the circular buffer. */
+    raw_samples_add(RawSamples, level, duration);
+    // FURI_LOG_E(TAG, "FEED: %d %d", (int)level, (int)duration);
+    return;
+}
+
+/* Setup the CC1101 to start receiving using a background worker. */
+uint32_t radio_rx(ProtoViewApp* app) {
+    furi_assert(app);
+
+    if(!subghz_devices_is_frequency_valid(app->radio_device, app->frequency)) {
+        furi_crash(TAG " Incorrect RX frequency.");
+    }
+
+    if(app->txrx->txrx_state == TxRxStateRx) return app->frequency;
+
+    subghz_devices_idle(app->radio_device); /* Put it into idle state in case it is sleeping. */
+    uint32_t value = subghz_devices_set_frequency(app->radio_device, app->frequency);
+    FURI_LOG_E(TAG, "Switched to frequency: %lu", value);
+
+    subghz_devices_flush_rx(app->radio_device);
+    subghz_devices_set_rx(app->radio_device);
+
+    if(!app->txrx->debug_timer_sampling) {
+        subghz_devices_start_async_rx(app->radio_device, protoview_rx_callback, NULL);
+    } else {
+        furi_hal_gpio_init(
+            subghz_devices_get_data_gpio(app->radio_device),
+            GpioModeInput,
+            GpioPullNo,
+            GpioSpeedLow);
+        raw_sampling_worker_start(app);
+    }
+    app->txrx->txrx_state = TxRxStateRx;
+    return value;
+}
+
+/* Stop receiving (if active) and put the radio on idle state. */
+void radio_rx_end(ProtoViewApp* app) {
+    furi_assert(app);
+
+    if(app->txrx->txrx_state == TxRxStateRx) {
+        if(!app->txrx->debug_timer_sampling) {
+            subghz_devices_stop_async_rx(app->radio_device);
+        } else {
+            raw_sampling_worker_stop(app);
+        }
+    }
+    subghz_devices_idle(app->radio_device);
+    app->txrx->txrx_state = TxRxStateIDLE;
+}
+
+/* Put radio on sleep. */
+void radio_sleep(ProtoViewApp* app) {
+    furi_assert(app);
+    if(app->txrx->txrx_state == TxRxStateRx) {
+        /* Stop the asynchronous receiving system before putting the
+         * chip into sleep. */
+        radio_rx_end(app);
+    }
+    subghz_devices_sleep(app->radio_device);
+    app->txrx->txrx_state = TxRxStateSleep;
+}
+
+/* =============================== Transmission ============================= */
+
+/* This function suspends the current RX state, switches to TX mode,
+ * transmits the signal provided by the callback data_feeder, and later
+ * restores the RX state if there was one. */
+void radio_tx_signal(ProtoViewApp* app, FuriHalSubGhzAsyncTxCallback data_feeder, void* ctx) {
+    TxRxState oldstate = app->txrx->txrx_state;
+
+    if(oldstate == TxRxStateRx) radio_rx_end(app);
+    radio_begin(app);
+
+    subghz_devices_idle(app->radio_device);
+    uint32_t value = subghz_devices_set_frequency(app->radio_device, app->frequency);
+    FURI_LOG_E(TAG, "Switched to frequency: %lu", value);
+
+    subghz_devices_start_async_tx(app->radio_device, data_feeder, ctx);
+    while(!subghz_devices_is_async_complete_tx(app->radio_device)) furi_delay_ms(10);
+    subghz_devices_stop_async_tx(app->radio_device);
+    subghz_devices_idle(app->radio_device);
+
+    radio_begin(app);
+    if(oldstate == TxRxStateRx) radio_rx(app);
+}
+
+/* ============================= Raw sampling mode =============================
+ * This is a special mode that uses a high frequency timer to sample the
+ * CC1101 pin directly. It's useful for debugging purposes when we want
+ * to get the raw data from the chip and completely bypass the subghz
+ * Flipper system.
+ * ===========================================================================*/
+
+void protoview_timer_isr(void* ctx) {
+    ProtoViewApp* app = ctx;
+
+    bool level = furi_hal_gpio_read(subghz_devices_get_data_gpio(app->radio_device));
+    if(app->txrx->last_g0_value != level) {
+        uint32_t now = DWT->CYCCNT;
+        uint32_t dur = now - app->txrx->last_g0_change_time;
+        dur /= furi_hal_cortex_instructions_per_microsecond();
+        if(dur > 15000) dur = 15000;
+        raw_samples_add(RawSamples, app->txrx->last_g0_value, dur);
+        app->txrx->last_g0_value = level;
+        app->txrx->last_g0_change_time = now;
+    }
+    LL_TIM_ClearFlag_UPDATE(TIM2);
+}
+
+void raw_sampling_worker_start(ProtoViewApp* app) {
+    UNUSED(app);
+
+    furi_hal_bus_enable(FuriHalBusTIM2);
+
+    LL_TIM_InitTypeDef tim_init = {
+        .Prescaler = 63, /* CPU frequency is ~64Mhz. */
+        .CounterMode = LL_TIM_COUNTERMODE_UP,
+        .Autoreload = 5, /* Sample every 5 us */
+    };
+
+    LL_TIM_Init(TIM2, &tim_init);
+    LL_TIM_SetClockSource(TIM2, LL_TIM_CLOCKSOURCE_INTERNAL);
+    LL_TIM_DisableCounter(TIM2);
+    LL_TIM_SetCounter(TIM2, 0);
+    furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, protoview_timer_isr, app);
+    LL_TIM_EnableIT_UPDATE(TIM2);
+    LL_TIM_EnableCounter(TIM2);
+    FURI_LOG_E(TAG, "Timer enabled");
+}
+
+void raw_sampling_worker_stop(ProtoViewApp* app) {
+    UNUSED(app);
+    FURI_CRITICAL_ENTER();
+    LL_TIM_DisableCounter(TIM2);
+    LL_TIM_DisableIT_UPDATE(TIM2);
+    furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, NULL, NULL);
+    furi_hal_bus_disable(FuriHalBusTIM2);
+    FURI_CRITICAL_EXIT();
+}

Некоторые файлы не были показаны из-за большого количества измененных файлов