Compare commits

...

99 Commits

Author SHA1 Message Date
qwer123 865bdee9b3 add external clock detect method (#3180) 2026-05-20 22:40:39 +02:00
Totoo 314e910cbc make battleship smaller (#3181) 2026-05-20 18:39:21 +02:00
Pezsma ec6c7eff86 Hard reset app (#3182) 2026-05-20 18:38:13 +02:00
Pezsma 95b2e9fbc3 Charge sleep bug (#3177) 2026-05-15 09:24:30 +00:00
未来方舟 52ff442fcc Tune pull_request_template a bit (#3176) 2026-05-14 00:48:27 +08:00
gullradriel 95d246a020 Update hackrf submodule (#3174)
* updated submodule

* usb_serial: populate usb_device before usb_run. Upstream now leaves the global usb_device zero-initialized and expects hackrf_usb.c to memcpy a per-board const into it. We don't link hackrf_usb.c, so do the memcpy here. Also flip control_in to enable_zlp=true to match the new endpoint API.

* baseband: derive IS_* board defines from BOARD. Upstream moved platform IS_* macros from platform_detect.h to cmake. Set them per BOARD here since we don't include platform-detect.cmake. Drop the duplicate clkin.c entry.

* sd_over_usb: drop duplicate driver objects, fix setup callback. Upstream now defines i2c0/i2c1, spi_bus_ssp0/1, sgpio_config and rf_path in the common driver files, so stop redefining them here and patch the runtime fields in pin_setup() instead. Update si5351c_reset_pll() call to the two-arg form. Replace the no-op transceiver_usb_setup_complete stub with one that delegates to usb_setup_complete.

* sd_over_usb: populate usb_device before usb_run. Same fix as the application side: memcpy a const template into usb_device before usb_device_init/usb_run, otherwise the descriptor pointer is NULL. Also pass enable_zlp=true on control_in to match the new endpoint API.

* fix unicode in comment

* remove lz4 bufs reservation in M0
2026-05-13 14:53:54 +02:00
Frederic BORRY c34a6940ca EPIRB RX app rework + EPIRB TX app fixes (#3172)
* First step to EPIRB rx app fix
* Added spike filtering on carrier detection for more robustness.
* Created dedicated packet builder
* First step to fixing UI.
* First step to epirb-rx ui rework.
* Made static methods static members
* Code optim
* Code cleanup + first step to new UI
* Fixed display
* Added BeaconList widget + BeaconDB
* Epirb TX app memory optim
* Fixed OOM when opening Map Display or Locator editor on EPIRB TX app
* First step to tabs + code cleanup to free some space...
* Added spectrum analyzer + fixed display
* Fixed display refresh issue after leaving spectrum.
* More code optim + first step to detail view.
* Fixed float coord display.
* Fixed protocol names
* Fixed location display
* Externalized country base to sd card + more code optim
* Fixed country display
* Fixed path
* Added protocol description and resource manager
* Added main/aux loc device
* Removed specan to save space
* First step to adding QR code
* Used a custom TextArea component instead of Console
* Fixed QR code display for map URL
* Added beacon selection management + fixes
* First step to map/data qr.
* QR tab : added data + detail/map toggle
* Removed sqhelch to save space
* Removed audio to save space
* Removed freq label to save space
* Removed packet timestamp to save space
* Moved frequency values to resource file
* Fixed detection parameters to suite real beacons (slower phase shift time).
* Fixed countdown field size
* Fixed frequency list.
* Fixed detail view on select.
* First step to fix settings.
* Fixed squelch for a 0-99 range.
* Added bch code correction (single bit error).
* More code optim, disable country cache, removed inline from location to reduce code size.
* Removed inline, code formatting.
* Added bch code correction display.
* Fixed focus bug, fixed packet size check. Added BCH1/BCH2 correction test cases in BEACONS.TXT file for EPIRB TX application.
* Fixed merge
* Added countdown setting.
* Added selection display to beacon list
* Restored squelch control. Added countdown reset.
* Code optim on formatSummary
* More code optim
* Made ResourceManager methods static
* Externalized beacon strings to res file
*Removed frame parameter from methods
* Added test beacons for emergency. Removed old res file.
* Fixed resource manager
* Fixed resources. Added emergency display.
* BCH + res fixes
* Fixed beacons
* Fixed app color. Fixed HexId and Serial calculation.
* Fixed frequency list. Comments.
* Code cleanup and comments
* Added slideshow mode to EPIRB TX application. Code comments / cleanup.
* Fixed frame end after wrong code cleanup
* More code optim and comments. Removed touch from beacon list.
* Added beacon selection with encoder on detail view.
* Added beacon paging in header. Fixed timeout display
* Fixed build for PRALINE
* Fixed formatting
* Potential fix for pull request finding
* stop on carriage return
* empty string if unknown
* zeroing data buffer before use
* fix typo
* add include
* fix case if pair == 0
* fix scpectrum_on to spectrum_on
* fix typos
* replaced 3 inlined offset blocks with apply_offset calls
* set_beacon consolidation
2026-05-12 14:00:47 +02:00
Synray 33330e4c34 Use gradient for level view, fix height scaling (#3173)
* Use gradient for level view, fix height scaling
* Add RSSI indicators
2026-05-12 12:48:17 +02:00
Pezsma 66f1835232 Wait tx complete (#3165)
* Implement radio transmission drain mechanism and update shared memory structure
* don't wait for timeout if baseband already in shut down state
2026-05-12 12:45:02 +02:00
Synray 4dfbf666d0 Add more waterfalls (#3170) 2026-05-10 09:37:08 +02:00
Synray 245a36459f UI and bug fixes (#3164)
* Fix BLE RX RSSI and Channel scale

* Properly reset gradient index 0

* Use move constructor in MenuView::add_item

* Avoid erasing during iteration

* Fix gradient rounding. Extend to end of table

* Add comment to add_item
2026-05-10 00:08:05 +02:00
janhaverkamp 590f19062b Add support for larger battery capacities (#3168) 2026-05-09 20:54:25 +02:00
Totoo f38ef4ebc8 Added CU8 playback support (#3166) 2026-05-09 12:23:43 +02:00
gullradriel 900d2f2482 fix missing header (#3167) 2026-05-09 12:23:10 +02:00
Totoo 5aff5ac277 Fix text color multiline handling (#3161) 2026-05-08 09:57:06 +02:00
Totoo cf4d245964 Fixes #3159 (#3160) 2026-05-07 23:54:30 +08:00
Pezsma c7f7173958 sleep warning fix (#3162) 2026-05-07 15:26:34 +02:00
Totoo 02c0f67a8d fix menu handling again (#3157) 2026-05-04 20:59:48 +02:00
Totoo 2bacbc80a8 Memory management improv. 2026-04-30 15:00:19 +02:00
Pezsma ab986a0378 Change charge display off to sleep (#3153) 2026-04-29 19:57:17 +02:00
Totoo c9f310f548 Add power off command to I2cDev_PPmod class (#3152) 2026-04-23 13:18:56 +02:00
Synray 1dafdd5a26 Increase text length to avoid cutoff (#3150) 2026-04-20 15:47:59 +08:00
VasylSamoilov fc5beb0c09 FLEX RX: fix long-address numeric decode, improve short message format (#3136)
- Fix long-address numeric message decoding: read body[0] from Vy (j+1)
  for multi-word messages, from w1 for single-word. Fix MF word count
  for long addresses (n_field words, not n_field+1).
- Fix long-address short message: read 5 additional BCD digits from Vy
  for 8-digit decode.
- Fix BCD table: index 10 is '.' (dot) not ' ' (space) in both RX and TX.
- Clean up address decode: identify address type by value range per
  Table 3.8.1-1. Remove is_group/is_temp_group from packet structs.
- Rename SMSG to SHORT. Format message payload directly in baseband:
  TONE, NUM abc, SRC N, SRC N N=M R=R, RESERVED hex.
- Add BIW1 heartbeat packet (biw_field=0xFF) on every decoded frame.
- Move timezone table to file scope, simplify console log_message,
  add No signal initial status, simplify serial BIW output format.
2026-04-18 21:15:05 +02:00
gullradriel 3f10663bc9 Pull request guidelines (#3149)
* update PR template
* wiki mention
* added trusted contributors guidelines, compile proof simplification
2026-04-18 21:13:30 +02:00
VasylSamoilov 396f8aef41 POCSAG: show '?' for characters from uncorrectable codewords (#3138)
Use per-character error tracking to substitute '?' when a
character's bits came from an uncorrectable codeword (BCH error_count >= 3). 
Previously these displayed as garbage.
2026-04-18 18:56:33 +02:00
VasylSamoilov c095a88cb3 FLEX TX: fix stop button not stopping transmission (fixes #3135) (#3137)
Reset tx_phase_ to 0 on stop so on_tx_progress does not restart
the next phase. Reset progress bar and repaint capcode info.
2026-04-13 15:57:31 +08:00
Totoo 900c80549f externalize basebands, not needed, and remove too high level function (#3134)
* externalize basebands, not needed, and remove too high level function

* fix ert
2026-04-10 21:08:46 +02:00
VasylSamoilov 4dce613172 FLEX TX: pager transmitter with long address support (1600/2FSK) (#3132)
External app for encoding and transmitting FLEX pager frames at
1600bps/2FSK. Supports short (1-1,933,312) and long (2,101,249-
4,297,068,542) addresses across all encoding sets (1-2, 1-3/1-4, 2-3).

Message types:
- Alphanumeric (vector type 5): 7-bit chars, signature, K checksum
- Standard Numeric (vector type 3): 4-bit BCD, K checksum
- Short/tone-only (vector type 2): space-filled BCD in vector word
- Short numeric (vector type 2): BCD digits in vector word (3/8 digits)

Frame structure:
- FIW (Frame Information Word): cycle, frame, roaming flag
- BIW (Block Information Word) support with up to 3 extra words:
  Date, Time, SysInfo/timezone+DST, SSID1 (Simulcast System ID:
  Local ID + Coverage Zone), SSID2 (Country Code)
- BCH(31,21) encoding with bit reversal, block interleaving
- Two frames per TX: message R=1 (new) then R=0 (duplicate)
- Message number N (0-63): random seed from RTC, auto-increments
- ERS (Emergency Re-Sync) burst: configurable N x 42-cycle bursts
  with 8-cycle preamble per frame

UI:
- Capcode info line: address type, computed frame/phase (reference)
- TX status: step counter with ERS/frame progress
- Set params view: Date/Time/TZ/DST, LocID/CovZone, CountryCode,
  Roaming, message number, ERS count
- Date/time auto-populated from RTC with calendar-equivalent year
  mapping for years beyond 2025 (per ARIB STD-43A)
- Year validation with equiv-year popup for out-of-range values
- Capcode and BIW flags persisted via SettingsManager

Serial interface:
- sendflex <capcode> <type> <msglen> + payload
- Types: 0=alpha, 1=numeric, 2=short/tone, 3=short numeric
- FlexTosendMessage (ID 103) for serial-to-app communication
- App must be open to receive serial commands
2026-04-10 11:17:52 +02:00
VasylSamoilov cf44076a34 FLEX RX: comprehensive decoder rewrite (#3131)
Baseband (proc_flex.cpp):
- Fix numeric vector field width (3-bit n+1 for types 3,4,7)
- Fix capcode range classification for long address components
- Add long address decode (Set 1-2, 1-3/1-4, 2-3)
- Add vector checksum validation (4-bit nibble sum)
- Add tone-only boundary detection via vector pre-scan
- Add idle phase detection (skip all-zeros/all-ones before BCH)
- Skip spurious TON for capcode 1 (BCH-corrected idle artifact)
- Add BIW parsing: SSID1/SSID2, DATE, TIME, TZ, SYSMSG, CHAN
- Add alpha fragment flags: frag, more_frag, seq, new, maildrop, sig
- Add secure message enc= field (alpha/binary/separate)
- Add numbered numeric flags: seq, new, fmt
- Add HEX/Binary header decode: block_bits, new, maildrop, rtl
- Add short instruction decode: temp group slot/target, sys events
- Add short message (SMSG) decode: tone/numeric/source/numbered
- Add group/temp-group/priority flags per address
- Add S2 C-pattern detection with ±1 symbol boundary correction
- Extract FIW roaming, repeat, traffic fields
- Replace snprintf with lightweight str_* helpers (no heap/_sbrk)
- Mark uncorrectable BCH words as ? instead of aborting phase
- ETX/NUL handling: trim trailing padding, show mid-message as ?

App (ui_flex_rx.cpp):
- Add status bar: cycle/frame, bitrate, polarity, time, timezone
- Add network info bar: LID, CZ, CC, roaming flag
- Pipe-delimited serial output for all message types
- BIW events to serial and status bar (not console)
- Human-readable console: +GRP for temp group, G/TG/P flags
- USB serial via UsbSerialAsyncmsg

Packet (flex_defs.hpp):
- uint64_t capcode (long address support)
- 256-byte message buffer
- Fragment flags, BIW raw values, address type, group/priority

Known limitation: phase label unreliable on multi-phase modes
(3200/2FSK, 6400/4FSK). Data always decodes correctly.
2026-04-10 08:37:38 +02:00
VasylSamoilov dd006b4830 POCSAG: decoder fixes, serial output, TX polarity cleanup (#3130)
RX: fix address/batch-boundary handling, add numeric continuation,
add heuristic type detection toggle, pass inverted polarity flag,
stream decoded messages over USB serial.

TX: rename phase to polarity (Standard/Inverted), fix function
validation (&&→||), fix serial shell payload read (offset tracking,
31-byte cap, preserve msglen).

Decoder: remove color escapes from output (plain text for all
consumers), guard count_alpha_fill against empty string, keep
numeric_len across continuation batches.

Serial format: POCSAG <baud> <addr> <func> <pol> <type> "<msg>" hex:<hex>
Quote escaping for embedded " and \\ in alpha messages.
2026-04-10 08:35:43 +02:00
qwer123 fc18992442 Add retry mechanism for volume write (#3121) 2026-04-10 08:33:48 +02:00
gullradriel ef2ae9874b fix build (#3129)
Co-authored-by: gullradriel <gullradriel@users.noreply.github.com>
2026-04-08 08:28:44 +02:00
Pezsma 5deeaed5f0 Praline rssi (#3127) 2026-04-07 19:42:21 +02:00
Ryan Harden d5f94398ce Add external 2-Tone TX/RX Apps (#3128) 2026-04-07 19:32:41 +02:00
Totoo fba15c48e5 Battery capacity options added (#3125) 2026-04-04 09:19:17 +13:00
Totoo 888634ce35 praline without the much fixed ram (#3123) 2026-04-04 09:17:21 +13:00
Frederic BORRY 03131c8a0c EPIRB TX application update (#3120) 2026-04-03 11:35:46 +02:00
gullradriel 605c9efa0c Make detector use freqman (#3119)
* make detector list a freqman file
* add file loading ability, autoscan/pause, step in on pause on range, frequency value display
* Update firmware/application/external/detector_rx/ui_detector_rx.hpp
* Update firmware/application/external/detector_rx/ui_detector_rx.cpp
* add 750 kHz step
* revamp UI and add auto advance, auto scan, and only display 'RANGE SCAN...' when auto scan is on on ranges to avoid flicker of the hell.
* adjust as I can the ranges as they where before
* Update sdcard/FREQMAN/DETECTOR.TXT
* fix instance related copilot remark
2026-04-02 08:26:45 +02:00
gullradriel aee54e5b2d Merge updated submodule (#3116)
* update hackrf submodule
* add platform_gpio.c and platform_scu.c to baseband build
    -New source files required by the updated hackrf submodule.
* adapt scsi.c to updated hackrf API
    -Rename struct gpio_t to struct gpio and add gpio_lpc.h include.
* adapt hackrf_core.c to updated hackrf API
    - Rename struct gpio_t to struct gpio throughout
    - Add platform_gpio.h, platform_scu.h, and fixed_point.h includes
    - Update pin_setup() to use platform_scu() accessor instead of SCU_ macros
    - Rewrite sample_rate_set() to use new fixed-point frequency API
    - Update ssp_config_w25q80bv for changed struct layout
    - Update si5351c and max283x function call signatures
2026-03-30 23:47:39 +08:00
zxkmm e33e697cca remove some bluffing text from fpv detect app (#3114) 2026-03-29 17:24:29 +08:00
zxkmm d7d27d99e7 edit security policy (#3113) 2026-03-28 18:14:22 +01:00
Pezsma 78d3480b68 Morse tx update (#3112)
* loop message, progress bar
2026-03-27 18:29:20 +01:00
Totoo 70b42f4a56 fix audio mode change crash (#3111) 2026-03-26 22:40:27 +01:00
jLynx 5c719645d6 Update version.txt 2026-03-24 22:31:30 +13:00
jLynx b0eb776bdd Update past_version.txt 2026-03-24 22:31:18 +13:00
jLynx ce87161f9b Revert "Switched build to use ninja by default (#3072)" (#3102)
This reverts commit 22932e636d.
2026-03-20 12:16:14 +13:00
Totoo 8883f2decc fix sd test app mem usage (#3101) 2026-03-17 15:42:10 +01:00
Totoo e06d23ea3e app color 2026-03-17 15:41:31 +01:00
Totoo 0da90c7c5e modified app colors based on wiki (#3099) 2026-03-17 15:00:25 +01:00
Totoo e7572e5d41 transparent bg on map marker text (#3098) 2026-03-17 21:46:05 +08:00
Totoo 50f1e51d7e pocsag fix (#3097) 2026-03-17 21:35:37 +08:00
Sarah Rose 55a15958ec Add P25 Phase 1 TSCC TX external app (p25_tx) (#3090)
* Add P25 TX external app (UI shell)

- Register p25_tx in external.cmake and external.ld at 0xAE010000
- UI with NAC, SYSID, WACN, RFSSID, SITEID, TG, VCH fields
- 2.4 Msps TX, 155 MHz default, no baseband (m4_app_tag={0,0,0,0})

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Add P25 TX baseband processor (M4)

- P25TxConfigure = 102 in message.hpp + P25TxConfigureMessage
- image_tag_p25_tx in spi_image.hpp
- set_p25tx_data() in baseband_api (copies dibits to bb_data, sends msg)
- proc_p25_tx registered in baseband CMakeLists (tag P25T)
- m4_app_tag updated to {'P','2','5','T'}
- TX wired: transmits P25 FSW test pattern (512 dibits) via M4 C4FM proc
- on_tx_progress handler stops TX when frame complete

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* p25_tx: implement correct P25 TSBK encoding from ccemu

- BCH(63,16) via generator matrix (not polynomial division)
- CRC-CCITT bit-by-bit init=0 over 80 bits
- 1/2-rate trellis encoder (4 states)
- DataInterleave per TIA-102
- Status symbol insertion (SS=0x02 every 35 dibits)
- TSBK rotation: IDEN_UP -> NET_STS -> RFSS_STS -> NET_STS
- tsbk_idx_ persists across buffer refills, resets on stop_tx

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* p25_tx: apply clang-format

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* p25_tx: fix HackRF lockup - zero output buffer when idle

When configured=false, execute() returned without writing to the
output buffer. The DMA would re-use stale IQ samples from the
previous cycle, sending garbage to the HackRF and causing it to
lock up mid-transmission.

Fix: explicitly zero the output buffer when the proc is idle.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* p25_tx: address PR review feedback and fix TX restart lockup

- Replace NumberField with SymField::Type::Hex for NAC, SYSID, WACN,
  RFSSID, SITEID, TG, VCH (hex values should display as hex)
- Add voice grant TSBK (OpcodeGrpVChGrant 0x00) to rotation cycle;
  rotation is now 5-step: IDEN_UP->NET_STS->RFSS_STS->GRP_V_GRANT->NET_STS
- Wire TG and VCH fields into fill_tx_buffer for voice grant encoding
- Reset txprogress_message.done=false on new P25TxConfigure in baseband
- Add #include <cstring> to baseband_api.cpp (needed for memcpy)
- Fix TX restart lockup: remove baseband::shutdown() from stop_tx() so
  the M4 stays loaded between sessions; only shut down in destructor.
  Previously, the stale ShutdownMessage in the queue would be picked up
  by the restarted M4 on second TX, causing it to exit immediately and
  leaving the HackRF stuck in TX mode.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* ifndef guard instead of pragma
2026-03-17 08:41:01 +01:00
stafur 395e20d17b Next praline clean up (add SW: RSSI for hackrf pro praline) (#3091)
* Cleaned up #ifndef PRALINE and updated logic to being with #ifdef PRALINE entries where possible to make logic flow for PRALINE code execution pipeline clearer. Cleaned up compiletime warnings for PRALINE related codebase updates.

* Addressed comments provided by copilot during PR review. Combed through frequency definitions for consistency between PLL A and PLL B register definitions for CLKs 0-7. Ensured CLK3/LK6 <- SMA PORTs and CLK7 <- not utiliized are disabled during core development phase to support root cause analysis of any spectral artifacts. Updated MCU frequency to 40MHz to ensure audio harmonics are outside FM radio band range (< 80 MHz, >120MHz) and added comments clarifying choice of 40 over 10 MHz for potential future root cause analysis in other bands where audio may be expected as needed. Added CLK6 and CLK7 to Clocks Status View Debug display. Moved CLK defintions and PLL instantiations for components that are most RF sensitive to PLL A. Left others in PLL B. That is move FPGA CLK1 to PLL B, while moving CLK2, CLK4, and CLK5 to PLL A.

* Cleaned up PLL A and B XTAL reference checks relative to 800 MHz.

* Encapsulated HackRF Pro Praline debug and status vies into a single Pro Debug submenu as part of clean up.

* Fixed BLE RX Out of Memory error. Updated LPC43xx ld scripts to accouint for additional HackRF Pro praline memory.

* Addressed copilot comments for ble_rx_app by adding recent_entries_view.set_dirty. Updated ble_rx_app for easier use with heap limit set to one less than recent entries max limit.

* Addressed copilot comments by updating comment clarity in source files. Updated ui_debug to allow for return reference if set for PRO debug menu item.

* Improved readability of intialization parameters for the FPGA registers, and addressed 20Mhz nulls by initializing DC Notch width with standard setting, and DC Adaptiation rate with a balanced setting.

* Ran format-code.sh

* Added option to allow for user to set number if entries in recent list. Default is set to a relatively stable 32.

* Removed #ifdef PRALINE pragmas from ble_rx_app such that HackRF One can also use the updated UI widget to allow for user to set number of entries in recent list.

* Ran format-code.sh

* Improved RSSI for praline. Values are now being counted correctly by statistics methods after selecting ADC = 0 0 for RSSI. This was different than for the hackrf one which uses ADC = 1.

* Implemented SW RSSI calculation since HW RSSI not currently available in hackrf pro (praline) via fpga pass through. Calibrated RSSI power sensistivity to mid level signal intensitities.

* In preparation for WIP allocated full 128k to M4 limiting heap for M0 to 0k, and leabing it only with 64k from bank 0. That is, bank1 and bank2 are fully allocated to M4. Cleaned up #ifdef PRALINE conditionals such taht max2837/39 are in #else conditionals, as well as continuing to clean up hackrf_r9 booleans by placing them within #else conditionals.

* fix typo

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Addressed co-pilot comments. Clarified use of 25 recent samples in ble app for stability, udpated comments to reflect use of avg power over pwak pwer detection, improved safety of sample packing while relying on intrinstics for execute the implementation in a single machine instruction (PKHBT) for computational and memory efficiency.
2026-03-17 08:13:09 +01:00
zxkmm 9bf1f2175e fix bad color (#3096) 2026-03-17 08:10:07 +01:00
zxkmm ec57f99a2c Contribution template (#3088) 2026-03-16 19:41:43 +01:00
Sarah Rose 5c2d1d3dfb Add MDC-1200 TX external app (#3083)
Implements MDC-1200 single and double-packet TX as a PPMA external app.

Features:
- Supports PTT ID, Emergency, Radio Check, Stun/Unstun, Call Alert,
  Selective Call (1 & 2), Status Request/Response, Remote Monitor, Message
- Auto-fills Arg byte on Op selection
- AFSK FSK modulation: 1800 Hz mark / 1200 Hz space, 1200 baud
- NRZI encoding with Golay FEC per MDC-1200 spec
- Tap-to-edit frequency via keypad
- Default TX gain of 30 dB
- Uses AFSK baseband (same as POCSAG/SAME TX)
- All buffers kept off the stack to avoid hard faults in ext app environment

* mdc_tx: address PR review feedback

- Move MDC helpers into ui::external_app::mdc_tx namespace (drop anonymous namespace)
- Use AFSK_TX_SAMPLERATE macro instead of hardcoded 1536000
- Add #include "modems.hpp" explicitly for AFSK_TX_SAMPLERATE
- Replace n*8/n*16 pixel positions with UI_POS_X/UI_POS_Y macros
- Fix field comments: 'hex bytes' -> 'decimal bytes (0-255)'
- Fix TransmitterView frequency_step: 1750000 -> 12500 (12.5kHz NFM step)
- Fix MDC preamble: replace leading 0x00 bytes with 0xAA
  after NRZI encoding stayed 0x00, terminating TX on the first word.
  0xAA bytes NRZI-encode to 0xFF (continuous 1800Hz mark tone), which
  is the standard MDC-1200 preamble and does not trigger the sentinel.
2026-03-16 19:28:07 +01:00
berkeozkir 52dd2ea2bb Add FPV DETECT external app with Auto-scan FPV Presence Receiver (#3084)
* fpv_rx external app implemented

* FPV DETECT: PR feedback and Copilot suggestions

- Rename app from 'FPV RX' to 'FPV DETECT' (menu and title)
- Add fpv_rx to EXTAPPLIST in external.cmake so app is included in build
- Set external_apps_address_end = 0xAE010000 in external_app_info.py
- Fix clang-format in ui_fpv_rx.cpp (update_visual_state block)
- Re-sample adjacent channels during candidate verification so
  neighbor_margin lock decision uses current measurements instead of
  stale channel_memory_ from scan (reduces false/missed locks)

Made-with: Cursor

* Rename fpv_rx to fpv_detect (files, dir, app id)

- Rename directory external/fpv_rx -> external/fpv_detect
- Rename ui_fpv_rx.{cpp,hpp} -> ui_fpv_detect.{cpp,hpp}
- Update external.cmake and external.ld for fpv_detect
- Namespace fpv_rx -> fpv_detect, class FpvRxView -> FpvDetectView
- Section/symbol .app_fpv_rx -> .app_fpv_detect

Made-with: Cursor
2026-03-16 10:28:07 +08:00
zxkmm b273165a0c fix warning and ub (#3089) 2026-03-14 00:51:15 +08:00
Frederic BORRY 5aecd4097e EPIRB TX Application (#3081)
* First step to epirb-tx app

* Next step to epirb_tx app

* Fixed merge

* EPIRB TX app progress

- Fixed UI
- Added automatic frame resend after delay
- Added load of beacons from EPIRB/BEACONS.TXT file

* First step to adding 121.5 MHz signal

* Refactored 121.5 signal generation code

* Added frequency change when switching from BPSK to AM

* Added checkbox for AM signal.

Added START/STOP button
Added AM frequency
First step to editor mode.

* Next step to frame editor

* Fixed location bits.

* Refactored code + fixed location

* Added location fields

* UI fixes + settings backup

Fixed lat/long display
Added send on change checkbox
Added settings backup
Fixed locator edition
Fixed BEACONS.TXT to move to Self test beacons.

* Update ui_epirb_tx.cpp

Fixed timeout reset

* Added national location protocol.

Added national location protocol.
Fixed send on change.

* UI fixes

Added country selection
Separated beacon protocol and beacon type selectors

* Standard protocol

Added standard protocol
Added internal checkbox

* Fixed fomratting

* Code cleanup

* Comments / doc

* More comments / doc

* More comments / doc

Fixed pre count duration.
Added frequency restore after leaving

* Prepare merge

* Prepare merge

* Finished merge

* More comments and doc

* Update ui_epirb_tx.cpp

Fixed out of memory error when using AlphanumView

* Update proc_epirb_tx.hpp

Fixed comment

* Fixed copilot PR comments.

* Update proc_epirb_tx.hpp

Fixed formatting

* Update external.ld

Merge with kiss_tnc app
2026-03-12 22:05:42 +13:00
qwer123 2c2959df30 change pin mux (#3085)
Co-authored-by: fuwenbo <16166717+fuwenbo95@user.noreply.gitee.com>
2026-03-12 20:24:42 +13:00
stafur 9a3c2cc6ac Next praline clean up (fixed BLE RX crashes) (#3080)
* Cleaned up #ifndef PRALINE and updated logic to being with #ifdef PRALINE entries where possible to make logic flow for PRALINE code execution pipeline clearer. Cleaned up compiletime warnings for PRALINE related codebase updates.

* Addressed comments provided by copilot during PR review. Combed through frequency definitions for consistency between PLL A and PLL B register definitions for CLKs 0-7. Ensured CLK3/LK6 <- SMA PORTs and CLK7 <- not utiliized are disabled during core development phase to support root cause analysis of any spectral artifacts. Updated MCU frequency to 40MHz to ensure audio harmonics are outside FM radio band range (< 80 MHz, >120MHz) and added comments clarifying choice of 40 over 10 MHz for potential future root cause analysis in other bands where audio may be expected as needed. Added CLK6 and CLK7 to Clocks Status View Debug display. Moved CLK defintions and PLL instantiations for components that are most RF sensitive to PLL A. Left others in PLL B. That is move FPGA CLK1 to PLL B, while moving CLK2, CLK4, and CLK5 to PLL A.

* Cleaned up PLL A and B XTAL reference checks relative to 800 MHz.

* Encapsulated HackRF Pro Praline debug and status vies into a single Pro Debug submenu as part of clean up.

* Fixed BLE RX Out of Memory error. Updated LPC43xx ld scripts to accouint for additional HackRF Pro praline memory.

* Addressed copilot comments for ble_rx_app by adding recent_entries_view.set_dirty. Updated ble_rx_app for easier use with heap limit set to one less than recent entries max limit.

* Addressed copilot comments by updating comment clarity in source files. Updated ui_debug to allow for return reference if set for PRO debug menu item.

* Improved readability of intialization parameters for the FPGA registers, and addressed 20Mhz nulls by initializing DC Notch width with standard setting, and DC Adaptiation rate with a balanced setting.

* Ran format-code.sh

* Added option to allow for user to set number if entries in recent list. Default is set to a relatively stable 32.

* Removed #ifdef PRALINE pragmas from ble_rx_app such that HackRF One can also use the updated UI widget to allow for user to set number of entries in recent list.

* Ran format-code.sh
2026-03-10 21:40:43 -04:00
zxkmm c91a6db165 remove redundant code from #3078 (#3082) 2026-03-10 16:13:10 +01:00
Sarah Rose bf5ea0a004 Add KISS TNC external app for APRS RX/TX over USB serial (#3078)
* Add KISS TNC external app for APRS RX/TX over USB serial

Adds a KISS TNC (Terminal Node Controller) app that bridges APRS
packets between the HackRF radio and a connected PC over USB CDC
serial using the KISS protocol.

Features:
- APRS receive at 144.390 MHz (configurable), decoding packets via
  the existing APRS RX baseband (PAPR.bin)
- Received AX.25 frames forwarded to host as KISS-framed data over
  USB serial
- KISS frames received from host transmitted as AFSK audio using the
  existing AFSK TX baseband (PAFT.bin)
- Clean RX->TX->RX baseband switching with proper timing delays
- USB connection status indicator with periodic refresh
- Compatible with standard KISS TNC clients (Xastir, APRSISCE/32,
  Dire Wolf, etc.)

Firmware changes required to support the external app:
- baseband_api.cpp: mark set_aprs() __attribute__((used)) so it is
  retained by the linker for external app use
- protocols/ax25: add make_frame_from_raw() to build NRZI bitstream
  from raw AX.25 bytes, marked __attribute__((used))
- usb_serial_host_to_device: add kiss_raw_handler hook to route
  incoming USB bytes directly to a registered callback, bypassing
  the shell; marked __attribute__((used))
- baseband/proc_aprsrx: add constructor that auto-configures at
  1200 baud so external apps do not need to call set_aprs() at init

* Address PR review: generic RAII USB handler, fix TX cutoff and buffer overflow

- Replace KISS-specific set_kiss_raw_handler() in shared USB code with a
  generic UsbSerialInputHandler RAII class; any app can now register a
  handler via the ctor and it auto-clears in the dtor — no app-specific
  'if' checks in shared code, no __attribute__((used)) needed
- Remove __attribute__((used)) from set_aprs() — it is referenced directly
  by ui_aprs_rx.cpp so it will never be dead-stripped
- Fix send_kiss_frame() buffer overflow: per-byte bounds check prevents
  2-byte escape sequences from writing past the end of the output buffer
- Replace fillOBuffer(TIME_INFINITE) with chOQWriteTimeout(TIME_IMMEDIATE)
  to drop bytes instead of blocking the event loop
- Remove chThdSleepMilliseconds() calls from start_tx() and finish_tx()
- Fix TX cutoff bug: call start_tx() directly from process_kiss_frame()
  instead of deferring via tx_pending_ flag (deferral caused kiss_idx_
  to be 0 by the time start_tx() fired, producing an empty frame)

* Move USB write into UsbSerialInputHandler class

Add a write() method to UsbSerialInputHandler so all USB I/O
(both input callback and output) is encapsulated in the class.
KISS TNC now uses usb_input_handler_->write() instead of calling
chOQWriteTimeout(&SUSBD1.oqueue, ...) directly, keeping raw USB
details out of app code.

* Address PR review: remove auto-configure from APRSRxProcessor, add timeout param to write()

- Remove default_config from APRSRxProcessor() constructor; baseband should
  start unconfigured and wait for APRSRxConfigureMessage from the app side
  (already sent via baseband::set_aprs() in KISS TNC and APRS RX app)
- Remove stray #include "stdio.h" from proc_aprsrx.cpp
- Add systime_t timeout parameter with default TIME_IMMEDIATE to
  UsbSerialInputHandler::write() so callers can choose blocking behaviour
2026-03-10 10:40:27 +01:00
Erwin Ried bf166bb2fc Update main video 2026-03-08 21:32:39 +01:00
stafur 52239d320a Next praline clean up (#3077)
* Cleaned up #ifndef PRALINE and updated logic to being with #ifdef PRALINE entries where possible to make logic flow for PRALINE code execution pipeline clearer. Cleaned up compiletime warnings for PRALINE related codebase updates.

* Addressed comments provided by copilot during PR review. Combed through frequency definitions for consistency between PLL A and PLL B register definitions for CLKs 0-7. Ensured CLK3/LK6 <- SMA PORTs and CLK7 <- not utiliized are disabled during core development phase to support root cause analysis of any spectral artifacts. Updated MCU frequency to 40MHz to ensure audio harmonics are outside FM radio band range (< 80 MHz, >120MHz) and added comments clarifying choice of 40 over 10 MHz for potential future root cause analysis in other bands where audio may be expected as needed. Added CLK6 and CLK7 to Clocks Status View Debug display. Moved CLK defintions and PLL instantiations for components that are most RF sensitive to PLL A. Left others in PLL B. That is move FPGA CLK1 to PLL B, while moving CLK2, CLK4, and CLK5 to PLL A.

* Cleaned up PLL A and B XTAL reference checks relative to 800 MHz.
2026-03-08 13:39:53 +13:00
E.T. 561143cfb0 Improve SD Card Status Display and Error Handling (#3079)
Summary:
Fixed SD card mount error detection by enabling immediate mounting, made the status icon clickable to access settings, and added real-time status display (including filesystem type) in the SD card settings page.

Changes:
- Changed f_mount() to immediate mounting for error detection
- Made SD card status icon clickable, linking to an enhanced sd card settings page that now includes live display of card status and filesystem type
- Removed "SDCard Error" menu item
2026-03-06 20:05:44 +01:00
jLynx 678ee2963e PortaRF & Windows tool update (#3075)
* Remove outdated DLL files and update HackRF submodule to latest commit

* Remove outdated msvcp120.dll and msvcr120.dll files
2026-03-06 09:41:56 +13:00
Sarah Rose bae3854d27 Add SAME TX external app (#3069)
* Add SAME TX external app

Adds a Specific Area Message Encoding (SAME/EAS) transmitter as an
external app (.ppma) for HackRF PortaPack.

SAME is the digital protocol used by NOAA Weather Radio and the
Emergency Alert System in the US and Canada for broadcasting
emergency alerts (tornado warnings, flash floods, EAN, etc.)
on 162.400-162.550 MHz and AM/FM broadcast stations.

Features:
- Originator code selector (WXR, EAS, CIV, PEP)
- Event code selector: 26 standard SAME event codes
  (RWT, TOR, SVR, FFW, EAN, etc.) with live name display
- FIPS location code entry (state 00-99 + county 000-999)
- Purge time entry (hours + minutes)
- Live message preview showing the encoded header
- AFSK encoding: mark=2083Hz, space=1563Hz, 520.833 baud
- FM deviation: 5 kHz, repeated 3x per SAME spec
- Default frequency: 162.550 MHz (WX channel 7)

Protocol details:
- 16-byte 0xAB preamble (bit-reversed for LSB-first AFSK)
- Header: ZCZC-ORG-EVT-SSPCCC+HHMM-JJJHHMM-STATION-
- Uses existing PAFT (proc_afsk) baseband image

* Apply clang-format via format-code.sh

* Add GPL license headers, guard re-entry, call set_transmitting(true)

- Add standard PortaPack GPL-2.0 license header to ui_same_tx.cpp and .hpp
- Guard start_tx() with tx_active_ to prevent re-entrant calls
- Call tx_view.set_transmitting(true) after starting TX so the
  TransmitterView button switches to stop mode
2026-03-05 19:49:17 +13:00
jLynx 0645f1897a Flashing: overhaul mayhem_flasher.bat with serial fallback and improved UX (#3074)
* Refactor mayhem_flasher.bat to streamline firmware flashing process and add serial fallback for device connection

* Improve COM port selection logic in mayhem_flasher.bat for better user input handling

* Enhance error handling in firmware flashing process for improved user feedback
2026-03-05 16:20:41 +13:00
jLynx da0a5c3e73 Fix on-device flash utility hanging on HackRF Pro (Praline) (#3073)
* Add support for W25Q32JV device ID in wait_for_device function

* Enhance mayhem_flasher.bat: Add DFU unbrick option and update firmware links
2026-03-05 14:49:32 +13:00
jLynx 22932e636d Switched build to use ninja by default (#3072)
* Initial plan

* Enable Ninja parallel builds for nightly and stable release pipelines

Co-authored-by: jLynx <4393979+jLynx@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-03-05 13:25:39 +13:00
E.T. 2b7302e659 rename Widget::visible to Widget::drawn (#3066)
* rename Widget::visible to Widget::drawn

* Update firmware/standalone/common/ui/ui_widget.cpp

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update firmware/standalone/common/ui/ui_widget.hpp

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix fm_radio usage of drawn()

---------

Co-authored-by: gullradriel <3157857+gullradriel@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-04 21:30:43 +01:00
jLynx 60ce89021a Combine per-device firmware ZIPs into a single unified flasher (#3070)
* Add combined firmware ZIP creation and update flashing script for device selection

* Refactor firmware flashing scripts and update README for improved device selection and actions

* Remove outdated flash script for PortaPack Mayhem

* Add write permissions to release jobs in nightly and stable release workflows

* Rename HackRF firmware files for consistency in nightly and stable release workflows

* Refactor release workflows to streamline asset preparation and upload process

* Fix file paths for HackRF firmware in nightly and stable release workflows

* Updated labels

* Refactor mayhem_flasher.bat for improved clarity

* Added reset after flash

Updated the flashing script to include error handling and improved user prompts.

* Remove --reset from DFU as it is known to cause issues
2026-03-05 08:40:39 +13:00
jLynx 25556428a7 Update HackRF flashing utilities for Windows (#3067)
* Update flasher for windows

* Updated scripts

* Fix echo statement formatting in flash script

* Fix echo statement formatting in flash script
2026-03-04 07:22:19 +00:00
stafur 584587d814 Resolve "crackling" sounds in analog_audio_app (#3068)
* Updated PRALINE audio processing methods to account for potential slip in 25MHz reference clock. Moved all clocks to PLLB except for CLK0 to isolate the ADC from potential EMI and clock spills from the other clocks to CLK0. Added PLL reference to Clock ui_debug display and added debug view for PLLA and PLLB. Updated PRO menu in analog_audio_app to allow for 100Hz resolution in sample rate for finer control of samplerate debugging of crackling noise artifacts. Updated ppb method and set it for account for a potential 49 Hz shift in the PRALINE crystal. Started instatiating methods for synchronized DMA transfers for the spectrogram since the FFT calculations and the LCD data updates appear to be related to the crackling noise.

* Added firmware/flash.h to .gitignore.

* Changed reference clock for start_audio_pll to 40MHz instead of ~12MHz xtal. Moved clocks around to reflect best audio quality in analog_audio_app at 3.072 MHz sample frequency.

* Ran format-code.sh.

* Removed ppb in set_sampling_frequency since it created aliasing in analog_audio_app.

* Expanded baseband_bandwidth back to 1750000 after testing since audio quality was retained.

* Updated comments to address copilot recommendations where acceptable.

* Removed firmware/flashsize.h from .gitignore as coordinated with @gullradriel.
2026-03-04 02:11:19 -05:00
Erwin Ried a0179117b1 Update README
Broken photo and links updated
2026-03-04 00:48:17 +01:00
gullradriel ad577a1c66 Delete firmware/flashsize.h (#3063)
Remove uneeded file
2026-03-02 23:43:23 +01:00
E.T. b9958a689b Btngrid better paging (#3061)
* improved paging for ui_btngrid

* move pgup and down to their own funcs in btngrid

* one line minus (format code)

* visible check before focus
2026-03-02 23:33:09 +01:00
E.T. 3d8bc308ee add checks to prevent crashes when showing an empty menu (#3060)
* add checks to prevent crashes when showing an empty menu

* Update firmware/application/ui/ui_btngrid.cpp

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-02 21:04:35 +01:00
zxkmm 9ca36394d0 add oscilloscope (time sink) app (#3059)
* POC

* submodule

* seperate bb

* seperate bb

* seperate bb

* seperate bb

* seperate bb

* sadly have to reduce history

* icon

* bring it back

* bring it back

* bb

* format and move bb outside
2026-03-02 19:17:02 +01:00
E.T. f489d43259 Auto update ext apps (#3046)
* first naive impl

* Unregister sdcard notification

* btngrid reload_items fixed

* format-code

* Avoid some unnecessary updates

* clear empty space after removing items

* Fix displaying sdcard error after inserting card while running

* format code

* Eliminate multiple update_items() calls from on_populate()
And call it only once after on_populate()

* update_items() only once when showing btngrid

* normalize offset when menu item count decreases
2026-03-02 12:35:45 +01:00
stafur 6b663894b0 Addresses comments from PR #3057 (#3058)
* Addressed clock inversion and fractiona/interger states. Created ui_debug display that checks expected clock frequencies for expected 3.072 MHz sampling frequency commonly utilizaed in portapack apps.

* Ran format-code.sh

* Addressed comments from PR. Ran format-code.sh. Updated definition of a, b, and c in comments and introduced x, y, and z for debug display. Changed default color for P2/P3 conditional debub display for MS_DIV. Removed implied recalibration since this did not address crackling sound.
2026-03-01 21:51:28 +01:00
stafur b8ca356ce3 Addressed clock inversion and fractional/interger states for 3.072 MHz sampling rate (#3057)
* Addressed clock inversion and fractiona/interger states. Created ui_debug display that checks expected clock frequencies for expected 3.072 MHz sampling frequency commonly utilizaed in portapack apps.

* Ran format-code.sh
2026-03-01 21:28:36 +01:00
stafur 3a54b112ec Imrpoved sound quality in analog_audio_app, and added Nyquist protection option to BBW filter for praline. (#3054) 2026-02-28 23:36:01 +01:00
stafur b013e68b17 Sampling frequency and Receiver Model tweaks. (#3053) 2026-02-28 10:11:04 +01:00
stafur b2bf0f2459 Legacy Initialization, Analog Audio App, and Aliasing fixes. (#3052)
* Added PRO button to analog_audio.cpp for debugging metallic ringing sounds in Audio app. Ensured consitency to 4MHz in analog_audio.cpp

* Restored blutooth after loss.

* Added several sampling rates to analog_audio for testing.

* Ran format-code.sh

* Fixed 0x03 mode for DC/Q-INV/Q-SHFT being set at every tuning and sample rate change. This was the root cause for loss of bluetooth before. Sample rate, and frequency can now be changed without need for manually resetting DC/Q-INV/Q-SHIFT settings. Updated method for setting frequncies in praline so that we have more testing options.

* Ran format-code.sh and cleaned up stale comments.

* Addressed comments, and removed commented line, opting for higher register values, 5E and 5D. Added WFM Debug View to support testing demodulation ringing.

* Addressed comments in PR conversation to clean comments and ensure consistency at initializtion accross updated methods and displays.

* Ran format-code.sh

* Set initial legacy state. Improved readability of clocking initialization settings. Updated set_sampling_frequency, and udpate_bandwidth to set decimation values in the fpga_registers to avoid aliasing in low band frequencies.

* Updated clock_manager to use correct clock and clock parameters for audio pll. Ran format-code.sh.
2026-02-27 23:43:19 -05:00
stafur 56adca3bf6 Resolved root cause for loss of bluetooth functionality and added more testing options (#3049)
* Added PRO button to analog_audio.cpp for debugging metallic ringing sounds in Audio app. Ensured consitency to 4MHz in analog_audio.cpp

* Restored blutooth after loss.

* Added several sampling rates to analog_audio for testing.

* Ran format-code.sh

* Fixed 0x03 mode for DC/Q-INV/Q-SHFT being set at every tuning and sample rate change. This was the root cause for loss of bluetooth before. Sample rate, and frequency can now be changed without need for manually resetting DC/Q-INV/Q-SHIFT settings. Updated method for setting frequncies in praline so that we have more testing options.

* Ran format-code.sh and cleaned up stale comments.

* Addressed comments, and removed commented line, opting for higher register values, 5E and 5D. Added WFM Debug View to support testing demodulation ringing.

* Addressed comments in PR conversation to clean comments and ensure consistency at initializtion accross updated methods and displays.

* Ran format-code.sh
2026-02-26 11:16:07 -05:00
stafur cd7c412aa4 Improve low band signal reception (FM Radio Station Audio tests) (#3048)
* Added PRO button to analog_audio.cpp for debugging metallic ringing sounds in Audio app. Ensured consitency to 4MHz in analog_audio.cpp

* Restored blutooth after loss.

* Added several sampling rates to analog_audio for testing.

* Ran format-code.sh
2026-02-25 03:29:21 -05:00
gullradriel 16c4c28584 fix guru in level / scanner / recon app (#3047)
* fix guru
* fix potential guru
* added information for the sudden return
2026-02-25 01:28:16 +01:00
Totoo 10d17fa7ce Fix device locking in grid item selection callback (#3044) 2026-02-24 16:32:05 +01:00
Totoo e63f54c0a2 Fixes (#3032) 2026-02-24 11:23:41 +01:00
stafur b09efb4d3c Mixer lock:: update clocks and move fpga_bridge_init to portapack.cpp (#3039)
* Updated harckrf_gpio methods to more closely reflect hackrf_usb. Added some ui debug updates to RFFC5072 Status View.

* Updated tuning tables for tuning.cpp. Remnoved 15MHz lower limit in max2831.cpp since lower bandwidths don't seem to be causing lower band issues. Added more opportunities for clocks to stabalize at startup in board.cpp. Added/amended UI to help with addresssing low band tuning issues. Cleaned up stale comments in radio.cpp.

* Ran format-code.sh

* Updated to remove commented lines as part of clean up addressing review comments.

* Fixed clock_manager.cpp configruation for praline. Praline hackrf pro should have: CLK4: 6mA, Invert RFFC5072 40MHz ref and CLK5: 4mA, Invert MAX2831 40MHz ref. Improvements should be visible in the watefall at 2.4GHz, and between 2.311 and 2.599GHz.

* After reviewin clock config, updated values to reflect: CLK0 MAX5864 (ADC) 40 MHz 4mA Normal Integer Minimizes sampling jitter for SNR. CLK1 iCE40 FPGA 40 MHz 6mA Normal Integer Stable timing for the SPI bridge. CLK2 LPC43xx MCU 40 MHz 4mA Normal Integer Standard reference for MCU PLL. CLK3 SMA Port P1 10 MHz 8mA Normal Integer Cleanest square wave for Ext Ref. CLK4 RFFC5072 (Mixer) 40 MHz 6mA Inverted Integer Crucial for PLL Lock stability. CLK5 MAX2831 (TRX) 40 MHz 4mA Inverted Integer Reduces phase noise in the 2.4GHz LO. CLK6 SMA Port P2 10 MHz 8mA Normal Integer Sync output for external gear. CLK7 Reserved Off N/A N/A N/A Disabled to save power/reduce EMI.

* Ran format-code.sh

* Moved fpga_brdige_init to portapack.cpp. This more closely resembles how hackrf_usb starts initializes the fpga, and allows time for the clocks to stabilize and facilitate locking to support low band tuning.

* Ran format-code.sh

* Added ProRadio Debug display to check for / debug locking.

* Moved fpga_bridge_init before radio_init in portapack.cpp

* Low band can now see signals. Updated clock_manager, rffc507 and portapack.cpp to ensure fpga intialized correctly. Ensures rffc507x.cpp has correct 40MHz reference frequency, prescaler, and synth configuration.

* Updated radio to add q-invert on, dc-block on, and deimation=3 (8x, for 20 -> 2.5 MHz decimation for testing cleaner low band signals.

* Ran format-code.sh
2026-02-24 03:36:55 -05:00
gullradriel bfbbacd43c Update hackrf submodule (#3034)
* fix warnings

* update hackrf submodule
2026-02-24 00:41:59 +01:00
Sandbox 065d01b591 Move POCSAG Tx to Ext. (#3033)
* Disable POCSAG TX in menu

Comment out POCSAG TX related code in ui_navigation.cpp

* Comment out ui_pocsag_tx.cpp in CMakeLists

Comment out the ui_pocsag_tx.cpp file in CMakeLists.

* Move POCSAG Tx to Ext.

* Update external.cmake

* Delete firmware/application/apps/ui_pocsag_tx.hpp

* Delete firmware/application/apps/ui_pocsag_tx.cpp

* Update main.cpp

* Update main.cpp

* Update external.ld

* fix namespace

* deleted commented out entry

* delete commented entries

* fix: correct baseband for pocsag tx

* run prepared

---------

Co-authored-by: gullradriel <gullradriel@users.noreply.github.com>
2026-02-23 21:37:03 +01:00
stafur b197a4b1de Update to CLK4 and CLK5 configuration for PRALINE. (#3031)
* Updated harckrf_gpio methods to more closely reflect hackrf_usb. Added some ui debug updates to RFFC5072 Status View.

* Updated tuning tables for tuning.cpp. Remnoved 15MHz lower limit in max2831.cpp since lower bandwidths don't seem to be causing lower band issues. Added more opportunities for clocks to stabalize at startup in board.cpp. Added/amended UI to help with addresssing low band tuning issues. Cleaned up stale comments in radio.cpp.

* Ran format-code.sh

* Updated to remove commented lines as part of clean up addressing review comments.

* Fixed clock_manager.cpp configruation for praline. Praline hackrf pro should have: CLK4: 6mA, Invert RFFC5072 40MHz ref and CLK5: 4mA, Invert MAX2831 40MHz ref. Improvements should be visible in the watefall at 2.4GHz, and between 2.311 and 2.599GHz.

* After reviewin clock config, updated values to reflect: CLK0 MAX5864 (ADC) 40 MHz 4mA Normal Integer Minimizes sampling jitter for SNR. CLK1 iCE40 FPGA 40 MHz 6mA Normal Integer Stable timing for the SPI bridge. CLK2 LPC43xx MCU 40 MHz 4mA Normal Integer Standard reference for MCU PLL. CLK3 SMA Port P1 10 MHz 8mA Normal Integer Cleanest square wave for Ext Ref. CLK4 RFFC5072 (Mixer) 40 MHz 6mA Inverted Integer Crucial for PLL Lock stability. CLK5 MAX2831 (TRX) 40 MHz 4mA Inverted Integer Reduces phase noise in the 2.4GHz LO. CLK6 SMA Port P2 10 MHz 8mA Normal Integer Sync output for external gear. CLK7 Reserved Off N/A N/A N/A Disabled to save power/reduce EMI.

* Ran format-code.sh
2026-02-22 21:31:46 -05:00
stafur 85eaa9d800 Updated praline low and high band tuning (#3030)
* Updated harckrf_gpio methods to more closely reflect hackrf_usb. Added some ui debug updates to RFFC5072 Status View.

* Updated tuning tables for tuning.cpp. Remnoved 15MHz lower limit in max2831.cpp since lower bandwidths don't seem to be causing lower band issues. Added more opportunities for clocks to stabalize at startup in board.cpp. Added/amended UI to help with addresssing low band tuning issues. Cleaned up stale comments in radio.cpp.

* Ran format-code.sh

* Updated to remove commented lines as part of clean up addressing review comments.
2026-02-23 13:40:49 +13:00
Sandbox 1ad092f341 ACARS Rx App using libacars (#3029)
* Using same decode as libacrars
* Enable ACARS RX
* indent + fix warning
* fixed CRC calculations, length validation, message print
Co-authored-by: gullradriel <gullradriel@users.noreply.github.com>
2026-02-22 21:29:20 +01:00
E.T. 0fe51fa7e3 Move flashsize.h to build directory to avoid conflicts when switching between different builds (#3021)
* Move flashsize.h to build directory to avoid conflicts when switching builds

plus small fix in praline image generation

* Update hackrf submodule to latest next

* fix fpga append comments

* Update firmware/CMakeLists.txt

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update firmware/CMakeLists.txt

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* remove ls dependency from build

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: gullradriel <gullradriel@users.noreply.github.com>
2026-02-22 21:21:03 +01:00
Sandbox 4cc2ba690b Add 12k5 RXBW to NFM Mode (#3023)
* Add 12k5 option to NFM
* Updated freqman_db
* Add 12k5 RXBW to NFM
* Add 12k5 RXBW
* formating
2026-02-22 20:53:26 +01:00
310 changed files with 23159 additions and 4995 deletions
+69
View File
@@ -0,0 +1,69 @@
<!--
👋 Thank you for your contribution!
⚠️ Before you start, please review our Contributing Guidelines:
https://github.com/portapack-mayhem/mayhem-firmware/wiki/Contributing-Guidelines
-->
## Brief description of what you did
<!-- Replace this line with a description of your changes. What problem does this PR solve? What does it add or fix?
Don't forget to describe how maintainers can test your modifications! -->
---
## Proof that your changes work
> ⚠️ **PRs without proof will not be merged.** Please provide evidence for every section below that applies to your change.
>
> 🛈 **Trusted contributors:** If you have a track record of merged PRs that were properly tested and documented, maintainers may waive one or more of the proof sections below at their discretion. You are still encouraged to include whatever evidence you have, but sections may be marked `N/A — trusted contributor` with a short note. First-time contributors must provide full proof. See the [Contributing Guidelines](https://github.com/portapack-mayhem/mayhem-firmware/wiki/Contributing-Guidelines) and [Trusted Contributors](https://github.com/portapack-mayhem/mayhem-firmware/wiki/Trusted-Contributors) articles for details.
### 🖥️ Proof it compiles
Attach a log snippet showing a successful build from the final firmware size/space summary in the build output. Example: `Space remaining in flash ROM: 19552 bytes ( 1.9 % )`.
<!-- Paste log below -->
### 📱 Proof of testing on a real device
Attach photos, screenshots, or a short video of your changes running on actual PortaPack hardware. **Emulator or simulator output is not a substitute for real-device testing.**
<!-- Paste photo / video / screenshot below -->
### 📡 Proof against a real emitter/receiver (if applicable)
If your PR involves RX/TX, protocol decoding, signal generation, or any RF-related functionality, you **must** demonstrate it working against a real emitter or receiver. Include photos, videos, logs, or waterfall/spectrum screenshots.
If this section does not apply to your PR, write `N/A` below and briefly explain why.
<!-- Paste RF evidence, or write N/A with a short justification -->
---
## 📚 Wiki documentation commitment
**By submitting this PR, you acknowledge that once it is merged you are responsible for creating or updating the corresponding page on the [project wiki](https://github.com/portapack-mayhem/mayhem-firmware/wiki).**
Your wiki article should include:
- A **screenshot of the main app screen** (strongly recommended)
- A clear **description** of what the app does
- An explanation of the **controls** and UI elements
- Any known **limitations**, quirks, or caveats
- Anything else a user should know to use the app effectively (dependencies, required hardware, file formats, etc.)
If you are modifying an existing app, make sure the wiki page reflects your changes.
---
## Checklist
- [ ] Kept changes minimal and limited to necessary files
- [ ] Verified functionality remains intact and code compiles
- [ ] Attached proof that the code compiles successfully *(or marked N/A as a trusted contributor)*
- [ ] Attached proof of testing on real PortaPack hardware *(or marked N/A as a trusted contributor)*
- [ ] Attached proof of testing against a real emitter/receiver (if RF-related), or marked N/A with justification
- [ ] I understand that by getting this PR merged, I am implicitly agreeing to create or update the corresponding wiki page (including a main-screen screenshot, description, controls, and limitations)
- [ ] I own all rights to this code (i.e., all code contained in this PR), including compliant usage rights for third-party libraries, and I agree that this code is licensed under the license of this project (GPL-3.0).
- [ ] If any third-party libraries are used, I confirm that their licenses comply with the requirements for contributing to this repository.
- [ ] Reviewed the [Contributing Guidelines](https://github.com/portapack-mayhem/mayhem-firmware/wiki/Contributing-Guidelines)
+37 -117
View File
@@ -72,7 +72,7 @@ jobs:
unzip world_map.zip -d sdcard/ADSB
- name: Prepare Firmware ZIP
run: |
cp build/hackrf/firmware/hackrf_usb/hackrf_usb.dfu flashing/utils/hackrf_one_usb.dfu && cp build/hackrf/firmware/hackrf_usb/hackrf_usb.bin flashing/utils/hackrf_one_usb.bin
mkdir -p flashing/firmware && cp build/hackrf/firmware/hackrf_usb/hackrf_usb.dfu flashing/firmware/hackrf_usb.dfu && cp build/hackrf/firmware/hackrf_usb/hackrf_usb.bin flashing/firmware/hackrf_usb.bin
- name: Create Firmware ZIP
run: |
zip -j firmware.zip build/firmware/portapack-mayhem-firmware.bin && cd flashing && zip -r ../firmware.zip *
@@ -103,6 +103,8 @@ jobs:
release:
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Get current date
id: date
@@ -129,14 +131,42 @@ jobs:
echo EOF
} >> "$GITHUB_OUTPUT"
id: changelog
# Combine all 3 device firmware bins into a single zip with device selector bat
- name: Create Combined Firmware ZIP
run: |
mkdir -p firmware_combined
unzip artifacts/firmware-default/firmware.zip -d firmware_combined
mv firmware_combined/portapack-mayhem-firmware.bin firmware_combined/firmware/firmware_hackrf.bin
unzip -j artifacts/firmware-portarf/firmware.zip portapack-mayhem-firmware.bin -d firmware_combined/firmware
mv firmware_combined/firmware/portapack-mayhem-firmware.bin firmware_combined/firmware/firmware_portarf.bin
unzip -j artifacts/firmware-hpro/firmware.zip portapack-mayhem-firmware.bin -d firmware_combined/firmware
mv firmware_combined/firmware/portapack-mayhem-firmware.bin firmware_combined/firmware/firmware_hpro.bin
unzip -j artifacts/firmware-hpro/firmware.zip firmware/hackrf_usb.dfu firmware/hackrf_usb.bin -d firmware_combined_hpro
mv firmware_combined_hpro/hackrf_usb.dfu firmware_combined/firmware/hackrf_hpro_usb.dfu
mv firmware_combined_hpro/hackrf_usb.bin firmware_combined/firmware/hackrf_hpro_usb.bin
cd firmware_combined && zip -r ../firmware_all_devices.zip . && cd ..
- name: Prepare release assets
run: |
VER="${{ steps.version_date.outputs.date }}"
mkdir -p release_assets
# OCI tar assets
cp artifacts/oci-tar-default/portapack-mayhem_OCI.ppfw.tar "release_assets/OCI_hackrf_mayhem_nightly_${VER}.ppfw.tar"
cp artifacts/oci-tar-portarf/portapack-mayhem_OCI.ppfw.tar "release_assets/OCI_portarf_mayhem_nightly_${VER}.ppfw.tar"
cp artifacts/oci-tar-hpro/portapack-mayhem_OCI.ppfw.tar "release_assets/OCI_hpro_mayhem_nightly_${VER}.ppfw.tar"
# Combined firmware
cp firmware_all_devices.zip "release_assets/FIRMWARE_mayhem_nightly_${VER}.zip"
# SD card assets
cp artifacts/sdcard-default/sdcard.zip "release_assets/COPY_TO_SDCARD_hackrf_mayhem_nightly_${VER}.zip"
cp artifacts/sdcard-no-map-default/sdcard-no-map.zip "release_assets/COPY_TO_SDCARD_hackrf_mayhem_nightly_${VER}-no-world-map.zip"
cp artifacts/sdcard-portarf/sdcard.zip "release_assets/COPY_TO_SDCARD_portarf_mayhem_nightly_${VER}.zip"
cp artifacts/sdcard-no-map-portarf/sdcard-no-map.zip "release_assets/COPY_TO_SDCARD_portarf_mayhem_nightly_${VER}-no-world-map.zip"
cp artifacts/sdcard-hpro/sdcard.zip "release_assets/COPY_TO_SDCARD_hpro_mayhem_nightly_${VER}.zip"
cp artifacts/sdcard-no-map-hpro/sdcard-no-map.zip "release_assets/COPY_TO_SDCARD_hpro_mayhem_nightly_${VER}-no-world-map.zip"
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
uses: softprops/action-gh-release@v2
with:
tag_name: nightly-tag-${{ steps.date.outputs.date }}
release_name: Nightly Release - ${{ steps.date.outputs.date }}
name: Nightly Release - ${{ steps.date.outputs.date }}
body: |
**Nightly release - ${{ steps.date.outputs.date }}**
This build is the latest and greatest, although may not be the most stable as this is a nightly release.
@@ -145,114 +175,4 @@ jobs:
${{ steps.changelog.outputs.content }}
draft: false
prerelease: true
# Default device assets
- name: Upload Default Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-default/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_hackrf_mayhem_nightly_${{ steps.version_date.outputs.date }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload Default Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-default/firmware.zip
asset_name: FIRMWARE_hackrf_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload Default SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-default/sdcard.zip
asset_name: COPY_TO_SDCARD_hackrf_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload Default SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-default/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_hackrf_mayhem_nightly_${{ steps.version_date.outputs.date }}-no-world-map.zip
asset_content_type: application/zip
# PortaRF device assets
- name: Upload PortaRF Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-portarf/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_portarf_mayhem_nightly_${{ steps.version_date.outputs.date }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload PortaRF Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-portarf/firmware.zip
asset_name: FIRMWARE_portarf_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload PortaRF SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-portarf/sdcard.zip
asset_name: COPY_TO_SDCARD_portarf_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload PortaRF SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-portarf/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_portarf_mayhem_nightly_${{ steps.version_date.outputs.date }}-no-world-map.zip
asset_content_type: application/zip
# HPro device assets
- name: Upload HPro Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-hpro/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_hpro_mayhem_nightly_${{ steps.version_date.outputs.date }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload HPro Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-hpro/firmware.zip
asset_name: FIRMWARE_hpro_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload HPro SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-hpro/sdcard.zip
asset_name: COPY_TO_SDCARD_hpro_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload HPro SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-hpro/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_hpro_mayhem_nightly_${{ steps.version_date.outputs.date }}-no-world-map.zip
asset_content_type: application/zip
files: release_assets/*
+37 -117
View File
@@ -55,7 +55,7 @@ jobs:
unzip world_map.zip -d sdcard/ADSB
- name: Prepare Firmware ZIP
run: |
cp build/hackrf/firmware/hackrf_usb/hackrf_usb.dfu flashing/utils/hackrf_one_usb.dfu && cp build/hackrf/firmware/hackrf_usb/hackrf_usb.bin flashing/utils/hackrf_one_usb.bin
mkdir -p flashing/firmware && cp build/hackrf/firmware/hackrf_usb/hackrf_usb.dfu flashing/firmware/hackrf_usb.dfu && cp build/hackrf/firmware/hackrf_usb/hackrf_usb.bin flashing/firmware/hackrf_usb.bin
- name: Create Firmware ZIP
run: |
zip -j firmware.zip build/firmware/portapack-mayhem-firmware.bin && cd flashing && zip -r ../firmware.zip *
@@ -86,6 +86,8 @@ jobs:
release:
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Get current date
id: date
@@ -115,14 +117,42 @@ jobs:
echo EOF
} >> "$GITHUB_OUTPUT"
id: changelog
# Combine all 3 device firmware bins into a single zip with device selector bat
- name: Create Combined Firmware ZIP
run: |
mkdir -p firmware_combined
unzip artifacts/firmware-default/firmware.zip -d firmware_combined
mv firmware_combined/portapack-mayhem-firmware.bin firmware_combined/firmware/firmware_hackrf.bin
unzip -j artifacts/firmware-portarf/firmware.zip portapack-mayhem-firmware.bin -d firmware_combined/firmware
mv firmware_combined/firmware/portapack-mayhem-firmware.bin firmware_combined/firmware/firmware_portarf.bin
unzip -j artifacts/firmware-hpro/firmware.zip portapack-mayhem-firmware.bin -d firmware_combined/firmware
mv firmware_combined/firmware/portapack-mayhem-firmware.bin firmware_combined/firmware/firmware_hpro.bin
unzip -j artifacts/firmware-hpro/firmware.zip firmware/hackrf_usb.dfu firmware/hackrf_usb.bin -d firmware_combined_hpro
mv firmware_combined_hpro/hackrf_usb.dfu firmware_combined/firmware/hackrf_hpro_usb.dfu
mv firmware_combined_hpro/hackrf_usb.bin firmware_combined/firmware/hackrf_hpro_usb.bin
cd firmware_combined && zip -r ../firmware_all_devices.zip . && cd ..
- name: Prepare release assets
run: |
VER="${{ steps.version.outputs.version }}"
mkdir -p release_assets
# OCI tar assets
cp artifacts/oci-tar-default/portapack-mayhem_OCI.ppfw.tar "release_assets/OCI_hackrf_mayhem_${VER}.ppfw.tar"
cp artifacts/oci-tar-portarf/portapack-mayhem_OCI.ppfw.tar "release_assets/OCI_portarf_mayhem_${VER}.ppfw.tar"
cp artifacts/oci-tar-hpro/portapack-mayhem_OCI.ppfw.tar "release_assets/OCI_hpro_mayhem_${VER}.ppfw.tar"
# Combined firmware
cp firmware_all_devices.zip "release_assets/FIRMWARE_mayhem_${VER}.zip"
# SD card assets
cp artifacts/sdcard-default/sdcard.zip "release_assets/COPY_TO_SDCARD_hackrf_mayhem_${VER}.zip"
cp artifacts/sdcard-no-map-default/sdcard-no-map.zip "release_assets/COPY_TO_SDCARD_hackrf_mayhem_${VER}-no-world-map.zip"
cp artifacts/sdcard-portarf/sdcard.zip "release_assets/COPY_TO_SDCARD_portarf_mayhem_${VER}.zip"
cp artifacts/sdcard-no-map-portarf/sdcard-no-map.zip "release_assets/COPY_TO_SDCARD_portarf_mayhem_${VER}-no-world-map.zip"
cp artifacts/sdcard-hpro/sdcard.zip "release_assets/COPY_TO_SDCARD_hpro_mayhem_${VER}.zip"
cp artifacts/sdcard-no-map-hpro/sdcard-no-map.zip "release_assets/COPY_TO_SDCARD_hpro_mayhem_${VER}-no-world-map.zip"
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.version.outputs.version }}
release_name: Mayhem firmware ${{ steps.version.outputs.version }}
name: Mayhem firmware ${{ steps.version.outputs.version }}
body: |
**Stable release - ${{ steps.version.outputs.version }}**
This is a fork of the [Havoc](https://github.com/furrtek/portapack-havoc/) firmware, which itself was a fork of the [PortaPack](https://github.com/sharebrained/portapack-hackrf) firmware, an add-on for the [HackRF](http://greatscottgadgets.com/hackrf/). Please check the [readme](https://github.com/portapack-mayhem/mayhem-firmware/blob/master/README.md) for details.
@@ -141,114 +171,4 @@ jobs:
For certain functionality, like external apps, the world map, GPS simulator, and others you need to uncompress (using [7-zip](https://www.7-zip.org/download.html)) the files from `mayhem_vX.Y.Z_COPY_TO_SDCARD.zip` to a FAT32 formatted MicroSD card.
draft: true
prerelease: false
# Default device assets
- name: Upload Default Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-default/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_hackrf_mayhem_${{ steps.version.outputs.version }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload Default Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-default/firmware.zip
asset_name: FIRMWARE_hackrf_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload Default SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-default/sdcard.zip
asset_name: COPY_TO_SDCARD_hackrf_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload Default SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-default/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_hackrf_mayhem_${{ steps.version.outputs.version }}-no-world-map.zip
asset_content_type: application/zip
# PortaRF device assets
- name: Upload PortaRF Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-portarf/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_portarf_mayhem_${{ steps.version.outputs.version }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload PortaRF Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-portarf/firmware.zip
asset_name: FIRMWARE_portarf_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload PortaRF SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-portarf/sdcard.zip
asset_name: COPY_TO_SDCARD_portarf_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload PortaRF SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-portarf/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_portarf_mayhem_${{ steps.version.outputs.version }}-no-world-map.zip
asset_content_type: application/zip
# HPro device assets
- name: Upload HPro Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-hpro/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_hpro_mayhem_${{ steps.version.outputs.version }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload HPro Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-hpro/firmware.zip
asset_name: FIRMWARE_hpro_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload HPro SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-hpro/sdcard.zip
asset_name: COPY_TO_SDCARD_hpro_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload HPro SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-hpro/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_hpro_mayhem_${{ steps.version.outputs.version }}-no-world-map.zip
asset_content_type: application/zip
files: release_assets/*
+1 -1
View File
@@ -1 +1 @@
v2.3.1
v2.3.2
+1 -1
View File
@@ -1 +1 @@
v2.3.2
v2.4.0
-2
View File
@@ -83,5 +83,3 @@ venv/
# generated bitmap arr file
# TODO: generate bitmap during build, since we use python during build anyway, lemme know if this is a bad idea @zxkmm
/firmware/tools/bitmap.hpp
# flashsize is generated by cmake
/firmware/flashsize.h
-3
View File
@@ -58,9 +58,6 @@ else()
math(EXPR FLASH_BYTES_LIMIT_SIZE "${FLASH_MB_LIMIT_SIZE} * 1024 * 1024")
endif()
#generate h files
configure_file(flashsize.h.in ${CMAKE_CURRENT_SOURCE_DIR}/firmware/flashsize.h)
option(USE_CCACHE "Enable ccache, please keep an eye on this because sometimes it's not quite stable and generated unusable binary" OFF)
project(portapack-h1)
+14 -7
View File
@@ -10,16 +10,20 @@
This is a fork of the [Havoc](https://github.com/furrtek/portapack-havoc/) firmware, which itself was a fork of the [PortaPack](https://github.com/sharebrained/portapack-hackrf) firmware, an add-on for the [HackRF](http://greatscottgadgets.com/hackrf/). A fork is a derivate, in this case one that has extra features and fixes when compared to the older versions.
[<img src="https://github.com/user-attachments/assets/dea337ab-fb64-4a2a-b419-69afd272e815" height="310">](https://github.com/portapack-mayhem/mayhem-firmware/wiki/PortaPack-Versions#new-h4m-mayhem-edition)
[<img src="https://camo.githubusercontent.com/5c1f1da0688240ac7b2ccca0c8dbfd1d73f2540741ad8b1828ba4d5ea68af248/68747470733a2f2f6769746875622d70726f64756374696f6e2d757365722d61737365742d3632313064662e73332e616d617a6f6e6177732e636f6d2f343339333937392f3239353533323731382d38653562363631632d663934362d346365652d386232642d3061363135663737313566342e706e67" height="310">](https://github.com/portapack-mayhem/mayhem-firmware/wiki/PortaPack-Versions#h2m-mayhem-edition)
[<img src="https://camo.githubusercontent.com/c1f7dd1e7672324f60a513f0de23de76da6a669e63896a9de535d8c8093fc3c7/68747470733a2f2f7261772e6769746875622e636f6d2f7368617265627261696e65642f706f7274617061636b2d6861636b72662f6d61737465722f646f632f696d616765732f68617264776172652f706f7274617061636b5f68315f6f7065726174696e672e6a7067" height="310">]([https://github.com/portapack-mayhem/mayhem-firmware/wiki/PortaPack-Versions#h2m-mayhem-edition](https://github.com/portapack-mayhem/mayhem-firmware/wiki/PortaPack-Versions#h1r1r2))
[<img src="https://github-production-user-asset-6210df.s3.amazonaws.com/4393979/295532718-8e5b661c-f946-4cee-8b2d-0a615f7715f4.png" height="310">](https://github.com/portapack-mayhem/mayhem-firmware/wiki/PortaPack-Versions#h2m-mayhem-edition)
# What is this?
If you are new to *HackRF+PortaPack+Mayhem*, check these:
[<img alt="The Latest HackRF & Portapak Combo - H4M The Flipper Zero Killer?" src="https://img.youtube.com/vi/Ew2qDgm2hf0/maxresdefault.jpg" width="701">](https://share.hackrf.app/6HKX9A)
[<img alt="PortaPack H4M Crash Course" src="https://img.youtube.com/vi/CjI-nUzdpas/maxresdefault.jpg" width="701">](https://share.hackrf.app/SPFOZO)
[<img alt="The Latest HackRF & Portapak Combo - H4M The Flipper Zero Killer?" src="https://img.youtube.com/vi/Ew2qDgm2hf0/maxresdefault.jpg" width="172">](https://share.hackrf.app/6HKX9A)
[<img alt="Its TOO Easy to Accidentally Do Illegal Stuff with This" src="https://img.youtube.com/vi/OPckpjBSAOw/maxresdefault.jpg" width="172">](https://share.hackrf.app/X4D5TF)
[<img alt="HackRF Portapack H4M - Getting Started Guide" src="https://img.youtube.com/vi/wzP0zWi85SI/maxresdefault.jpg" width="172">](https://share.hackrf.app/F9MPOO)
[<img alt="The new HackRF Portapack H4M" src="https://img.youtube.com/vi/onQRdCITmuk/maxresdefault.jpg" width="172">](https://share.hackrf.app/0JUHZ6)
[<img alt="Its TOO Easy to Accidentally Do Illegal Stuff with This" src="https://img.youtube.com/vi/OPckpjBSAOw/maxresdefault.jpg" width="172">](https://share.hackrf.app/X4D5TF) [<img alt="HackRF Portapack H4M - Getting Started Guide" src="https://img.youtube.com/vi/wzP0zWi85SI/maxresdefault.jpg" width="172">](https://share.hackrf.app/F9MPOO) [<img alt="The new HackRF Portapack H4M" src="https://img.youtube.com/vi/onQRdCITmuk/maxresdefault.jpg" width="172">](https://share.hackrf.app/0JUHZ6) [<img alt="HackRF 101 : Everything You Need to Know to Get Started!" src="https://img.youtube.com/vi/xGR_PMD9LeU/maxresdefault.jpg" width="172">](https://share.hackrf.app/C0J6ZR)
# Frequently Asked Questions
@@ -28,9 +32,9 @@ This repository expands upon the previous work by many people and aims to consta
## What to buy?
<!---not direct to h4m but to opensourcesdrlab https://share.hackrf.app/TUOLYI--->
:heavy_check_mark: ![Static Badge](https://img.shields.io/badge/NEW-yellow) The fabulous H4M [complete](https://share.hackrf.app/9UMBN5) or [upgrade](https://share.hackrf.app/30CQ55), featuring numerous improvements and accessories. Sold by our friends at [OpenSourceSDRLab](https://share.hackrf.app/99SAMT). Join their giveaways on discord (check the badge on top). _EU customers_ can purchase via [Lab401](https://share.hackrf.app/0CI2CR).
:heavy_check_mark: ![Static Badge](https://img.shields.io/badge/NEW-yellow) The fabulous H4M [complete](https://share.hackrf.app/DF2BZS) or [upgrade](https://share.hackrf.app/OCSJYI), featuring numerous improvements and accessories. Sold by our friends at [OpenSourceSDRLab](https://share.hackrf.app/99SAMT). Join their giveaways on discord (check the badge on top). _EU customers_ can purchase via [Lab401](https://share.hackrf.app/0CI2CR).
:heavy_check_mark: A recommended one is this [PortaPack H2](https://www.ebay.com/itm/116382397447), that includes everything you need with the plastic case "inspired" on [this](https://github.com/portapack-mayhem/mayhem-firmware/wiki/3d-printed-enclosure).
:heavy_check_mark: A recommended one is this [PortaPack H2](https://share.hackrf.app/QT5JMB), that includes everything you need with the plastic case "inspired" on [this](https://github.com/portapack-mayhem/mayhem-firmware/wiki/3d-printed-enclosure).
:heavy_check_mark: Some individuals lean towards the [H2 with a metal enclosure](https://share.hackrf.app/24T3TO), but its advantages remain debated. Share your insights on our [wiki](https://github.com/portapack-mayhem/mayhem-firmware/wiki/Hardware-overview).
@@ -47,7 +51,10 @@ This repository expands upon the previous work by many people and aims to consta
The current **stable release** is on the [![GitHub release (latest by date)](https://img.shields.io/github/v/release/portapack-mayhem/mayhem-firmware?label=Releases&style=social)](https://github.com/portapack-mayhem/mayhem-firmware/releases/latest) page. Follow the instructions you can find in the release description. The **latest (nightly) release** can be found [here](https://github.com/portapack-mayhem/mayhem-firmware/releases/).
## How can I collaborate
You can write [documentation](https://github.com/portapack-mayhem/mayhem-firmware/wiki), fix bugs and [answer issues](https://github.com/portapack-mayhem/mayhem-firmware/issues) or add new functionality. Please check the following [guide](https://github.com/portapack-mayhem/mayhem-firmware/wiki/How-to-collaborate) with details.
We warmly welcome your contributions! Please refer to our **[Contributing Guidelines](https://github.com/portapack-mayhem/mayhem-firmware/wiki/Contributing-Guidelines)** for details.
You can write [documentation](https://github.com/portapack-mayhem/mayhem-firmware/wiki), fix bugs and [answer issues](https://github.com/portapack-mayhem/mayhem-firmware/issues) or add new functionality. Please also check the following [guide](https://github.com/portapack-mayhem/mayhem-firmware/wiki/How-to-collaborate) with details.
Consider that the hardware and firmware has been created and maintain by a [lot](https://github.com/mossmann/hackrf/graphs/contributors) of [people](https://github.com/portapack-mayhem/mayhem-firmware/graphs/contributors), so always try collaborating your time and effort first. For coding related questions, if something does not fit as an issue, please join our Discord by clicking the chat badge on [top](#portapack-mayhem).
+17 -1
View File
@@ -1 +1,17 @@
Please check [Intended-Use-and-Legality](https://github.com/portapack-mayhem/mayhem-firmware/wiki/)
# Security Policy
## Scope and Threat Model
This repository hosts the codebase for an embedded system designed for security research. Because the system operates primarily offline, traditional network-based vulnerabilities are generally not applicable. However, we still welcome and review security reports concerning the code within this repository.
## Reporting a Vulnerability
If you discover a vulnerability within this tool itself, please submit a report. Please be aware that the maintainers do not promise assistance with obtaining CVE IDs or managing formal security advisories.
## Out of Scope
* **Vulnerabilities found *using* this tool:** Please do not submit reports here for vulnerabilities you have discovered in other systems or targets using this tool. This channel is strictly for reporting vulnerabilities found *in* the tool itself.
* **Other Repositories:** For security issues concerning related tools, such as MayhemHub, please submit your reports directly to their respective repositories.
## Research Attribution
If you utilize this tool to successfully discover vulnerabilities in external systems, we would greatly appreciate it if you credit or mention our project in your published research or write-ups.
## Legal and Security Disclaimer
For comprehensive guidelines regarding the legal and secure usage of this tool, as well as our full liability disclaimer, please refer to: [Intended-Use-and-Legality](https://github.com/portapack-mayhem/mayhem-firmware/wiki/). Users are expected to comply with all applicable laws and regulations when using this software and/or hardware.
+33 -26
View File
@@ -48,43 +48,50 @@ if(NOT ${CMAKE_CXX_COMPILER_VERSION} VERSION_EQUAL ${EXPECTED_GCC_VERSION})
set(GCC_VERSION_MISMATCH 1)
endif()
#generate h files
configure_file(flashsize.h.in flashsize.h)
add_compile_options(-include ${CMAKE_CURRENT_BINARY_DIR}/flashsize.h)
add_subdirectory(application)
add_subdirectory(baseband)
add_subdirectory(standalone)
add_subdirectory(test)
# NOTE: Dependencies break if the .bin files aren't included in DEPENDS. WTF, CMake?
add_custom_command(
OUTPUT ${FIRMWARE_FILENAME}
COMMAND ${MAKE_SPI_IMAGE} ${application_BINARY_DIR}/application.bin ${baseband_BINARY_DIR}/baseband.img ${FIRMWARE_FILENAME} ${FLASH_BYTES_LIMIT_SIZE}
DEPENDS baseband application ${MAKE_SPI_IMAGE}
${baseband_BINARY_DIR}/baseband.img ${application_BINARY_DIR}/application.bin
VERBATIM
)
if(BOARD STREQUAL "PRALINE")
math(EXPR PRALINE_FINAL_SIZE "4 * 1024 * 1024")
set(PRALINE_FPGA_BIN ${CMAKE_CURRENT_SOURCE_DIR}/../hackrf/firmware/fpga/build/praline_fpga.bin)
set(APPEND_FPGA_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/tools/append_fpga_bitstream.py)
# NOTE: Dependencies break if the .bin files aren't included in DEPENDS. WTF, CMake?
add_custom_command(
OUTPUT ${FIRMWARE_FILENAME}
COMMAND ${MAKE_SPI_IMAGE} ${application_BINARY_DIR}/application.bin ${baseband_BINARY_DIR}/baseband.img ${FIRMWARE_FILENAME} ${FLASH_BYTES_LIMIT_SIZE}
# PRALINE: Append FPGA bitstream to firmware at offset 0x380000
# The base firmware is 3.5MB, FPGA bitstream gets appended at the end of it, final size is 4MB
COMMAND ${CMAKE_COMMAND} -E echo "Appending PRALINE FPGA bitstream to firmware..."
COMMAND python3 ${APPEND_FPGA_SCRIPT} ${FIRMWARE_FILENAME} ${PRALINE_FPGA_BIN} ${FIRMWARE_FILENAME}.tmp ${PRALINE_FINAL_SIZE}
COMMAND ${CMAKE_COMMAND} -E rename ${FIRMWARE_FILENAME}.tmp ${FIRMWARE_FILENAME}
DEPENDS baseband application ${MAKE_SPI_IMAGE}
${baseband_BINARY_DIR}/baseband.img ${application_BINARY_DIR}/application.bin
${PRALINE_FPGA_BIN} ${APPEND_FPGA_SCRIPT}
VERBATIM
)
else() # Sadly this part had to be duplicated (or at least I couldn't find a better way to do it)
# NOTE: Dependencies break if the .bin files aren't included in DEPENDS. WTF, CMake?
add_custom_command(
OUTPUT ${FIRMWARE_FILENAME}
COMMAND ${MAKE_SPI_IMAGE} ${application_BINARY_DIR}/application.bin ${baseband_BINARY_DIR}/baseband.img ${FIRMWARE_FILENAME} ${FLASH_BYTES_LIMIT_SIZE}
DEPENDS baseband application ${MAKE_SPI_IMAGE}
${baseband_BINARY_DIR}/baseband.img ${application_BINARY_DIR}/application.bin
VERBATIM
)
endif()
add_custom_target(
firmware
DEPENDS ${FIRMWARE_FILENAME} ${HACKRF_FIRMWARE_DFU_FILENAME} ${HACKRF_FIRMWARE_FILENAME}
)
# PRALINE: Append FPGA bitstream to firmware at offset 0x180000
# The base firmware is 1MB, FPGA goes at 1MB offset, final size is 2MB
if(BOARD STREQUAL "PRALINE")
math(EXPR PRALINE_FINAL_SIZE "4 * 1024 * 1024")
set(PRALINE_FPGA_BIN ${CMAKE_CURRENT_SOURCE_DIR}/../hackrf/firmware/fpga/build/praline_fpga.bin)
set(APPEND_FPGA_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/tools/append_fpga_bitstream.py)
add_custom_command(
TARGET firmware POST_BUILD
COMMAND ${CMAKE_COMMAND} -E echo "Appending PRALINE FPGA bitstream to firmware..."
COMMAND python3 ${APPEND_FPGA_SCRIPT} ${FIRMWARE_FILENAME} ${PRALINE_FPGA_BIN} ${FIRMWARE_FILENAME}.tmp ${PRALINE_FINAL_SIZE}
COMMAND ${CMAKE_COMMAND} -E rename ${FIRMWARE_FILENAME}.tmp ${FIRMWARE_FILENAME}
COMMAND ${CMAKE_COMMAND} -E echo "PRALINE firmware with FPGA bitstream created:"
COMMAND ls -la ${FIRMWARE_FILENAME}
COMMENT "Appending PRALINE FPGA bitstream"
VERBATIM
)
endif()
if(${GCC_VERSION_MISMATCH})
set(COMPILER_MISMATCH_MESSAGE "WARNING: Compiler version mismatch, please use the official compiler version ${EXPECTED_GCC_VERSION} when sharing builds! Current compiler version: ${CMAKE_CXX_COMPILER_VERSION}")
message(${COMPILER_MISMATCH_MESSAGE})
-2
View File
@@ -305,7 +305,6 @@ set(CPPSRC
apps/ui_mictx.cpp
apps/ui_modemsetup.cpp
apps/ui_playlist.cpp
apps/ui_pocsag_tx.cpp
apps/ui_rds.cpp
apps/ui_recon_settings.cpp
apps/ui_recon.cpp
@@ -333,7 +332,6 @@ set(CPPSRC
${CPLD_H4M_DATA_CPP}
${HACKRF_CPLD_DATA_CPP}
ui_external_items_menu_loader.cpp
view_factory_base.cpp
)
set_source_files_properties(${CPPSRC} PROPERTIES COMPILE_FLAGS -flto) # Add lto flag to the non-external sources only
+69 -3
View File
@@ -199,6 +199,55 @@ SPECOptionsView::SPECOptionsView(
view->set_spec_iq_phase_calibration_value(view->get_spec_iq_phase_calibration_value()); // initialize iq_phase_calibration in radio
}
/* PralineOptionsView *******************************************************/
#ifdef PRALINE
PralineOptionsView::PralineOptionsView(Rect parent_rect, const Style* style) {
set_style(style);
set_parent_rect(parent_rect);
add_children({&label_sr, &options_sr, &label_dc, &options_dc,
&label_qi, &options_qi, &label_qs, &options_qs});
// READ the current state from hardware
fpga_reg_1 = radio::debug::fpga::register_read(1);
// INITIALIZE UI WIDGETS based on read bits
options_dc.set_by_value((fpga_reg_1 & 0x01) ? 1 : 0); // Bit 0
options_qi.set_by_value((fpga_reg_1 & 0x02) ? 1 : 0); // Bit 1
options_qs.set_by_value((fpga_reg_1 & 0x04) ? 1 : 0); // Bit 2
options_sr.set_value(receiver_model.sampling_rate());
options_sr.on_change = [this](int32_t v) { receiver_model.set_sampling_rate(static_cast<uint32_t>(v)); };
options_dc.on_change = [this](size_t, OptionsField::value_t v) {
if (v)
fpga_reg_1 |= 0x01;
else
fpga_reg_1 &= ~0x01;
update_fpga_ctrl();
};
options_qi.on_change = [this](size_t, OptionsField::value_t v) {
if (v)
fpga_reg_1 |= 0x02;
else
fpga_reg_1 &= ~0x02;
update_fpga_ctrl();
};
options_qs.on_change = [this](size_t, OptionsField::value_t v) {
if (v)
fpga_reg_1 |= 0x04;
else
fpga_reg_1 &= ~0x04;
update_fpga_ctrl();
};
}
void PralineOptionsView::update_fpga_ctrl() {
radio::debug::fpga::register_write(1, fpga_reg_1);
}
#endif
/* AnalogAudioView *******************************************************/
AnalogAudioView::AnalogAudioView(
@@ -217,7 +266,13 @@ AnalogAudioView::AnalogAudioView(
&field_volume,
&text_ctcss,
&record_view,
&waterfall});
#ifdef PRALINE
&waterfall,
&button_pro
#else
&waterfall
#endif
});
// Filename Datetime and Frequency
record_view.set_filename_date_frequency(true);
@@ -256,6 +311,10 @@ AnalogAudioView::AnalogAudioView(
field_frequency.set_value(receiver_model.target_frequency() + offset);
};
#ifdef PRALINE
button_pro.on_select = [this](Button&) { this->on_show_options_praline(); };
#endif
audio::output::start();
// This call starts the correct baseband image to run
@@ -360,10 +419,10 @@ void AnalogAudioView::on_baseband_bandwidth_changed(uint32_t bandwidth_hz) {
}
void AnalogAudioView::on_modulation_changed(ReceiverModel::Mode modulation) {
baseband::spectrum_streaming_stop();
waterfall.stop();
update_modulation(modulation);
on_show_options_modulation();
baseband::spectrum_streaming_start();
waterfall.start();
}
void AnalogAudioView::remove_options_widget() {
@@ -553,4 +612,11 @@ void AnalogAudioView::handle_coded_squelch(uint32_t value) {
void AnalogAudioView::on_freqchg(int64_t freq) {
field_frequency.set_value(freq);
}
#ifdef PRALINE
void AnalogAudioView::on_show_options_praline() {
set_options_widget(std::make_unique<PralineOptionsView>(options_view_rect, Theme::getInstance()->option_active));
}
#endif
} /* namespace ui */
@@ -37,6 +37,38 @@ namespace ui {
class AnalogAudioView;
#ifdef PRALINE
class PralineOptionsView : public View {
public:
PralineOptionsView(Rect parent_rect, const Style* style);
private:
// Layout: SR (Sample Rate), DC (DC Block), QI (Q-Invert), QS (Quarter Shift), D (Decim)
Text label_sr{{UI_POS_X(0), UI_POS_Y(0), UI_POS_WIDTH(2), UI_POS_HEIGHT(1)}, "SR"};
// Parameters: Position, Length (in chars), Range, Step, and default value
NumberField options_sr{
{UI_POS_X(3), UI_POS_Y(0)},
8, // Number of digits to show
{0, 40000000}, // Range: 0 to 40,000 kHz
100, // Step: 100 Hz
' ' // Fix: Single quotes for char
};
Text label_dc{{UI_POS_X(14), UI_POS_Y(0), UI_POS_WIDTH(2), UI_POS_HEIGHT(1)}, "DC"};
OptionsField options_dc{{UI_POS_X(16), UI_POS_Y(0)}, 2, {{"Of", 0}, {"On", 1}}};
Text label_qi{{UI_POS_X(20), UI_POS_Y(0), UI_POS_WIDTH(2), UI_POS_HEIGHT(1)}, "QI"};
OptionsField options_qi{{UI_POS_X(22), UI_POS_Y(0)}, 2, {{"Of", 0}, {"On", 1}}};
Text label_qs{{UI_POS_X(26), UI_POS_Y(0), UI_POS_WIDTH(2), UI_POS_HEIGHT(1)}, "QS"};
OptionsField options_qs{{UI_POS_X(28), UI_POS_Y(0)}, 2, {{"Of", 0}, {"On", 1}}};
uint8_t fpga_reg_1{0x00}; // Tracks DC, QI, QS bits
void update_fpga_ctrl();
};
#endif
class AMOptionsView : public View {
public:
AMOptionsView(AnalogAudioView* view, Rect parent_rect, const Style* style);
@@ -222,6 +254,11 @@ class AnalogAudioView : public View {
uint8_t get_previous_zoom_option();
void set_previous_zoom_option(uint8_t zoom);
#ifdef PRALINE
Button button_pro{{UI_POS_X(12), UI_POS_Y(2), UI_POS_WIDTH(3), UI_POS_HEIGHT(1)}, "PRO"};
void on_show_options_praline();
#endif
private:
static constexpr ui::Dim header_height = 3 * 16;
+40 -3
View File
@@ -645,6 +645,20 @@ BLERxView::BLERxView(NavigationView& nav)
options_sort.set_selected_index(sort_index, true);
options_filter.set_selected_index(filter_index, true);
// ------------------------------------------------------------------------------
// Handle Max Recent Entries
// ------------------------------------------------------------------------------
// Max Recent Entries UI widget
add_child(&label_max_entries);
add_child(&field_max_entries);
field_max_entries.set_value(max_recent_entries);
// Define what happens when the user changes the number
field_max_entries.on_change = [this](int32_t v) {
max_recent_entries = (size_t)v;
};
// Auto-configure modem for LCR RX (will be removed later)
baseband::set_btlerx(channel_number);
@@ -819,6 +833,10 @@ void BLERxView::on_data(BlePacketData* packet) {
recent.push_front(*it);
recent.erase(it);
} else {
// Enforce limit
while (recent.size() >= max_recent_entries) {
recent.pop_back();
}
recent.emplace_front(key);
truncate_entries(recent);
}
@@ -887,6 +905,9 @@ void BLERxView::on_filter_change(std::string value) {
}
void BLERxView::on_file_changed(const std::filesystem::path& new_file_path) {
// Clear searchList
searchList.clear();
file_path = new_file_path;
found_count = 0;
total_count = 0;
@@ -919,8 +940,10 @@ void BLERxView::on_file_changed(const std::filesystem::path& new_file_path) {
break;
}
searchList.push_back(currentLine);
total_count++;
if (searchList.size() < max_recent_entries) {
searchList.push_back(currentLine);
total_count++;
}
bytePos += bytesRead;
@@ -940,6 +963,21 @@ void BLERxView::on_timer() {
channel_number = (channel_number < 39) ? channel_number + 1 : 37;
}
}
// Debug: Check heap status every ~1 second
static int heap_check_counter = 0;
if (++heap_check_counter >= 60) {
heap_check_counter = 0;
size_t heap_free = chCoreStatus();
if (heap_free < 4096) { // Less than 4KB free
// Emergency: clear old entries
while (recent.size() > (max_recent_entries - 1)) {
recent.pop_back();
}
recent_entries_view.set_dirty();
}
}
if (ble_rx_error != BLE_RX_NO_ERROR) {
if (ble_rx_error == BLE_RX_LIST_FILENAME_EMPTY_ERROR) {
nav_.display_modal("Error", "List filename is empty !");
@@ -1059,7 +1097,6 @@ bool BLERxView::updateEntry(const BlePacketData* packet, BleRecentEntry& entry,
entry.dbValue = packet->max_dB - (receiver_model.lna() + receiver_model.vga() + (receiver_model.rf_amp() ? 14 : 0));
entry.timestamp = to_string_timestamp(rtc_time::now());
entry.dataString = data_string;
entry.packetData.type = packet->type;
entry.packetData.size = packet->size;
entry.packetData.dataLen = packet->dataLen;
+23 -2
View File
@@ -42,6 +42,12 @@
#include "recent_entries.hpp"
// Add for heap debugging
// For ChibiOS core functions
#include "ch.h"
#include "chcore.h"
#include "chheap.h"
class BLELogger {
public:
Optional<File::Error> append(const std::filesystem::path& filename) {
@@ -90,6 +96,7 @@ struct BleRecentEntry {
uint64_t uniqueKey;
int dbValue;
BlePacketData packetData;
std::string timestamp;
std::string dataString;
std::string nameString;
@@ -315,10 +322,10 @@ class BLERxView : public View {
{UI_POS_X(21), UI_POS_Y(0)}};
RSSI rssi{
{UI_POS_X(24), 0, UI_POS_WIDTH_REMAINING(6), 4}};
{UI_POS_X(24), 0, UI_POS_WIDTH_REMAINING(24), 4}};
Channel channel{
{UI_POS_X(24), 5, UI_POS_WIDTH_REMAINING(6), 4}};
{UI_POS_X(24), 5, UI_POS_WIDTH_REMAINING(24), 4}};
Labels label_sort{
{{UI_POS_X(0), UI_POS_Y(1)}, "Sort:", Theme::getInstance()->fg_light->foreground}};
@@ -426,6 +433,20 @@ class BLERxView : public View {
[this](const Message* const) {
this->on_timer();
}};
// Widget to control the list limit
Labels label_max_entries{
{{UI_POS_X(22), 10 * 8 - 2}, "List:", Theme::getInstance()->fg_light->foreground}};
NumberField field_max_entries{
{UI_POS_X(28), 10 * 8 - 2}, // Correct: Position (x, y)
2, // Number of digits
{5, 64}, // Range (min, max) <- Coincides with max_entries
1, // Step size
' ' // Filler character
};
// Variable to store the current limit
size_t max_recent_entries = 25;
}; /* BLERxView */
} /* namespace ui */
+1
View File
@@ -199,6 +199,7 @@ void BLETxView::send_packet() {
generateRandomMacAddress(randomMac);
char advertisementData[63] = {0};
packets[current_packet].advertisementData[62] = '\0';
strcpy(advertisementData, packets[current_packet].advertisementData);
// TODO: Make this a checkbox.
+126 -16
View File
@@ -28,6 +28,7 @@
#include "string_format.hpp"
#include "utility.hpp"
#include "file_path.hpp"
#include "usb_serial_asyncmsg.hpp"
using namespace portapack;
using namespace pocsag;
@@ -62,6 +63,7 @@ POCSAGSettingsView::POCSAGSettingsView(
&check_small_font,
&check_hide_bad,
&check_hide_addr_only,
&check_numeric_detect,
&opt_filter_mode,
&field_filter_address,
&button_save});
@@ -72,6 +74,7 @@ POCSAGSettingsView::POCSAGSettingsView(
check_small_font.set_value(settings_.enable_small_font);
check_hide_bad.set_value(settings_.hide_bad_data);
check_hide_addr_only.set_value(settings_.hide_addr_only);
check_numeric_detect.set_value(settings_.enable_numeric_detect);
opt_filter_mode.set_by_value(settings_.filter_mode);
field_filter_address.set_value(settings_.filter_address);
@@ -81,6 +84,7 @@ POCSAGSettingsView::POCSAGSettingsView(
settings_.enable_small_font = check_small_font.value();
settings_.hide_bad_data = check_hide_bad.value();
settings_.hide_addr_only = check_hide_addr_only.value();
settings_.enable_numeric_detect = check_numeric_detect.value();
settings_.filter_mode = opt_filter_mode.selected_index_value();
settings_.filter_address = field_filter_address.to_integer();
settings_.baud_rate = opt_baud_rate.selected_index_value();
@@ -219,12 +223,24 @@ void POCSAGAppView::handle_decoded(Timestamp timestamp, const std::string& prefi
return;
}
// Color indicates the message has a lot of decoding errors.
std::string color = bad_data ? STR_COLOR_MAGENTA : STR_COLOR_WHITE;
// Type indicator with its own color.
std::string type_str;
bool numeric_detect = settings_.enable_numeric_detect;
if (numeric_detect && pocsag_state.detected == pocsag::DET_NUMERIC)
type_str = STR_COLOR_GREEN "n";
else if (numeric_detect && pocsag_state.detected == pocsag::DET_ALPHA)
type_str = STR_COLOR_LIGHT_GREY "a";
else if (pocsag_state.out_type == ADDRESS)
type_str = STR_COLOR_DARK_YELLOW "t";
else
type_str = "";
std::string console_info = "\n" + color + prefix;
console_info += " #" + to_string_dec_uint(pocsag_state.address);
// Header: timestamp+baud in light grey, capcode+function in white.
std::string console_info = "\n" STR_COLOR_LIGHT_GREY + prefix;
console_info += STR_COLOR_WHITE " #" + to_string_dec_uint(pocsag_state.address);
console_info += " F" + to_string_dec_uint(pocsag_state.function);
if (!type_str.empty())
console_info += " " + type_str;
if (pocsag_state.out_type == ADDRESS) {
last_address = pocsag_state.address;
@@ -240,23 +256,111 @@ void POCSAGAppView::handle_decoded(Timestamp timestamp, const std::string& prefi
}
}
/* Serial: tone-only page */
if (portapack::usb_serial.serial_connected()) {
std::string s = "\r\nPOCSAG " + to_string_dec_uint(current_bitrate) + " " + to_string_dec_uint(pocsag_state.address) + " " + std::string(1, 'A' + pocsag_state.function) + (current_inverted ? " I" : " S") + " tone";
UsbSerialAsyncmsg::asyncmsg(s);
}
} else if (pocsag_state.out_type == MESSAGE) {
if (pocsag_state.address != last_address) {
// New message
if (pocsag_state.new_message) {
last_address = pocsag_state.address;
serial_numeric_sent = 0;
console.writeln(console_info);
console.write(color + pocsag_state.output);
// If heuristic chose numeric, show numeric line first (green).
if (numeric_detect &&
pocsag_state.detected == pocsag::DET_NUMERIC &&
pocsag_state.numeric_len > 0) {
std::string num_str(pocsag_state.numeric_buf, pocsag_state.numeric_len);
console.write(STR_COLOR_GREEN + num_str);
console.writeln("");
}
// Alpha decode (already has per-char color escapes from decoder).
console.write(pocsag_state.output);
/* Serial: header + first chunk.
* hex field contains rendered alpha as hex bytes (color escapes
* stripped). Non-printable chars show as '.' (0x2E),
* uncorrectable chars show as '?' (0x3F) — original 7-bit
* values are not preserved.
* Numeric decode goes in the quoted message field only. */
if (portapack::usb_serial.serial_connected()) {
/* Build hex representation of decoded alpha characters. */
std::string raw;
for (size_t i = 0; i < pocsag_state.output.size(); ++i)
raw += to_string_hex((uint8_t)pocsag_state.output[i], 2);
std::string s = "\r\nPOCSAG " + to_string_dec_uint(current_bitrate) + " " + to_string_dec_uint(pocsag_state.address) + " " + std::string(1, 'A' + pocsag_state.function) + (current_inverted ? " I" : " S");
if (numeric_detect && pocsag_state.detected == pocsag::DET_NUMERIC) {
s += " numeric \"";
if (pocsag_state.numeric_len > 0)
s += std::string(pocsag_state.numeric_buf, pocsag_state.numeric_len);
s += "\"";
serial_numeric_sent = pocsag_state.numeric_len;
} else {
/* For alpha, the quoted text is the same chars as raw but as ASCII.
* Escape " and \ to avoid breaking the quoted field. */
s += " alpha \"";
for (size_t i = 0; i < pocsag_state.output.size(); ++i) {
if (pocsag_state.output[i] == '"' || pocsag_state.output[i] == '\\') {
s += '\\';
}
s += pocsag_state.output[i];
}
s += "\"";
}
s += " hex:" + raw;
UsbSerialAsyncmsg::asyncmsg(s);
}
} else {
// Message continues...
console.write(color + pocsag_state.output);
// Message continues from previous batch.
bool is_numeric = numeric_detect && pocsag_state.detected == pocsag::DET_NUMERIC;
// GUI: show numeric continuation if applicable.
if (is_numeric && pocsag_state.numeric_len > serial_numeric_sent) {
std::string num_str(pocsag_state.numeric_buf + serial_numeric_sent,
pocsag_state.numeric_len - serial_numeric_sent);
console.write(STR_COLOR_GREEN + num_str);
}
console.write(pocsag_state.output);
/* Serial: continuation chunk with full header.
* Type label carries over from first batch (numeric+ or alpha+). */
if (portapack::usb_serial.serial_connected()) {
std::string raw;
std::string decoded;
for (size_t i = 0; i < pocsag_state.output.size(); ++i) {
if (pocsag_state.output[i] == '"' || pocsag_state.output[i] == '\\')
decoded += '\\';
decoded += pocsag_state.output[i];
raw += to_string_hex((uint8_t)pocsag_state.output[i], 2);
}
if (!decoded.empty() || pocsag_state.numeric_len > serial_numeric_sent) {
std::string s = "\r\nPOCSAG " + to_string_dec_uint(current_bitrate) + " " + to_string_dec_uint(pocsag_state.address) + " " + std::string(1, 'A' + pocsag_state.function) + (current_inverted ? " I" : " S") + (is_numeric ? " numeric+" : " alpha+") + " \"";
if (is_numeric && pocsag_state.numeric_len > serial_numeric_sent)
s += std::string(pocsag_state.numeric_buf + serial_numeric_sent,
pocsag_state.numeric_len - serial_numeric_sent);
else
s += decoded;
s += "\" hex:" + raw;
UsbSerialAsyncmsg::asyncmsg(s);
}
}
serial_numeric_sent = pocsag_state.numeric_len;
}
if (logging()) {
logger.log_decoded(
timestamp,
to_string_dec_uint(pocsag_state.address) +
" F" + to_string_dec_uint(pocsag_state.function) +
" " + pocsag_state.output);
std::string log_entry = to_string_dec_uint(pocsag_state.address) +
" F" + to_string_dec_uint(pocsag_state.function);
if (numeric_detect &&
pocsag_state.detected == pocsag::DET_NUMERIC &&
pocsag_state.numeric_len > 0)
log_entry += " N:" + std::string(pocsag_state.numeric_buf, pocsag_state.numeric_len);
log_entry += " " + pocsag_state.output;
logger.log_decoded(timestamp, log_entry);
}
}
}
@@ -300,13 +404,19 @@ void POCSAGAppView::on_packet(const POCSAGPacketMessage* message) {
image_status.set_foreground(Theme::getInstance()->fg_magenta->foreground);
pocsag_state.codeword_index = 0;
pocsag_state.errors = 0;
current_bitrate = message->packet.bitrate();
current_inverted = message->packet.inverted();
// Handle multiple messages (if any).
while (pocsag_decode_batch(message->packet, pocsag_state))
handle_decoded(message->packet.timestamp(), prefix);
// Handle the remainder.
handle_decoded(message->packet.timestamp(), prefix);
// Handle the remainder. Skip if decoder is still in
// STATE_HAVE_ADDRESS — the address was at the end of this
// batch and we can't yet tell if it's tone-only or has
// message data in the next batch.
if (pocsag_state.mode != STATE_HAVE_ADDRESS)
handle_decoded(message->packet.timestamp(), prefix);
}
// Set status icon color to indicate state machine state.
+16 -5
View File
@@ -125,6 +125,7 @@ struct POCSAGSettings {
bool enable_raw_log = false;
bool hide_bad_data = false;
bool hide_addr_only = false;
bool enable_numeric_detect = true; /* heuristic alpha/numeric type detection */
uint8_t filter_mode = false;
int32_t baud_rate = -1;
uint32_t filter_address = 0;
@@ -150,8 +151,8 @@ class POCSAGSettingsView : public View {
Labels labels{
{{2 * 8, 0 * 16}, "Baud:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 12 * 16}, "Filter Mode:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 13 * 16}, "Filter Addr:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 14 * 16}, "Filter Mode:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 15 * 16}, "Filter Addr:", Theme::getInstance()->fg_light->foreground},
};
Checkbox check_log{
@@ -179,21 +180,26 @@ class POCSAGSettingsView : public View {
22,
"Hide Addr Only"};
Checkbox check_numeric_detect{
{2 * 8, 12 * 16},
22,
"Detect Numeric"};
OptionsField opt_filter_mode{
{15 * 8, 12 * 16},
{15 * 8, 14 * 16},
4,
{{"None", FILTER_NONE},
{"Drop", FILTER_DROP},
{"Keep", FILTER_KEEP}}};
SymField field_filter_address{
{15 * 8, 13 * 16},
{15 * 8, 15 * 16},
7,
SymField::Type::Dec,
true /*explicit_edit*/};
Button button_save{
{UI_POS_X_CENTER(10), UI_POS_Y(16), 10 * 8, 2 * 16},
{UI_POS_X_CENTER(10), UI_POS_Y(17), 10 * 8, 2 * 16},
"Save"};
};
@@ -231,6 +237,7 @@ class POCSAGAppView : public View {
{"filter_address"sv, &settings_.filter_address},
{"hide_bad_data"sv, &settings_.hide_bad_data},
{"hide_addr_only"sv, &settings_.hide_addr_only},
{"numeric_detect"sv, &settings_.enable_numeric_detect},
{"baud_rate"sv, &settings_.baud_rate},
}};
@@ -241,6 +248,10 @@ class POCSAGAppView : public View {
void on_stats(const POCSAGStatsMessage* stats);
uint32_t last_address = 0;
uint16_t current_bitrate = 0; /* bitrate of current packet being decoded */
bool current_inverted = false; /* polarity of current packet being decoded */
uint8_t serial_numeric_sent = 0; /* numeric chars already sent to serial/GUI */
pocsag::EccContainer ecc{};
pocsag::POCSAGState pocsag_state{&ecc};
POCSAGLogger logger{};
+8 -13
View File
@@ -27,6 +27,8 @@
#include "portapack.hpp"
#include "battery.hpp"
#include <cstring>
#include "ui_settings.hpp"
#include "portapack_persistent_memory.hpp"
using namespace portapack;
@@ -138,10 +140,8 @@ void BattinfoView::update_result() {
}
if ((valid_mask & battery::BatteryManagement::BATT_VALID_PERCENT) == battery::BatteryManagement::BATT_VALID_PERCENT) {
text_method.set("IC");
button_mode.set_text("Volt");
} else {
text_method.set("Voltage");
button_mode.set_text("IC");
}
if (uichg) set_dirty();
// to update status bar too, send message in behalf of batt manager
@@ -158,8 +158,9 @@ BattinfoView::BattinfoView(NavigationView& nav)
&text_current,
&text_charge,
&text_method,
&button_mode,
&button_settings,
&button_exit,
&text_capacity,
// &text_cycles,
// &text_warn,
&text_ttef});
@@ -167,17 +168,11 @@ BattinfoView::BattinfoView(NavigationView& nav)
button_exit.on_select = [this, &nav](Button&) {
nav.pop();
};
button_mode.on_select = [this, &nav](Button&) {
if (button_mode.text() == "IC") {
battery::BatteryManagement::set_calc_override(false);
persistent_memory::set_ui_override_batt_calc(false);
button_mode.set_text("Volt");
} else {
battery::BatteryManagement::set_calc_override(true);
persistent_memory::set_ui_override_batt_calc(true);
button_mode.set_text("IC");
}
button_settings.on_select = [this, &nav](Button&) {
nav.replace<SetBatteryView>();
};
text_capacity.set(to_string_dec_uint(persistent_memory::battery_cap_mah()) + " mAh");
if (!persistent_memory::battery_cap_valid()) text_capacity.set_style(Theme::getInstance()->fg_red);
update_result();
if (thread == nullptr) thread = chThdCreateFromHeap(NULL, 1024, NORMALPRIO + 10, BattinfoView::static_fn, this);
}
+25 -20
View File
@@ -54,48 +54,53 @@ class BattinfoView : public View {
int32_t current = 0;
Labels labels{
{{2 * 8, 1 * 16}, "Percent:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 2 * 16}, "Voltage:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 3 * 16}, "Method:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(1)}, "Percent:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(2)}, "Voltage:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(3)}, "Method:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(4)}, "Capacity:", Theme::getInstance()->fg_light->foreground},
};
Labels labels_opt{
{{2 * 8, 4 * 16}, "Current:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 5 * 16}, "Charge:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 6 * 16}, "TTF/E:", Theme::getInstance()->fg_light->foreground},
// {{2 * 8, 7 * 16}, "Cycles:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 10 * 16}, "Change method:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(5)}, "Current:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(6)}, "Charge:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(7)}, "TTF/E:", Theme::getInstance()->fg_light->foreground},
// {{UI_POS_X(2), UI_POS_Y(8)}, "Cycles:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(10)}, "Change settings:", Theme::getInstance()->fg_light->foreground},
};
Text text_percent{
{13 * 8, 1 * 16, 10 * 16, 16},
{UI_POS_X(13), UI_POS_Y(1), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)},
"-"};
Text text_voltage{
{13 * 8, 2 * 16, 10 * 16, 16},
{UI_POS_X(13), UI_POS_Y(2), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)},
"-"};
Text text_method{
{13 * 8, 3 * 16, 10 * 16, 16},
{UI_POS_X(13), UI_POS_Y(3), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)},
"-"};
Text text_capacity{
{UI_POS_X(13), UI_POS_Y(4), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)},
"-"};
Text text_current{
{13 * 8, 4 * 16, 10 * 16, 16},
{UI_POS_X(13), UI_POS_Y(5), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)},
"-"};
Text text_charge{
{13 * 8, 5 * 16, 10 * 16, 16},
{UI_POS_X(13), UI_POS_Y(6), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)},
"-"};
Text text_ttef{
{13 * 8, 6 * 16, 10 * 16, 16},
{UI_POS_X(13), UI_POS_Y(7), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)},
"-"};
/* Text text_cycles{
{13 * 8, 7 * 16, 10 * 16, 16},
{UI_POS_X(13), UI_POS_Y(8), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)},
"-"};
Text text_warn{
{1 * 8, 8 * 16, screen_width, 2 * 16},
{UI_POS_X(1), UI_POS_Y(9), screen_width, UI_POS_HEIGHT(2)},
""}; */
Button button_mode{
{2 * 8, 11 * 16 + 5, 5 * 16, 32},
"Volt"};
Button button_settings{
{UI_POS_X(2), UI_POS_Y(11) + 5, UI_POS_WIDTH(10), UI_POS_HEIGHT(2)},
"Settings"};
Button button_exit{
{UI_POS_X_CENTER(12), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(12), UI_POS_HEIGHT(2)},
@@ -106,4 +111,4 @@ class BattinfoView : public View {
} /* namespace ui */
#endif /*__UI_BATTINFO__*/
#endif /*__UI_BATTINFO__*/
File diff suppressed because it is too large Load Diff
+382 -7
View File
@@ -438,6 +438,123 @@ class RadioDiagnosticsView : public View {
"Done"};
};
#ifdef PRALINE
class PralineDebugMenuView : public BtnGridView {
public:
PralineDebugMenuView(NavigationView& nav);
std::string title() const override { return "Pro Debug"; };
private:
NavigationView& nav_;
void on_populate() override;
};
/* Praline-Specific Radio Debug View
* Monitors Mixer Lock, SPI Bit Depth, and toggles Si5351 CLK5
*/
class PralineRadioDebugView : public View {
public:
PralineRadioDebugView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Pro Radio Debug"; };
private:
void refresh();
void toggle_clk5();
Text text_title{{0, 0, 240, 16}, "=== Pro Radio Debug ==="};
// Mixer Lock (PD_11 / GPIO6[25])
Text text_lbl_lock{{0, 24, 124, 16}, "Mix Lock (LD):"};
Text text_lock_status{{126, 24, 114, 16}, "---"};
// Si5351 CLK5 (Mixer Reference)
Text text_lbl_clk5{{0, 40, 124, 16}, "Si5351 CLK5(Mix):"};
Text text_clk5_status{{126, 40, 114, 16}, "---"};
// SPI Bus configuration check
Text text_lbl_spi{{0, 56, 124, 16}, "SPI Bit Mode:"};
Text text_spi_status{{126, 56, 118, 16}, "---"};
// FPGA DC Block (Reg 1)
Text text_lbl_fpga_ctrl{{0, 72, 124, 16}, "FPGA Reg 1:"};
Text text_fpga_ctrl{{126, 72, 118, 16}, "---"};
// VAA Power Rail (P8_1 / GPIO4[1])
Text text_lbl_vaa{{0, 88, 124, 16}, "VAA RF Power:"};
Text text_vaa_status{{126, 88, 118, 16}, "---"};
Text text_status_msg{{0, 110, 240, 48}, ""};
Button button_refresh{{8, 240, 72, 24}, "Refresh"};
Button button_toggle_clk5{{88, 240, 72, 24}, "CLK5_T"};
Button button_done{{168, 240, 64, 24}, "Done"};
};
#endif
/* WFMAudioDebugView ***************************************************/
#ifdef PRALINE
class WFMAudioDebugView : public View {
public:
WFMAudioDebugView(NavigationView& nav);
void focus() override;
std::string title() const override { return "WFM Audio Debug"; }
private:
void refresh();
NavigationView& nav_;
Text text_title{{0, 0, 240, 16}, "=== WFM Audio Debug ==="};
// Sample rates section
Text text_lbl_clk0{{0, 20, 140, 16}, "Si5351 CLK0 Rate:"};
Text text_clk0{{150, 20, 90, 16}, "---"};
Text text_lbl_fpga_dec{{0, 36, 140, 16}, "FPGA Decimation:"};
Text text_fpga_dec{{150, 36, 90, 16}, "---"};
Text text_lbl_post_fpga{{0, 52, 140, 16}, "Post-FPGA Rate:"};
Text text_post_fpga{{150, 52, 90, 16}, "---"};
// MAX2831 section
Text text_section1{{0, 72, 240, 16}, "--- MAX2831 LPF ---"};
Text text_lbl_reg8{{0, 88, 140, 16}, "Reg8 (LPF RX):"};
Text text_reg8{{150, 88, 90, 16}, "---"};
Text text_lbl_lpf_bw{{0, 104, 140, 16}, "LPF Bandwidth:"};
Text text_lpf_bw{{150, 104, 90, 16}, "---"};
// FPGA section
Text text_section2{{0, 124, 240, 16}, "--- FPGA Control ---"};
Text text_lbl_fpga_r1{{0, 140, 140, 16}, "Reg1 (Ctrl):"};
Text text_fpga_r1{{150, 140, 90, 16}, "---"};
Text text_lbl_dc_q{{0, 156, 70, 16}, "DC/Q/QS:"};
Text text_dc_q{{72, 156, 168, 16}, "---"};
// Audio section
Text text_section3{{0, 176, 240, 16}, "--- Audio Path ---"};
Text text_lbl_expected{{0, 192, 96, 16}, "Expctd Aud:"};
Text text_expected{{98, 192, 142, 16}, "---"};
Text text_lbl_deemph{{0, 208, 96, 16}, "D-emph Cfg:"};
Text text_deemph{{98, 208, 132, 16}, "---"};
// Status
Text text_status{{0, 228, 240, 16}, "---"};
Text text_status2{{0, 244, 240, 16}, "---"};
Button button_refresh{{10, 268, 70, 24}, "Refresh"};
Button button_toggle_q{{90, 268, 70, 24}, "Toggle Q"};
Button button_done{{170, 268, 60, 24}, "Done"};
};
#endif
/* BasebandStatusView ***************************************************/
class BasebandStatusView : public View {
@@ -804,10 +921,9 @@ class RFFC5072StatusView : public View {
NavigationView& nav_;
void refresh_status();
Text text_title{{0, 0, 240, 16}, "=== RFFC5072 (1st IF) ==="};
Text text_status{{0, 0, 240, 16}, "---"};
Text text_lbl_lock{{0, 16, 114, 16}, "Lock Detect:"};
Text text_lock{{116, 16, 124, 16}, "---"};
Text text_gpio4{{0, 16, 240, 16}, "---"};
Text text_ctrl{{0, 32, 240, 16}, "---"};
@@ -841,13 +957,13 @@ class RFFC5072StatusView : public View {
Text text_lbl_calc{{0, 192, 114, 16}, "Calc freq:"};
Text text_calc{{116, 192, 124, 16}, "---"};
Text text_status{{0, 208, 240, 16}, ""};
Text text_regs_status{{0, 208, 240, 16}, "---"};
Text text_lbl_regs_status{{0, 224, 48, 16}, "Regs:"};
Text text_regs_status{{50, 224, 190, 16}, "---"};
Text text_status2{{0, 224, 240, 16}, ""};
Text text_status3{{0, 240, 240, 16}, ""};
Button button_refresh{{2, 280, 72, 24}, "Refresh"};
Button button_force_enx{{98, 280, 60, 24}, "T_ENX"};
Button button_force{{98, 280, 60, 24}, "SPI"};
Button button_done{{182, 280, 56, 24}, "Done"};
};
@@ -1019,6 +1135,265 @@ class SystemDiagnosticsView : public View {
};
#endif
#ifdef PRALINE
/* Si5351PLLADebugView - Debug fractional parameters for PLL A */
class Si5351PLLADebugView : public View {
public:
Si5351PLLADebugView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Si5351 PLL A Debug"; };
private:
NavigationView& nav_;
void refresh();
Text text_title{{0, 0, 240, 16}, "===PLL A Fractional Debug==="};
// Raw register values
Text text_lbl_raw{{0, 24, 240, 16}, "---Raw Registers (26-33)---"};
Text text_r26_27{{8, 40, 224, 16}, "---"};
Text text_r28_30{{8, 56, 224, 16}, "---"};
Text text_r31_33{{8, 72, 224, 16}, "---"};
// Decoded values
Text text_lbl_decoded{{0, 96, 240, 16}, "---Decoded Parameters---"};
Text text_lbl_p1{{0, 112, 48, 16}, "P1:"};
Text text_p1{{50, 112, 190, 16}, "---"};
Text text_lbl_p2{{0, 128, 48, 16}, "P2:"};
Text text_p2{{50, 128, 190, 16}, "---"};
Text text_lbl_p3{{0, 144, 48, 16}, "P3:"};
Text text_p3{{50, 144, 190, 16}, "---"};
// Calculated VCO
Text text_lbl_calc{{0, 168, 240, 16}, "---Calculated VCO---"};
Text text_lbl_mult{{0, 184, 80, 16}, "Multiplier:"};
Text text_mult{{82, 184, 158, 16}, "---"};
Text text_lbl_vco{{0, 200, 80, 16}, "VCO Freq:"};
Text text_vco{{82, 200, 158, 16}, "---"};
Text text_status{{0, 224, 240, 32}, ""};
Button button_refresh{{8, 280, 100, 24}, "Refresh"};
Button button_done{{132, 280, 100, 24}, "Done"};
};
#endif
#ifdef PRALINE
class Si5351PLLBDebugView : public View {
public:
Si5351PLLBDebugView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Si5351 PLL B Debug"; };
private:
void refresh();
NavigationView& nav_;
Text text_title{{0, 0, 240, 16}, "=== PLL B Fractional Debug ==="};
Text text_lbl_raw{{0, 24, 240, 16}, "--- Raw Registers (34-41) ---"};
Text text_r34_35{{8, 40, 224, 16}, "---"};
Text text_r36_38{{8, 56, 224, 16}, "---"};
Text text_r39_41{{8, 72, 224, 16}, "---"};
Text text_lbl_decoded{{0, 96, 240, 16}, "--- Decoded Parameters ---"};
Text text_lbl_p1{{0, 112, 48, 16}, "P1:"};
Text text_p1{{50, 112, 190, 16}, "---"};
Text text_lbl_p2{{0, 128, 48, 16}, "P2:"};
Text text_p2{{50, 128, 190, 16}, "---"};
Text text_lbl_p3{{0, 144, 48, 16}, "P3:"};
Text text_p3{{50, 144, 190, 16}, "---"};
Text text_lbl_calc{{0, 168, 240, 16}, "--- Calculated VCO ---"};
Text text_lbl_vco{{0, 200, 80, 16}, "VCO Freq:"};
Text text_vco{{82, 200, 158, 16}, "---"};
Text text_status{{0, 224, 240, 32}, ""};
Button button_refresh{{8, 280, 100, 24}, "Refresh"};
Button button_done{{132, 280, 100, 24}, "Done"};
};
#endif
#ifdef PRALINE
/* Si5351MultiSynthDebugView - Debug fractional register values for MS0 */
class Si5351MultiSynthDebugView : public View {
public:
Si5351MultiSynthDebugView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Si5351 MS0 Debug"; };
private:
NavigationView& nav_;
void refresh();
void force_pll_reset();
void force_fractional_mode();
Text text_title{{0, 0, 240, 16}, "===MS0 Fractional Debug==="};
// Clock Control Register 16 (CLK0)
Text text_lbl_clk_ctrl{{0, 18, 100, 16}, "CLK0 Ctrl:"};
Text text_clk_ctrl{{102, 18, 138, 16}, "---"};
Text text_lbl_ms_int{{0, 34, 100, 16}, "MS_INT bit:"};
Text text_ms_int{{102, 34, 138, 16}, "---"};
// Raw register values
Text text_lbl_raw{{0, 54, 240, 16}, "---Raw Registers (42-49)---"};
Text text_lbl_r42_43{{0, 70, 80, 16}, "R42-43:"};
Text text_r42_43{{82, 70, 158, 16}, "---"};
Text text_lbl_r44_46{{0, 86, 80, 16}, "R44-46:"};
Text text_r44_46{{82, 86, 158, 16}, "---"};
Text text_lbl_r47_49{{0, 102, 80, 16}, "R47-49:"};
Text text_r47_49{{82, 102, 158, 16}, "---"};
// Decoded values
Text text_lbl_decoded{{0, 122, 240, 16}, "---Decoded Values---"};
Text text_lbl_p1{{0, 138, 48, 16}, "P1:"};
Text text_p1{{50, 138, 190, 16}, "---"};
Text text_lbl_p2{{0, 154, 48, 16}, "P2:"};
Text text_p2{{50, 154, 190, 16}, "---"};
Text text_lbl_p3{{0, 170, 48, 16}, "P3:"};
Text text_p3{{50, 170, 190, 16}, "---"};
Text text_lbl_rdiv{{0, 186, 48, 16}, "R_DIV:"};
Text text_rdiv{{50, 186, 190, 16}, "---"};
// Calculated frequency
Text text_lbl_calc{{0, 206, 240, 16}, "---Calculated Output---"};
Text text_lbl_div{{0, 222, 80, 16}, "MS Div:"};
Text text_div{{82, 222, 158, 16}, "---"};
Text text_lbl_freq{{0, 238, 80, 16}, "CLK0 Out:"};
Text text_freq{{82, 238, 158, 16}, "---"};
// Status
Text text_status{{0, 258, 240, 16}, ""};
Button button_refresh{{2, 280, 56, 24}, "Refresh"};
Button button_reset{{62, 280, 56, 24}, "PLL Rst"};
Button button_frac{{122, 280, 56, 24}, "Frac"};
Button button_done{{182, 280, 56, 24}, "Done"};
};
#endif
#ifdef PRALINE
class PralineClockDebugView : public View {
public:
PralineClockDebugView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Pro Clock Status"; };
private:
void refresh();
Text text_title{{0, 0, 240, 16}, "=== Pro Clock Dashboard ==="};
// System Status
Text text_lbl_pll{{0, 20, 80, 16}, "PLL Lock:"};
Text text_pll_status{{88, 20, 152, 16}, "---"};
Text text_lbl_afe{{0, 36, 80, 16}, "AFE Rate:"};
Text text_afe_rate{{88, 36, 152, 16}, "---"};
Text text_lbl_n{{0, 52, 80, 16}, "Decim (n):"};
Text text_n_val{{88, 52, 152, 16}, "-"};
// Table Header (Width 240px, 30 characters)
Text text_header{{0, 72, 240, 16}, "ID mA Mode Src Phase Stat"};
// Helper structure to group row widgets for CLK0-CLK5
struct ClockRow {
Text* id;
Text* ma;
Text* mode;
Text* src; // PLL A, or B
Text* phase;
Text* stat;
};
std::vector<ClockRow> rows;
// We define the actual widgets for 6 clocks
// Note: Layout uses 16px vertical spacing per row
// Full list of clock row entries (C0 through C5)
// Layout: Y starts at 88, increments by 16 per row.
// C0: MAX5864 (AFE/Sampling)
Text t0_id{{0, 88, 24, 16}, "C0:"}; // Column 0
Text t0_ma{{32, 88, 24, 16}, "-"}; // Column 4 (mA)
Text t0_mode{{64, 88, 48, 16}, "-"}; // Column 8 (Mode)
Text t0_src{{112, 88, 32, 16}, "-"}; // Column 14 (Src)
Text t0_ph{{160, 88, 48, 16}, "-"}; // Column 20 (Phase)
Text t0_st{{208, 88, 32, 16}, "-"}; // Column 26 (Stat)
// C1: iCE40 FPGA Timing
Text t1_id{{0, 104, 24, 16}, "C1:"};
Text t1_ma{{32, 104, 24, 16}, "-"};
Text t1_mode{{64, 104, 48, 16}, "-"};
Text t1_src{{112, 104, 32, 16}, "-"};
Text t1_ph{{160, 104, 48, 16}, "-"};
Text t1_st{{208, 104, 32, 16}, "-"};
// C2: LPC43xx MCU Input
Text t2_id{{0, 120, 24, 16}, "C2:"};
Text t2_ma{{32, 120, 24, 16}, "-"};
Text t2_mode{{64, 120, 48, 16}, "-"};
Text t2_src{{112, 120, 32, 16}, "-"};
Text t2_ph{{160, 120, 48, 16}, "-"};
Text t2_st{{208, 120, 32, 16}, "-"};
// C3: SG_CLK PORT 1 (Switching Regulator/Logic Sync)
Text t3_id{{0, 136, 24, 16}, "C3:"};
Text t3_ma{{32, 136, 24, 16}, "-"};
Text t3_mode{{64, 136, 48, 16}, "-"};
Text t3_src{{112, 136, 32, 16}, "-"};
Text t3_ph{{160, 136, 48, 16}, "-"};
Text t3_st{{208, 136, 32, 16}, "-"};
// C4: P_CLK (Peripheral/Expansion Clock)
Text t4_id{{0, 152, 24, 16}, "C4:"};
Text t4_ma{{32, 152, 24, 16}, "-"};
Text t4_mode{{64, 152, 48, 16}, "-"};
Text t4_src{{112, 152, 32, 16}, "-"};
Text t4_ph{{160, 152, 48, 16}, "-"};
Text t4_st{{208, 152, 32, 16}, "-"};
// C5: AUX_CLK (Auxiliary Reference)
Text t5_id{{0, 168, 24, 16}, "C5:"};
Text t5_ma{{32, 168, 24, 16}, "-"};
Text t5_mode{{64, 168, 48, 16}, "-"};
Text t5_src{{112, 168, 32, 16}, "-"};
Text t5_ph{{160, 168, 48, 16}, "-"};
Text t5_st{{208, 168, 32, 16}, "-"};
// C6: SG_CLK PORT 2 (Switching Regulator/Logic Sync)
Text t6_id{{0, 184, 24, 16}, "C6:"};
Text t6_ma{{32, 184, 24, 16}, "-"};
Text t6_mode{{64, 184, 48, 16}, "-"};
Text t6_src{{112, 184, 32, 16}, "-"};
Text t6_ph{{160, 184, 48, 16}, "-"};
Text t6_st{{208, 184, 32, 16}, "-"};
// C7: UNUSED_CLK (Internal Expansion)
Text t7_id{{0, 200, 24, 16}, "C7:"};
Text t7_ma{{32, 200, 24, 16}, "-"};
Text t7_mode{{64, 200, 48, 16}, "-"};
Text t7_src{{112, 200, 32, 16}, "-"};
Text t7_ph{{160, 200, 48, 16}, "-"};
Text t7_st{{208, 200, 32, 16}, "-"};
Button button_refresh{{8, 260, 100, 24}, "Refresh"};
Button button_done{{132, 260, 100, 24}, "Done"};
};
#endif
#endif
class DebugPeripheralsMenuView : public BtnGridView {
+4
View File
@@ -43,6 +43,7 @@ namespace ui {
static const fs::path txt_ext{u".TXT"};
static const fs::path ppl_ext{u".PPL"};
static const fs::path c8_ext{u".C8"};
static const fs::path cu8_ext{u".CU8"};
static const fs::path c16_ext{u".C16"};
static const fs::path cxx_ext{u".C*"};
static const fs::path png_ext{u".PNG"};
@@ -88,8 +89,11 @@ fs::path get_partner_file(fs::path path) {
path.replace_extension(txt_ext);
else if (path_iequal(ext, txt_ext)) {
path.replace_extension(c8_ext);
if (!fs::file_exists(path))
path.replace_extension(cu8_ext);
if (!fs::file_exists(path))
path.replace_extension(c16_ext);
} else
return {};
+1
View File
@@ -80,6 +80,7 @@ class FileManBaseView : public View {
{u".PNG", &bitmap_icon_file_image, ui::Color::green()},
{u".BMP", &bitmap_icon_file_image, ui::Color::green()},
{u".C8", &bitmap_icon_file_iq, ui::Color::dark_cyan()},
{u".CU8", &bitmap_icon_file_iq, ui::Color::dark_cyan()},
{u".C16", &bitmap_icon_file_iq, ui::Color::dark_cyan()},
{u".WAV", &bitmap_icon_file_wav, ui::Color::dark_magenta()},
{u".PPL", &bitmap_icon_file_iq, ui::Color::white()}, // Playlist/Replay
@@ -32,8 +32,6 @@
#include "untar.hpp"
#include <cstdint>
#include "../../flashsize.h"
#define FLASH_ROM_SIZE (FLASH_SIZE_MB * 1024 * 1024)
#define FLASH_STARTING_ADDRESS 0x00000000
#define FLASH_EXPECTED_CHECKSUM 0x00000000
+1
View File
@@ -172,6 +172,7 @@ void IQTrimView::update_range_controls(iq::TrimRange trim_range) {
void IQTrimView::profile_capture() {
power_buckets_.clear();
power_buckets_.resize(screen_width);
iq::PowerBuckets buckets{
.p = power_buckets_.data(),
.size = power_buckets_.size()};
@@ -31,6 +31,7 @@
using namespace portapack;
namespace ui {
void GlassView::focus() {
range_presets.focus();
}
@@ -44,7 +45,7 @@ GlassView::~GlassView() {
// Function to map the value from one range to another
int32_t GlassView::map(int32_t value, int32_t fromLow, int32_t fromHigh, int32_t toLow, int32_t toHigh) {
return toLow + (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow);
return toLow + ((value - fromLow) * (toHigh - toLow) + (fromHigh - fromLow) / 2) / (fromHigh - fromLow);
}
void GlassView::update_display_beep() {
@@ -128,8 +129,9 @@ void GlassView::reset_live_view() {
max_freq_power = -1000;
// Clear screen in peak mode.
const int spectrum_height = screen_height - spectrum_y;
if (live_frequency_view == 2)
display.fill_rectangle({{0, 108 + 16}, {screen_width, screen_height - (108 + 16)}}, {0, 0, 0});
display.fill_rectangle({{0, spectrum_y}, {screen_width, spectrum_height}}, {0, 0, 0});
}
void GlassView::add_spectrum_pixel(uint8_t power) {
@@ -144,11 +146,9 @@ void GlassView::add_spectrum_pixel(uint8_t power) {
constexpr float rssi_voltage_min = 0.4;
constexpr float rssi_voltage_max = 2.2;
constexpr float adc_voltage_max = 3.3;
constexpr int raw_min = rssi_sample_range * rssi_voltage_min / adc_voltage_max;
constexpr int raw_max = rssi_sample_range * rssi_voltage_max / adc_voltage_max;
constexpr int raw_delta = raw_max - raw_min;
const range_t<int> y_max_range{0, screen_height - (108 + 16)};
constexpr int raw_min = 0.5f + rssi_sample_range * rssi_voltage_min / adc_voltage_max;
constexpr int raw_max = 0.5f + rssi_sample_range * rssi_voltage_max / adc_voltage_max;
const int spectrum_height = screen_height - spectrum_y;
// drawing and keeping track of max freq
for (uint16_t xpos = 0; xpos < screen_width; xpos++) {
// save max powerwull freq
@@ -156,14 +156,16 @@ void GlassView::add_spectrum_pixel(uint8_t power) {
max_freq_power = spectrum_data[xpos];
max_freq_hold = get_freq_from_bin_pos(xpos);
}
int16_t point = y_max_range.clip(((spectrum_data[xpos] - raw_min) * (screen_height - (108 + 16))) / raw_delta);
uint8_t color_gradient = (point * 255) / 212;
int16_t point = map(spectrum_data[xpos], 0, 255, 0, spectrum_height);
// clear if not in peak view
if (live_frequency_view != 2) {
display.fill_rectangle({{xpos, 108 + 16}, {1, screen_height - point}}, {0, 0, 0});
display.fill_rectangle({{xpos, spectrum_y}, {1, screen_height - point}}, {0, 0, 0});
}
display.fill_rectangle({{xpos, screen_height - point}, {1, point}}, {color_gradient, 0, uint8_t(255 - color_gradient)});
display.fill_rectangle({{xpos, screen_height - point}, {1, point}}, gradient.lut[spectrum_data[xpos]]);
}
// indicate RSSI min and max power
display.fill_rectangle({{0, screen_height - map(raw_min, 0, 255, 0, spectrum_height)}, {screen_width, 1}}, -gradient.lut[raw_min]);
display.fill_rectangle({{0, screen_height - map(raw_max, 0, 255, 0, spectrum_height)}, {screen_width, 1}}, -gradient.lut[raw_max]);
if (last_max_freq != max_freq_hold) {
last_max_freq = max_freq_hold;
freq_stats.set("MAX HOLD: " + to_string_short_freq(max_freq_hold));
@@ -104,6 +104,7 @@ class GlassView : public View {
};
void on_freqchg(int64_t freq);
// Function to map the value from one range to another
int32_t map(int32_t value, int32_t fromLow, int32_t fromHigh, int32_t toLow, int32_t toHigh);
std::vector<preset_entry> presets_db{};
void manage_beep_audio();
@@ -164,6 +165,9 @@ class GlassView : public View {
uint8_t offset = 0;
uint8_t ignore_dc = 0;
// start of spectrum area
static constexpr int spectrum_y = (108 + 16);
Labels labels{
{{0, UI_POS_Y(0)}, "MIN: MAX: LNA VGA ", Theme::getInstance()->fg_light->foreground},
{{0, 1 * 16}, "RANGE: FILTER: AMP:", Theme::getInstance()->fg_light->foreground},
+2 -1
View File
@@ -304,7 +304,8 @@ class MicTXView : public View {
{
{" 8k5 ", 0}, // Initial dynamic values when we start Mic App.
{" 11k ", 1},
{" 16k ", 2},
{" 12k5 ", 2},
{" 16k ", 3},
}};
NumberField field_squelch{
+1
View File
@@ -1261,6 +1261,7 @@ size_t ReconView::change_mode(freqman_index_t new_mod) {
else
v = SPEC_MODULATION;
field_mode.set_selected_index(v);
return; // Important ! Guru will occur if you don't return when modifying field from within on_change !
}
last_mode = v;
change_mode(v);
+109 -3
View File
@@ -35,6 +35,7 @@
#include "ui_external_items_menu_loader.hpp"
#include "ui_ss_viewer.hpp"
#include "ui_fileman.hpp"
#include "ui_sd_card_debug.hpp"
#include "portapack_persistent_memory.hpp"
#include "lpc43xx_cpp.hpp"
@@ -446,7 +447,11 @@ void SetUIView::focus() {
/* SetSDCardView *********************************************/
SetSDCardView::SetSDCardView(NavigationView& nav) {
add_children({&labels,
add_children({&status_labels,
&text_card_status,
&text_filesystem_type,
&button_more_info,
&labels,
&checkbox_sdcard_speed,
&button_test_sdcard_high_speed,
&text_sdcard_test_status,
@@ -455,6 +460,10 @@ SetSDCardView::SetSDCardView(NavigationView& nav) {
checkbox_sdcard_speed.set_value(pmem::config_sdcard_high_speed_io());
button_more_info.on_select = [&nav, this](Button&) {
nav.push<SDCardDebugView>();
};
button_test_sdcard_high_speed.on_select = [&nav, this](Button&) {
pmem::set_config_sdcard_high_speed_io(true, false);
text_sdcard_test_status.set("!! HIGH SPEED MODE ON !!");
@@ -472,7 +481,79 @@ SetSDCardView::SetSDCardView(NavigationView& nav) {
}
void SetSDCardView::focus() {
button_save.focus();
button_cancel.focus();
}
void SetSDCardView::on_show() {
sd_card_status_signal_token = sd_card::status_signal += [this](const sd_card::Status) {
update_sd_card_status();
};
update_sd_card_status();
}
void SetSDCardView::on_hide() {
sd_card::status_signal -= sd_card_status_signal_token;
}
void SetSDCardView::update_sd_card_status() {
using sd_card::Status;
const auto status = sd_card::status();
// Update card status text
switch (status) {
case Status::NotPresent:
text_card_status.set("Not Inserted");
text_filesystem_type.set("---");
break;
case Status::Present:
text_card_status.set("Inserted");
text_filesystem_type.set("---");
break;
case Status::Mounted:
text_card_status.set("Mounted");
// Determine filesystem type
{
const auto fs_type = sd_card::fs.fs_type;
std::string fs_name;
switch (fs_type) {
case FS_FAT12:
fs_name = "FAT12";
break;
case FS_FAT16:
fs_name = "FAT16";
break;
case FS_FAT32:
fs_name = "FAT32";
break;
case FS_EXFAT:
fs_name = "exFAT";
break;
default:
fs_name = "Unknown";
break;
}
text_filesystem_type.set(fs_name);
}
break;
case Status::ConnectError:
text_card_status.set("Connect Error");
text_filesystem_type.set("---");
break;
case Status::MountError:
text_card_status.set("Mount Error");
text_filesystem_type.set("---");
break;
case Status::IOError:
text_card_status.set("I/O Error");
text_filesystem_type.set("---");
break;
default:
text_card_status.set("Unknown");
text_filesystem_type.set("---");
break;
}
}
/* SetConverterSettingsView ******************************/
@@ -1079,6 +1160,8 @@ SetBatteryView::SetBatteryView(NavigationView& nav) {
add_children({&labels,
&button_save,
&button_cancel,
&field_battcap,
&button_help_cap,
&checkbox_overridebatt,
&checkbox_battery_charge_hint});
@@ -1088,21 +1171,44 @@ SetBatteryView::SetBatteryView(NavigationView& nav) {
pmem::set_ui_override_batt_calc(checkbox_overridebatt.value());
pmem::set_ui_battery_charge_hint(checkbox_battery_charge_hint.value());
battery::BatteryManagement::set_calc_override(checkbox_overridebatt.value());
if (((uint32_t)field_battcap.value() != pmem::battery_cap_mah()) || (!pmem::battery_cap_valid())) {
pmem::set_battery_cap_mah(field_battcap.value());
i2cdev::I2cDev_MAX17055* dev = (i2cdev::I2cDev_MAX17055*)i2cdev::I2CDevManager::get_dev_by_model(I2C_DEVMDL::I2CDEVMDL_MAX17055);
if (dev && !dev->reInit()) {
nav.display_modal("Error", "Battery gauge re-init failed");
return;
}
}
send_system_refresh();
nav.pop();
};
button_reset.on_select = [&nav, this](Button&) {
auto dev = (i2cdev::I2cDev_MAX17055*)i2cdev::I2CDevManager::get_dev_by_model(I2C_DEVMDL::I2CDEVMDL_MAX17055);
if (dev->reset_learned())
if (dev && dev->reset_learned())
nav.display_modal("Reset", "Battery parameters reset");
else
nav.display_modal("Error", "Error parameter reset");
};
button_help_cap.on_select = [&nav, this](Button&) {
nav.display_modal("Battery Capacity",
"Only change default, if you\n"
" changed the battery!\n"
"Defaults:\n"
"H4 + Hackrf One: 2500\n"
"H4 + Hackrf Pro: 2000\n"
"H4Pro + Hackrf Pro: custom\n"
"PortaRf: 3000\n"
);
};
checkbox_overridebatt.set_value(pmem::ui_override_batt_calc());
checkbox_battery_charge_hint.set_value(pmem::ui_battery_charge_hint());
field_battcap.set_value(pmem::battery_cap_mah());
button_cancel.on_select = [&nav, this](Button&) {
nav.pop();
};
+54 -14
View File
@@ -34,6 +34,7 @@
#include "ui_navigation.hpp"
#include "bitmap.hpp"
#include "ff.h"
#include "sd_card.hpp"
#include "portapack_persistent_memory.hpp"
#include "irq_controls.hpp"
@@ -424,36 +425,60 @@ class SetSDCardView : public View {
public:
SetSDCardView(NavigationView& nav);
void on_show() override;
void on_hide() override;
void focus() override;
std::string title() const override { return "SD Card"; };
private:
SignalToken sd_card_status_signal_token{};
// Status section (top half)
Labels status_labels{
{{10, 24}, "Card Status:", Theme::getInstance()->fg_light->foreground},
{{10, 48}, "Filesystem:", Theme::getInstance()->fg_light->foreground}};
Text text_card_status{
{120, 24, 110, 16},
""};
Text text_filesystem_type{
{120, 48, 110, 16},
""};
Button button_more_info{
{UI_POS_X_CENTER(20), 90, UI_POS_WIDTH(20), UI_POS_HEIGHT(2)},
"More Info"};
// Settings section (bottom half)
Labels labels{
// 01234567890123456789012345678
{{UI_POS_X_CENTER(26), 120 - 48}, " HIGH SPEED SDCARD IO ", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X_CENTER(26), 120 - 32}, " May or may not work !! ", Theme::getInstance()->fg_light->foreground}};
{{UI_POS_X_CENTER(26), 140}, " HIGH SPEED SDCARD IO ", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X_CENTER(26), 156}, " May or may not work !! ", Theme::getInstance()->fg_light->foreground}};
Checkbox checkbox_sdcard_speed{
{UI_POS_X_CENTER(26), 120},
{UI_POS_X_CENTER(26), 180},
20,
"enable high speed IO"};
Button button_test_sdcard_high_speed{
{UI_POS_X_CENTER(27), 152, UI_POS_WIDTH(27), UI_POS_HEIGHT(2)},
{UI_POS_X_CENTER(27), 210, UI_POS_WIDTH(27), UI_POS_HEIGHT(2)},
"TEST BUTTON (NO PMEM SAVE)"};
Text text_sdcard_test_status{
{UI_POS_X_CENTER(28), 198, UI_POS_WIDTH(28), UI_POS_HEIGHT(1)},
{UI_POS_X_CENTER(28), 256, UI_POS_WIDTH(28), UI_POS_HEIGHT(1)},
""};
Button button_save{
{UI_POS_X_CENTER(12) - UI_POS_WIDTH(8), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(12), UI_POS_HEIGHT(2)},
{UI_POS_X_CENTER(12) - UI_POS_WIDTH(8), UI_POS_Y_BOTTOM(4), 12 * 8, 32},
"Save"};
Button button_cancel{
{UI_POS_X_CENTER(16) + UI_POS_WIDTH(8), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(12), UI_POS_HEIGHT(2)},
{UI_POS_X_CENTER(12) + UI_POS_WIDTH(8), UI_POS_Y_BOTTOM(4), 12 * 8, 32},
"Cancel"};
void update_sd_card_status();
};
class SetConverterSettingsView : public View {
@@ -1020,21 +1045,36 @@ class SetBatteryView : public View {
private:
int32_t selected = 0;
Labels labels{
{{1 * 8, 1 * 16}, "Override batt calculation", Theme::getInstance()->fg_light->foreground},
{{1 * 8, 2 * 16}, "method to voltage based", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X_CENTER(26), UI_POS_Y(0)}, "Override batt calculation", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X_CENTER(24), UI_POS_Y(1)}, "method to voltage based", Theme::getInstance()->fg_light->foreground},
/**/
{{1 * 8, 6 * 16}, "Display a hint to remind you", Theme::getInstance()->fg_light->foreground},
{{1 * 8, 7 * 16}, "when you charge", Theme::getInstance()->fg_light->foreground}};
{{UI_POS_X_CENTER(29), UI_POS_Y(4)}, "Display a hint to remind you", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X_CENTER(16), UI_POS_Y(5)}, "when you charge", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X_CENTER(17), UI_POS_Y(8)}, "Battery capacity", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(7), UI_POS_Y(9)}, "mAh", Theme::getInstance()->fg_light->foreground}};
Labels labels2{{{1 * 8, 11 * 16}, "Reset IC's learned params.", Theme::getInstance()->fg_light->foreground}};
Labels labels2{{{UI_POS_X(1), UI_POS_Y(11)}, "Reset IC's learned params.", Theme::getInstance()->fg_light->foreground}};
NumberField field_battcap{
{UI_POS_X(1), UI_POS_Y(9)},
5,
{BATT_18650_MIN_MAH, BATT_18650_MAX_MAH},
100,
' ',
};
Button button_help_cap{
{UI_POS_X(12), UI_POS_Y(9), UI_POS_WIDTH(5), UI_POS_HEIGHT(1)},
"Help",
};
Checkbox checkbox_overridebatt{
{2 * 8, 4 * 16},
{UI_POS_X(2), UI_POS_Y(2)},
23,
"Override"};
Checkbox checkbox_battery_charge_hint{
{2 * 8, 9 * 16},
{UI_POS_X(2), UI_POS_Y(6)},
23,
"Charge hint"};
@@ -34,7 +34,7 @@
namespace ui {
void create_thread(int32_t (*fn)(void*), void* arg, size_t stack_size, int priority) {
// TODO: collect memory on terminate, once this is used
// TODO: collect memory on terminate, once this is used. This is a HUGE TODO! need to call chThdWait on all of them!
chThdCreateFromHeap(NULL, stack_size, priority, fn, arg);
}
+9 -2
View File
@@ -225,8 +225,15 @@ volume_range_t volume_range() {
return audio_codec->headphone_gain_range();
}
void set_volume(const volume_t volume) {
audio_codec->set_headphone_volume(volume);
bool set_volume(const volume_t volume) {
// add retry method
for (int i = 0; i < 100; ++i) {
if (audio_codec->set_headphone_volume(volume)) {
return true;
}
chThdSleepMilliseconds(2);
}
return false;
}
} /* namespace headphone */
+2 -2
View File
@@ -49,7 +49,7 @@ class Codec {
virtual void headphone_enable() = 0;
virtual void headphone_disable() = 0;
virtual volume_range_t headphone_gain_range() const = 0;
virtual void set_headphone_volume(const volume_t volume) = 0;
virtual bool set_headphone_volume(const volume_t volume) = 0;
virtual void microphone_enable(int8_t alc_mode, bool mic_to_HP_enabled) = 0; // added user-GUI AK4951 ,selected ALC mode.
virtual void microphone_disable() = 0;
@@ -93,7 +93,7 @@ namespace headphone {
volume_range_t volume_range();
void set_volume(const volume_t volume);
bool set_volume(const volume_t volume);
} /* namespace headphone */
+38 -1
View File
@@ -21,6 +21,7 @@
*/
#include "baseband_api.hpp"
#include <cstring>
#include "audio.hpp"
#include "tonesets.hpp"
@@ -334,12 +335,22 @@ void set_rds_data(const uint16_t message_length) {
send_message(&message);
}
void set_spectrum(const size_t sampling_rate, const size_t trigger) {
void set_spectrum(
const size_t sampling_rate,
const size_t trigger) {
const WidebandSpectrumConfigMessage message{
sampling_rate, trigger};
send_message(&message);
}
void set_time_sink(
const size_t sampling_rate,
const size_t trigger) {
const TimeSinkConfigMessage message{
sampling_rate, trigger};
send_message(&message);
}
void set_wefax_config(uint8_t lpm = 120, uint8_t ioc = 0) {
const WeFaxRxConfigureMessage message{lpm, ioc};
send_message(&message);
@@ -382,6 +393,11 @@ void set_moreserx_config(uint8_t mode) {
send_message(&message);
}
void set_tonedetect_config(uint8_t squelch, uint32_t ctcss_freq_x10) {
const ToneDetectConfigureMessage message{squelch, ctcss_freq_x10};
send_message(&message);
}
void set_morsetx_config(uint8_t mode, uint32_t tone, float fm_delta) {
const MorseTXConfigureMessage message{mode, tone, fm_delta};
send_message(&message);
@@ -412,8 +428,29 @@ void set_rtty_config(RTTYDataMessage& message) {
send_message(&message);
}
void set_epirb_tx_config(EPIRBTXDataMessage& message) {
send_message(&message);
}
void set_epirb_rx_config(EPIRBRXConfig& message) {
send_message(&message);
}
void set_p25tx_data(const uint8_t* dibits, uint16_t frame_length) {
const size_t max_len = sizeof(shared_memory.bb_data.data);
if (frame_length > max_len) frame_length = max_len;
memcpy(shared_memory.bb_data.data, dibits, frame_length);
P25TxConfigureMessage msg{};
msg.frame_length = frame_length;
send_message(&msg);
}
static bool baseband_image_running = false;
bool is_image_running() {
return baseband_image_running;
}
void run_image(const spi_flash::image_tag_t image_tag) {
if (baseband_image_running) {
chDbgPanic("BBRunning");
+11 -1
View File
@@ -97,12 +97,18 @@ void set_pocsag(int8_t baud_config = -1);
void set_adsb();
void set_jammer(const bool run, const jammer::JammerType type, const uint32_t speed);
void set_rds_data(const uint16_t message_length);
void set_spectrum(const size_t sampling_rate, const size_t trigger);
void set_spectrum(
const size_t sampling_rate,
const size_t trigger);
void set_time_sink(
const size_t sampling_rate,
const size_t trigger);
void set_siggen_tone(const uint32_t tone);
void set_siggen_config(const uint32_t bw, const uint32_t shape, const uint32_t duration);
void set_spectrum_painter_config(const uint16_t width, const uint16_t height, bool update, int32_t bw);
void set_subghzd_config(uint8_t modulation, uint32_t sampling_rate);
void set_moreserx_config(uint8_t mode);
void set_tonedetect_config(uint8_t squelch, uint32_t ctcss_freq_x10 = 0);
void set_morsetx_config(uint8_t mode, uint32_t tone, float fm_delta);
void set_morsetx_key(bool key_down);
void set_wefax_config(uint8_t lpm, uint8_t ioc);
@@ -111,12 +117,16 @@ void set_flex_config();
void set_bitstream_config(uint32_t deviation, uint8_t mode); // mode 0 for am, 1 for 2fsk
void set_rtty_config(uint16_t baud, uint16_t shift, uint8_t* payload = nullptr, uint16_t payload_length = 0); // baud*100
void set_rtty_config(RTTYDataMessage& message);
void set_epirb_tx_config(EPIRBTXDataMessage& message);
void set_epirb_rx_config(EPIRBRXConfig& message);
void set_p25tx_data(const uint8_t* dibits, uint16_t frame_length);
void request_roger_beep();
void request_rssi_beep();
void request_beep_stop();
void request_audio_beep(uint32_t freq, uint32_t sample_rate, uint32_t duration_ms);
bool is_image_running();
void run_image(const portapack::spi_flash::image_tag_t image_tag);
void run_prepared_image(const uint32_t m4_code);
void shutdown();
+494 -147
View File
@@ -35,12 +35,16 @@ using namespace lpc43xx;
extern "C" {
#include "fpga_bridge.h"
}
// Need access to ssp1_arbiter from radio namespace
// Need access to ssp1_arbiter from radio namespace for FPGA related radio method dependencies.
#include "radio.hpp"
#endif
constexpr uint32_t si5351_vco_f = 800000000;
#ifdef PRALINE
constexpr uint32_t si5351_vco_afe_f = 800000000; // If necessary may be changed to 768 MHz for optimal for 3.072 MHz sample frequencies commonly used by apps
#endif
constexpr si5351::Inputs si5351_inputs{
.f_xtal = si5351_xtal_f,
.f_clkin = si5351_clkin_f,
@@ -62,8 +66,44 @@ constexpr si5351::PLL si5351_pll_xtal_25m{
.b = 0,
.c = 1,
};
constexpr auto si5351_pll_a_xtal_reg = si5351_pll_xtal_25m.reg(0);
#ifdef PRALINE
// Define pll_a from 25MHz clock for stable PLL A, and AFE locked reference
// PLL A: 800 MHz VCO (32x Multiplier for jitter-free 3.072 MHz sampling)
constexpr si5351::PLL si5351_pll_a_afe_800m{
.f_in = si5351_inputs.f_xtal, // 25,000,000 Hz
.a = 32, // Multiplier: 25 * 32 = 800
.b = 0,
.c = 1,
};
// PLL A: registers (Base 34) 800 MHz VCO (For jitter-free AFE sampling frequencies)
constexpr auto si5351_pll_a_800_reg = si5351_pll_a_afe_800m.reg(0); // Base 26
static_assert(si5351_pll_a_afe_800m.f_vco() == si5351_vco_f, "PLL A XTAL frequency wrong");
static_assert(si5351_pll_a_afe_800m.p1() == 3584, "PLL A XTAL P1 wrong");
static_assert(si5351_pll_a_afe_800m.p2() == 0, "PLL A XTAL P2 wrong");
static_assert(si5351_pll_a_afe_800m.p3() == 1, "PLL A XTAL P3 wrong");
// Define pll_b 25MHz clock for stable PLL B
// PLL B: 800 MHz VCO (32x Multiplier for (For stable Digital/SGPIO bus)
constexpr si5351::PLL si5351_pll_b_800m{
.f_in = si5351_inputs.f_xtal, // 25,000,000 Hz
.a = 32, // Multiplier: 25 * 32 = 800
.b = 0,
.c = 1,
};
// PLL B: registers (Base 34) 800 MHz VCO (For stable Digital/SGPIO bus)
constexpr auto si5351_pll_b_800_reg = si5351_pll_b_800m.reg(1); // Base 34
static_assert(si5351_pll_b_800m.f_vco() == si5351_vco_f, "PLL B XTAL frequency wrong");
static_assert(si5351_pll_b_800m.p1() == 3584, "PLL B XTAL P1 wrong");
static_assert(si5351_pll_b_800m.p2() == 0, "PLL B XTAL P2 wrong");
static_assert(si5351_pll_b_800m.p3() == 1, "PLL B XTAL P3 wrong");
#else
// PLL A registers (Base 26)
constexpr auto si5351_pll_a_xtal_reg = si5351_pll_xtal_25m.reg(0);
static_assert(si5351_pll_xtal_25m.f_vco() == si5351_vco_f, "PLL XTAL frequency wrong");
static_assert(si5351_pll_xtal_25m.p1() == 3584, "PLL XTAL P1 wrong");
static_assert(si5351_pll_xtal_25m.p2() == 0, "PLL XTAL P2 wrong");
@@ -79,13 +119,6 @@ constexpr si5351::PLL si5351_pll_clkin_10m{
constexpr auto si5351c_pll_b_clkin_reg = si5351_pll_clkin_10m.reg(1);
constexpr auto si5351a_pll_a_clkin_reg = si5351_pll_clkin_10m.reg(0);
#ifndef PRALINE
static_assert(si5351_pll_xtal_25m.f_vco() == si5351_vco_f, "PLL XTAL frequency wrong");
static_assert(si5351_pll_xtal_25m.p1() == 3584, "PLL XTAL P1 wrong");
static_assert(si5351_pll_xtal_25m.p2() == 0, "PLL XTAL P2 wrong");
static_assert(si5351_pll_xtal_25m.p3() == 1, "PLL XTAL P3 wrong");
#endif
static_assert(si5351_pll_clkin_10m.f_vco() == si5351_vco_f, "PLL CLKIN frequency wrong");
static_assert(si5351_pll_clkin_10m.p1() == 9728, "PLL CLKIN P1 wrong");
static_assert(si5351_pll_clkin_10m.p2() == 0, "PLL CLKIN P2 wrong");
@@ -99,16 +132,16 @@ constexpr si5351::MultisynthFractional si5351_ms_18m432 {
.r_div = 1,
};
*/
/*
constexpr si5351::MultisynthFractional si5351_ms_0_20m {
.f_src = si5351_vco_f,
.a = 20,
.b = 0,
.c = 1,
.r_div = 1,
// constexpr auto si5351_ms_0_20m_reg = si5351_ms_0_20m.reg(0);
constexpr si5351::MultisynthFractional si5351_ms_0_4m{
.f_src = si5351_vco_f, // 800,000,000 Hz
.a = 100, // Integer divider 100
.b = 0,
.c = 1,
.r_div = 1 // Final R-divider: 2^1 = 2
};
constexpr auto si5351_ms_0_20m_reg = si5351_ms_0_20m.reg(0);
*/
constexpr si5351::MultisynthFractional si5351_ms_0_8m{
.f_src = si5351_vco_f,
.a = 50,
@@ -116,6 +149,73 @@ constexpr si5351::MultisynthFractional si5351_ms_0_8m{
.c = 1,
.r_div = 1,
};
#ifdef PRALINE
// (initial 4 MHz from 800 MHz VCO: 800 / 200 = 4)
constexpr si5351::MultisynthFractional si5351_ms_afe_4m{
.f_src = si5351_vco_afe_f, // 800 MHz
.a = 200,
.b = 0,
.c = 1,
.r_div = 0};
// (10 MHz from 800 MHz VCO: 800 / 80 = 10)
constexpr si5351::MultisynthFractional si5351_ms_afe_10m{
.f_src = si5351_vco_afe_f, // 800 MHz
.a = 80,
.b = 0,
.c = 1,
.r_div = 0};
// (20 MHz from 800 MHz VCO: 800 / 40 = 20)
constexpr si5351::MultisynthFractional si5351_ms_afe_20m{
.f_src = si5351_vco_afe_f,
.a = 40,
.b = 0,
.c = 1,
.r_div = 0,
};
// (25 MHz from 800 MHz VCO: 800 / 32 = 25)
// Define xtal MultiSynth 25MHz clock for stable PLL A, and AFE locked XTAL reference
constexpr si5351::MultisynthFractional si5351_ms_afe_25m{
.f_src = si5351_vco_afe_f, // 800,000,000 Hz
.a = 32, // 800 / 32 = 25 MHz
.b = 0,
.c = 1,
.r_div = 0 // No final bit-shifting
};
// (40 MHz from 800 MHz VCO: 800 / 20 = 40)
constexpr si5351::MultisynthFractional si5351_ms_afe_40m{
.f_src = si5351_vco_afe_f, // 800 MHz
.a = 20,
.b = 0,
.c = 1,
.r_div = 0};
// (20 MHz from 800 MHz VCO: 800 / 40 = 20)
constexpr si5351::MultisynthFractional si5351_ms_20m{
.f_src = si5351_vco_f,
.a = 40,
.b = 0,
.c = 1,
.r_div = 0,
};
// constexpr auto si5351_ms_20m_reg = si5351_ms_20m.reg(0);
// (25 MHz from 800 MHz VCO: 800 / 32 = 25)
// Define xtal MultiSynth 25MHz clock for stable PLL B, and XTAL reference
constexpr si5351::MultisynthFractional si5351_ms_25m{
.f_src = si5351_vco_f, // 800,000,000 Hz
.a = 32, // 800 / 32 = 25 MHz
.b = 0,
.c = 1,
.r_div = 0 // No final bit-shifting
};
#endif
constexpr auto si5351c_ms_0_8m_reg = si5351_ms_0_8m.reg(clock_generator_output_og_codec);
#ifdef PRALINE
@@ -219,12 +319,21 @@ static_assert(si5351a_ms_int_mcu_clkin.f_out() == mcu_clkin_r9_f, "MS int MCU CL
using namespace si5351;
#ifdef PRALINE
static constexpr ClockControl::MultiSynthSource get_si5351a_reference_clock_generator_pll(const ClockManager::ReferenceSource reference_source) {
return (reference_source == ClockManager::ReferenceSource::Xtal)
? ClockControl::MultiSynthSource::PLLA
: ClockControl::MultiSynthSource::PLLB;
}
#else
static constexpr ClockControl::MultiSynthSource get_si5351c_reference_clock_generator_pll(const ClockManager::ReferenceSource reference_source) {
return (reference_source == ClockManager::ReferenceSource::Xtal)
? ClockControl::MultiSynthSource::PLLA
: ClockControl::MultiSynthSource::PLLB;
}
#endif
#ifndef PRALINE
constexpr ClockControls si5351c_clock_control_common{{
{ClockControl::ClockCurrentDrive::_8mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, get_si5351c_reference_clock_generator_pll(ClockManager::ReferenceSource::Xtal), ClockControl::MultiSynthMode::Fractional, ClockControl::ClockPowerDown::Power_Off},
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Group, ClockControl::ClockInvert::Invert, get_si5351c_reference_clock_generator_pll(ClockManager::ReferenceSource::Xtal), ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
@@ -235,21 +344,43 @@ constexpr ClockControls si5351c_clock_control_common{{
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, get_si5351c_reference_clock_generator_pll(ClockManager::ReferenceSource::Xtal), ClockControl::MultiSynthMode::Fractional, ClockControl::ClockPowerDown::Power_Off},
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, get_si5351c_reference_clock_generator_pll(ClockManager::ReferenceSource::Xtal), ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
}};
#endif
constexpr ClockControls si5351a_clock_control_common{{
#ifndef PRALINE
{ClockControl::ClockCurrentDrive::_6mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
#ifdef PRALINE
// CLK0: MAX5864 (ADC) - 4mA, Normal PLLA Integer
{ClockControl::ClockCurrentDrive::_4mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_On},
// CLK1: SCT_CLK (iCE40 FPGA) - 4mA, Normal PLLB Integer
{ClockControl::ClockCurrentDrive::_4mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLB, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_On},
// CLK2: LPC43xx MCU - 2mA, Normal PLLA (Must be Integer for MCU stability)
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_On},
// CLK3: CLKOUT SMA Port P1 - 2mA, Normal PLLB Integer Power_Off
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLB, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
// CLK4: MAX2831 reference (40 MHz) - 4mA, Invert PLLA Integer (Required for mixer lock)
{ClockControl::ClockCurrentDrive::_4mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Invert, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_On},
// CLK5: RFFC5072 reference (40 MHz) - 4mA, Invert PLLA Integer (Required for mixer lock)
{ClockControl::ClockCurrentDrive::_4mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Invert, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_On},
// CLK6: Not used (disabled) 2mA, Normal PLLB Integer, Power_Off
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLB, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
// CLK7: Not used (disabled) 2mA, Normal PLLB Integer, Power_Off
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLB, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
#else
{ClockControl::ClockCurrentDrive::_6mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Fractional, ClockControl::ClockPowerDown::Power_Off}, // CLK0: MUST be Fractional for 8 MHz!
#endif
{ClockControl::ClockCurrentDrive::_6mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
{ClockControl::ClockCurrentDrive::_4mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Fractional, ClockControl::ClockPowerDown::Power_Off},
{ClockControl::ClockCurrentDrive::_8mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
// CLK4: HackRF r9 - not inverted
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
// CLK5: HackRF r9 - not used
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
// CLK6: Not used
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
// CLK7: Not used
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
#endif
}};
ClockManager::Reference ClockManager::get_reference() const {
return reference;
}
@@ -293,17 +424,34 @@ using namespace hackrf::one;
void ClockManager::init_clock_generator() {
#ifdef PRALINE
// PRALINE: Configure clock input mux GPIO
// GPIO0_15 (clkin_ctrl) selects GP_CLKIN source:
// 0 = P1 connector (external)
// 1 = P22 (internal Si5351 CLK2)
constexpr GPIO gpio_clkin_ctrl = gpio[GPIO0_15];
gpio_clkin_ctrl.output();
gpio_clkin_ctrl.write(1); // CLKIN_SIGNAL_P22 = 1 = internal Si5351 CLK2
// thoese PIN can review platform_scu file
// have many conflict and modify for clock init
// P2_10 -> GPIO0[14] P1_CTRL0
LPC_SCU->SFSP[2][10] = 0xF0;
// P6_8 -> GPIO5[16] P1_CTRL1
LPC_SCU->SFSP[6][8] = 0xF4;
// P6_9 -> GPIO3[5] P1_CTRL2
LPC_SCU->SFSP[6][9] = 0xF0;
// P1_20 -> GPIO0[15] CLKIN_CTRL
LPC_SCU->SFSP[1][20] = 0xF0;
constexpr GPIO gpio_p1_ctrl0 = gpio[GPIO0_14];
constexpr GPIO gpio_p1_ctrl1 = gpio[GPIO5_16];
constexpr GPIO gpio_p1_ctrl2 = gpio[GPIO3_5];
constexpr GPIO gpio_clkin_ctrl = gpio[GPIO0_15];
gpio_p1_ctrl0.output();
gpio_p1_ctrl1.output();
gpio_p1_ctrl2.output();
gpio_clkin_ctrl.output();
// P1 control = 100 and choose P22 clock external clock on portapack
gpio_p1_ctrl0.write(0);
gpio_p1_ctrl1.write(0);
gpio_p1_ctrl2.write(1);
gpio_clkin_ctrl.write(1);
chThdSleepMilliseconds(20);
// Also enable MCU clock gate (GPIO0_8)
gpio_r9_mcu_clk_en.output();
gpio_r9_mcu_clk_en.write(1);
#else
// HackRF One r9: GPIO0_8 (mcu_clk_en) gates Si5351 CLK2/CLK7 to GP_CLKIN
if (hackrf_r9) {
@@ -327,10 +475,23 @@ void ClockManager::init_clock_generator() {
* 4. Reset PLLs
* 5. Enable outputs
*/
clock_generator.set_pll_input_sources(si5351a_pll_input_sources);
/* Skip MCU CLKIN setup and reference detection for PRALINE - not applicable */
reference = Reference{ReferenceSource::Xtal, 0};
// change there detect method same as hackrf one
// PLLA -> XTALPLLB -> CLKIN
clock_generator.set_pll_input_sources(si5351c_pll_input_sources);
// although the name a and the branch define CLK2 MCU CLOCK
// only use CLK2
auto si5351_clock_control_common = si5351a_clock_control_common;
constexpr size_t clock_generator_output_pro_mcu_clkin = 2;
// clk_src define CLKIN
clock_generator.set_clock_control(
clock_generator_output_pro_mcu_clkin,
si5351_clock_control_common[clock_generator_output_pro_mcu_clkin]
.clk_src(ClockControl::ClockSource::CLKIN)
.clk_pdn(ClockControl::ClockPowerDown::Power_On));
clock_generator.enable_output(clock_generator_output_pro_mcu_clkin);
chThdSleepMilliseconds(20);
// should be extern icon and 10MHz
reference = choose_reference();
/* Clock control will be set AFTER multisynth configuration - see below */
#else
@@ -377,58 +538,86 @@ void ClockManager::init_clock_generator() {
#endif
#ifdef PRALINE
/* PRALINE uses Si5351A with:
* CLK0 = AFE_CLK (codec/FPGA sample clock)
* CLK1 = SCT_CLK (FPGA timing clock at 2x sample rate)
* CLK4 = first IF (RFFC5072)
* CLK5 = second IF (MAX2831)
* Uses PLLA on XTAL only (no CLKIN support).
/* * Praline HackRF Pro Clock Assignments (800 MHz VCO Configuration)
* VCO Frequency: 800,000,000 Hz (Master Reference)
* * CLK0: AFE_CLK (MAX5864 Codec & FPGA ADC Interface)
* - Note: Defines hardware sample rate. Essential for WFM purity.
* * CLK1: SCT_CLK (iCE40 FPGA System/Timing Clock)
* - Note: Timing for SGPIO data bus; scales to 2x SR in wideband modes.
* * CLK2: MCU_CLKIN (LPC43xx MCU External Clock Input)
* - Note: Synchronizes MCU processing to the RF clock tree.
* * CLK3: SG_CLK (Switching Regulator/Internal Logic Sync) SMA Port 1
* - Note: Used for internal FPGA logic/gateware synchronization.
* * CLK4: P_CLK (MAX2831 Peripheral/Expansion Clock)
* - Note: Routed to expansion headers for external hardware sync.
* * CLK5: AUX_CLK (RFFC5371 Auxiliary reference for secondary logic)
* - Note: Provides additional timing flexibility for the iCE40 FPGA.
* * CLK6: SG_CLK (Switching Regulator/Internal Logic Sync) SMA Port 2
* - Note: Used for internal FPGA logic/gateware synchronization.
* * CLK7: Unused / Power-Down
* - State: Disabled (si5351a_ms6_7_off_reg)
* - Note: Kept OFF to reduce EMI/RFI near the RF front-end.
* * CLKOUT: Optional external clock output on the header.
*/
/* Step 1: Write PLL A configuration (800 MHz VCO from 25 MHz XTAL) */
/* Use single-byte writes to debug I2C issues */
/* Write PLL A (800 MHz based on 25 MHz xtal for RF) and
* PLL B (800 MHZ based on 25 MHz xtalfor Digital)
* Use single-byte writes to debug I2C issues
*/
{
const auto& pll_regs = si5351_pll_a_xtal_reg;
const uint8_t base_reg = pll_regs[0];
for (size_t i = 1; i < pll_regs.size(); i++) {
clock_generator.write_register(base_reg + i - 1, pll_regs[i]);
// Write PLLA (Registers 26-33)
/* Write PLL A configuration (Base 26) */
const auto& pll_a = si5351_pll_a_800_reg;
for (size_t i = 1; i < pll_a.size(); i++) {
clock_generator.write_register(pll_a[0] + i - 1, pll_a[i]);
}
// Write PLLB (Registers 34-41)
/* Write PLL B configuration (Base 34) */
const auto& pll_b = si5351_pll_b_800_reg;
for (size_t i = 1; i < pll_b.size(); i++) {
clock_generator.write_register(pll_b[0] + i - 1, pll_b[i]);
}
}
/* Step 2: Write multisynth configurations using single-byte writes */
clock_generator.write_ms_single_byte(0, si5351_ms_0_8m); // MS0 = divider 50, r_div=1 for 8 MHz
clock_generator.write_ms_single_byte(1, si5351_ms_16m); // MS1 = divider 50, r_div=0 for 16 MHz
/* Write multisynth configurations using single-byte writes */
// These cover all active channels on the Praline board
clock_generator.write_ms_single_byte(0, si5351_ms_afe_4m); // CLK0: PLL A AFE Codec (4 MHz)
clock_generator.write_ms_single_byte(1, si5351_ms_10m); // CLK1: PLL B SGPIO/FPGA Timing (10 MHz)
clock_generator.write_ms_single_byte(2, si5351_ms_afe_40m); // CLK2: PLL A Audio and MCU Input (40 MHz)
clock_generator.write_ms_single_byte(3, si5351_ms_0_4m); // CLK3: PLL B SMA Port 1 Logic Sync (4 MHz or 10 MHz)
clock_generator.write_ms_single_byte(4, si5351_ms_afe_40m); // CLK4: PLL A MAX2831 Second IF (40 MHz)
clock_generator.write_ms_single_byte(5, si5351_ms_afe_40m); // CLK5: PLL A RFFC5071First IF (40 MHz)
clock_generator.write_ms_single_byte(6, si5351_ms_0_4m); // CLK6: PLL B SMA Port 2 Logic Sync (4 MHz or 10 MHz)
clock_generator.write_ms_single_byte(7, si5351_ms_0_4m); // CLK7: PLL B Unused (4 MHz)
/* CLK4 and CLK5 - use single-byte writes too */
{
const auto& ms4_regs = si5351c_ms_4_reg;
const uint8_t base_reg = ms4_regs[0];
for (size_t i = 1; i < ms4_regs.size(); i++) {
clock_generator.write_register(base_reg + i - 1, ms4_regs[i]);
}
}
{
const auto& ms5_regs = si5351c_ms_5_reg;
const uint8_t base_reg = ms5_regs[0];
for (size_t i = 1; i < ms5_regs.size(); i++) {
clock_generator.write_register(base_reg + i - 1, ms5_regs[i]);
}
}
clock_generator.write(si5351a_ms6_7_off_reg); // MS6/7 off - short write is OK
/* Step 3: NOW set clock control registers (AFTER multisynths per HackRF reference) */
const auto ref_pll = ClockControl::MultiSynthSource::PLLA;
/* NOW set clock control registers (AFTER multisynths per HackRF reference) */
const auto ref_pll_a = ClockControl::MultiSynthSource::PLLA;
const auto ref_pll_b = ClockControl::MultiSynthSource::PLLB;
const ClockControls si5351_clock_control = ClockControls{{
si5351a_clock_control_common[0].ms_src(ref_pll),
si5351a_clock_control_common[1].ms_src(ref_pll),
si5351a_clock_control_common[2].ms_src(ref_pll),
si5351a_clock_control_common[3].ms_src(ref_pll),
si5351a_clock_control_common[4].ms_src(ref_pll),
si5351a_clock_control_common[5].ms_src(ref_pll),
si5351a_clock_control_common[6].ms_src(ref_pll),
si5351a_clock_control_common[7].ms_src(ref_pll),
si5351a_clock_control_common[0].ms_src(ref_pll_a),
si5351a_clock_control_common[1].ms_src(ref_pll_b),
si5351a_clock_control_common[2].ms_src(ref_pll_a),
si5351a_clock_control_common[3].ms_src(ref_pll_b),
si5351a_clock_control_common[4].ms_src(ref_pll_a),
si5351a_clock_control_common[5].ms_src(ref_pll_a),
si5351a_clock_control_common[6].ms_src(ref_pll_b),
si5351a_clock_control_common[7].ms_src(ref_pll_b),
}};
clock_generator.set_clock_control(si5351_clock_control);
// clock_generator.set_clock_control(si5351_clock_control);
// Use single-byte writes instead of multi-byte
clock_generator.set_clock_control_single_byte(si5351_clock_control);
// Don't write CLKS 3, 6, and 7 multisynth
// Ensure CLK3 clock control has Power_Off
// Verify output is disabled
clock_generator.disable_output(3);
clock_generator.disable_clock(3);
clock_generator.disable_output(6);
clock_generator.disable_clock(6);
clock_generator.disable_output(7);
clock_generator.disable_clock(7);
#else
if (hackrf_r9) {
const PLLReg pll_reg = (reference.source == ReferenceSource::Xtal)
@@ -456,8 +645,8 @@ void ClockManager::init_clock_generator() {
// Wait for PLL(s) to lock.
#ifdef PRALINE
// PRALINE: Wait for PLLA to lock (0x20 = LOL_A bit)
uint8_t device_status_mask = 0x20;
// PRALINE: Wait for 0x60 (0x20 | 0x40), PLLA and PLLB to lock (0x20 = LOL_A bit, 0x40 = LOL_B bit)
uint8_t device_status_mask = 0x60;
uint32_t pll_timeout = 100000;
while ((clock_generator.device_status() & device_status_mask) != 0 && pll_timeout > 0) {
pll_timeout--;
@@ -466,8 +655,6 @@ void ClockManager::init_clock_generator() {
static volatile uint32_t pll_lock_timeout = pll_timeout;
(void)pll_lock_timeout;
// CRITICAL: Add delay to ensure Si5351 writes complete before I2C bus stops
chThdSleepMilliseconds(100);
#else
// Wait for PLL(s) to lock - with timeout to prevent hang
uint8_t device_status_mask = hackrf_r9
@@ -475,14 +662,8 @@ void ClockManager::init_clock_generator() {
: (ref_pll == ClockControl::MultiSynthSource::PLLB)
? 0x40
: 0x20;
#ifndef PRALINE
while ((clock_generator.device_status() & device_status_mask) != 0);
#else
uint32_t pll_timeout = 100000;
while ((clock_generator.device_status() & device_status_mask) != 0 && pll_timeout > 0) {
pll_timeout--;
}
#endif
clock_generator.set_clock_control(
clock_generator_output_mcu_clkin,
@@ -499,12 +680,16 @@ uint32_t ClockManager::measure_gp_clkin_frequency() {
}
bool ClockManager::loss_of_signal() {
#ifdef PRALINE
return clock_generator.clkin_loss_of_signal();
#else
if (hackrf_r9) {
const auto frequency = measure_gp_clkin_frequency();
return (frequency < 9850000) || (frequency > 10150000);
} else {
return clock_generator.clkin_loss_of_signal();
}
#endif
}
ClockManager::ReferenceSource ClockManager::detect_reference_source() {
@@ -527,6 +712,17 @@ ClockManager::ReferenceSource ClockManager::detect_reference_source() {
}
ClockManager::Reference ClockManager::choose_reference() {
#ifdef PRALINE
const auto detected_reference = detect_reference_source();
if ((detected_reference == ReferenceSource::External) ||
(detected_reference == ReferenceSource::PortaPack)) {
const auto frequency = measure_gp_clkin_frequency();
if ((frequency >= 9850000) && (frequency <= 10150000)) {
return {detected_reference, 10000000};
}
}
#else
if (hackrf_r9) {
gpio_r9_clkin_en.write(1);
volatile uint32_t delay = 240000 + 24000;
@@ -545,6 +741,7 @@ ClockManager::Reference ClockManager::choose_reference() {
if (hackrf_r9) {
gpio_r9_clkin_en.write(0);
}
#endif
portapack_tcxo_disable();
return {ReferenceSource::Xtal, 25000000};
@@ -558,11 +755,11 @@ void ClockManager::enable_codec_clocks() {
#ifdef PRALINE
/* PRALINE: CLK0 (AFE_CLK) for codec/FPGA, CLK1 (SCT_CLK) for FPGA timing.
* Reference hackrf_core.c shows PRALINE needs both CLK0 and CLK1. */
clock_generator.enable_clock(clock_generator_output_og_codec); /* CLK0 */
clock_generator.enable_clock(clock_generator_output_og_cpld); /* CLK1 */
clock_generator.enable_clock(clock_generator_output_og_codec); /* CLK0 MAX5864*/
clock_generator.enable_clock(clock_generator_output_og_cpld); /* CLK1 iCE40 FPGA*/
clock_generator.enable_clock(clock_generator_output_og_sgpio); /* CLK2 LPC43xx*/
clock_generator.enable_output_mask(
(1U << clock_generator_output_og_codec) |
(1U << clock_generator_output_og_cpld));
(1U << clock_generator_output_og_codec) | (1U << clock_generator_output_og_cpld) | (1U << clock_generator_output_og_sgpio));
#else
if (hackrf_r9) {
clock_generator.enable_clock(clock_generator_output_r9_sgpio);
@@ -590,12 +787,12 @@ void ClockManager::disable_codec_clocks() {
* CLKx_DISABLE_STATE.
*/
#ifdef PRALINE
/* PRALINE: CLK0 (AFE_CLK) and CLK1 (SCT_CLK) used for codec/FPGA */
/* PRALINE: CLK0 (AFE_CLK), CLK1 (SCT_CLK), and CLK2 MCU used for codec/FPGA */
clock_generator.disable_output_mask(
(1U << clock_generator_output_og_codec) |
(1U << clock_generator_output_og_cpld));
(1U << clock_generator_output_og_codec) | (1U << clock_generator_output_og_cpld) | (1U << clock_generator_output_og_sgpio));
clock_generator.disable_clock(clock_generator_output_og_codec);
clock_generator.disable_clock(clock_generator_output_og_cpld);
clock_generator.disable_clock(clock_generator_output_og_sgpio);
#else
if (hackrf_r9) {
clock_generator.disable_output_mask(1U << clock_generator_output_r9_sgpio);
@@ -612,7 +809,7 @@ void ClockManager::disable_codec_clocks() {
void ClockManager::enable_if_clocks() {
#ifdef PRALINE
/* PRALINE uses CLK4 (first IF) and CLK5 (second IF) like original HackRF One */
/* PRALINE uses CLK5 (first IF) and CLK4 (second IF) */
clock_generator.enable_clock(clock_generator_output_og_first_if);
clock_generator.enable_output_mask(1U << clock_generator_output_og_first_if);
clock_generator.enable_clock(clock_generator_output_og_second_if);
@@ -651,23 +848,75 @@ void ClockManager::disable_if_clocks() {
void ClockManager::set_sampling_frequency(const uint32_t frequency) {
#ifdef PRALINE
/* PRALINE: CLK0=AFE_CLK runs at sample rate (VCO/divider/2)
* CLK1=SCT_CLK runs at 2x sample rate (VCO/divider/1)
* Reference: hackrf_core.c sample_rate_frac_set() lines 580-582
/*
* PRALINE sample rate strategy:
* 1. Maximize AFE rate to push Nyquist above MAX2831's 11.6 MHz LPF minimum
* 2. Use FPGA decimation to achieve desired output rate
* 3. Ensure AFE rate is achievable by Si5351 (clean division from 800 MHz VCO)
*/
/* PRALINE: Match HackRF USB sample_rate_frac_set()
* Reference: hackrf_usb radio.c lines 29-91, hackrf_core.c lines 501-685 */
constexpr uint32_t MAX_AFE_RATE = 40000000; // Use 40 MHz per GSG reference
constexpr uint8_t MAX_N = 5;
_base_band_frequency = frequency;
// Set FPGA decimation to 0 (no decimation) for direct passthrough
fpga_debug_register_write(2, 0);
uint8_t n = 0;
uint32_t afe_rate = frequency;
// Find the largest n where AFE rate stays within limit
// Start at n=0 and work up
while (n < MAX_N) {
uint32_t next_rate = afe_rate << 1;
if (next_rate > MAX_AFE_RATE) break;
afe_rate = next_rate;
n++;
}
_resampling_n = n;
// === Stop FPGA processing and flush filters ===
fpga_debug_register_write(1, 0x00); // Disable FPGA filters (resets CIC accumulators)
// Verify we're in RX mode before writing RX registers
if (fpga_get_mode() != FPGA_MODE_RX) {
// Either set mode or return error
fpga_set_mode(FPGA_MODE_RX);
}
// Set FPGA RX decimation register
fpga_debug_register_write(FPGA_REG_DECIM, n);
/* RX Mode: Register 3 is FPGA_REG_RX_DIGITAL_GAIN.
* We shift up by (3 * n) to compensate for CIC bit-growth.
* Relationship: ds = (Stages * n) - Offset
* For a 3-stage filter, every increment of n grows the signal by 3 bits.
* We subtract a baseline offset to keep the signal within 8-bit bounds.
* Add a baseline shift to ensure the signal isn't too quiet
*/
uint8_t ds = (3 * n);
ds += 2;
fpga_debug_register_write(FPGA_REG_RX_DIGITAL_GAIN, ds);
radio::invalidate_spi_config();
// The following was originally from @kitty. Adopting for testing radio.
clock_generator.set_ms_frequency(0, frequency * 2, si5351_vco_f, 1); // CLK0: r_div=1 (÷2)
clock_generator.set_ms_frequency(1, frequency * 2, si5351_vco_f, 0); // CLK1: r_div=0 (÷1)
// Configure Si5351 clocks
// CLK0: AFE_CLK (with r_div=1 for ÷2)
// CLK1: SCT_CLK (with r_div=0 for ÷1, runs at 2× AFE for FPGA timing)
// Configure Si5351 clocks using the correct AFE VCO
clock_generator.set_ms_frequency(0, afe_rate * 2, si5351_vco_afe_f, 1);
clock_generator.set_ms_frequency(1, afe_rate * 2, si5351_vco_afe_f, 0);
// === Reset PLL A for phase alignment ===
clock_generator.write_register(si5351::Register::PLLReset, 0x20);
// Brief delay for PLL lock and clock stability ===
// ~1ms at 96MHz = ~96000 cycles, use 10ms for safety
volatile uint32_t delay = 240000; // ~2.5ms
while (delay--);
// Re-enable FPGA processing with clean state ===
fpga_debug_register_write(1, 0x01);
#else
/* Codec clock is at sampling frequency, CPLD and SGPIO clocks are at
* twice the frequency, and derived from the MS0 synth. So it's only
@@ -688,10 +937,21 @@ void ClockManager::set_reference_ppb(const int32_t ppb) {
* It is assumed an external clock coming in to CLKIN/PLLB is sufficiently accurate as to not need adjustment.
* TODO: Revisit the above policy. It may be good to allow adjustment of the external reference too.
*/
#ifdef PRALINE
// On Praline, only apply if we aren't locked to a superior external 10MHz source
// (Assuming you have a way to detect the 10MHz presence on Praline)
if (reference.source == ReferenceSource::External) {
return;
}
constexpr uint32_t pll_multiplier = si5351_pll_a_afe_800m.a;
#else
if (hackrf_r9 && reference.source != ReferenceSource::Xtal) {
return;
}
constexpr uint32_t pll_multiplier = si5351_pll_xtal_25m.a;
#endif
constexpr uint32_t denominator = 1000000 / pll_multiplier;
const uint32_t new_a = (ppb >= 0) ? pll_multiplier : (pll_multiplier - 1);
const uint32_t new_b = (ppb >= 0) ? (ppb / 1000) : (denominator + (ppb / 1000));
@@ -703,8 +963,13 @@ void ClockManager::set_reference_ppb(const int32_t ppb) {
.b = new_b,
.c = new_c,
};
#ifdef PRALINE
clock_generator.write_pll_single_byte(0, pll);
#else
const auto pll_a_reg = pll.reg(0);
clock_generator.write(pll_a_reg);
#endif
}
void ClockManager::start_frequency_monitor_measurement(const cgu::CLK_SEL clk_sel) {
@@ -719,15 +984,15 @@ void ClockManager::start_frequency_monitor_measurement(const cgu::CLK_SEL clk_se
}
void ClockManager::wait_For_frequency_monitor_measurement_done() {
// FREQ_MON mechanism fails to finish if there's no clock present on selected input?!
#ifndef PRALINE
while (LPC_CGU->FREQ_MON.MEAS == 1);
#else
// FREQ_MON mechanism fails to finish if there's no clock present on selected input?!
#ifdef PRALINE
// PRALINE FIX: Add timeout to prevent infinite hang
uint32_t timeout = 100000;
while (LPC_CGU->FREQ_MON.MEAS == 1 && timeout > 0) {
timeout--;
}
#else
while (LPC_CGU->FREQ_MON.MEAS == 1);
#endif
}
@@ -740,33 +1005,89 @@ uint32_t ClockManager::get_frequency_monitor_measurement_in_hertz() {
void ClockManager::start_audio_pll() {
#ifdef PRALINE
/* PRALINE: Use 12MHz XTAL for audio PLL
* For 12MHz XTAL input, 48kHz audio rate, 256Fs MCLK:
* Fout=12.288MHz, Fcco=491.52MHz
* 12MHz * 1024 / 25 = 491.52MHz
* MSEL=1024, NSEL=25, PSEL=20
*/
// Control Block
cgu::pll0audio::ctrl({
.pd = 1,
.bypass = 0,
.directi = 0,
.directo = 0,
.clken = 0,
.frm = 0,
.autoblock = 1,
.pllfract_req = 0,
.sel_ext = 1,
.mod_pd = 1,
.clk_sel = cgu::CLK_SEL::XTAL,
.pd = 1, // Start powered down
.bypass = 0, // Use the PLL
.directi = 0, // Enable N-divider
.directo = 0, // Enable P-divider
.clken = 0, // Disable output initially
.frm = 0, // Normal mode
.autoblock = 1, // Glitchless switching
.pllfract_req = 1, // Integer, Disabled
.sel_ext = 1, // Use GP_CLKIN (CLK2)
.mod_pd = 0, // Modulator OFF
.clk_sel = cgu::CLK_SEL::GP_CLKIN,
});
cgu::pll0audio::mdiv({
.mdec = 22625UL, // MDEC for MSEL=1024
});
/*
* Audio PLL Configuration for 48 kHz audio with 256Fs MCLK
* Target output: Fout = 12.288 MHz
*
* Formulas:
* Fout = Fin × MSEL / (NSEL × PSEL)
* FCO = 2 × Fin × MSEL / NSEL (must be 275-550 MHz)
*/
/*
*
* 10 MHz INPUT (HackRF r9 compatible but interfere with fm band)
*
* MSEL=3072, NSEL=125, PSEL=20
* Fout = 10 × 3072 / (125 × 20) = 30720 / 2500 = 12.288 MHz
* FCO = 2 × 10 × 3072 / 125 = 61440 / 125 = 491.52 MHz
*
* Encoded values: MDEC=8308, NDEC=45, PDEC=31
* CLK2 harmonics: 90, 100, 110 MHz (interfere with FM band!)
*
*/
/*
// Math: (10 MHz * 3072) / (125 * 20) * 2 = 12.288MHz
cgu::pll0audio::mdiv({.mdec = 8308UL}); // MSEL = 3072
cgu::pll0audio::np_div({
.pdec = 31, // PSEL=20
.ndec = 69, // NDEC for NSEL=25
.pdec = 31, // PSEL = 20 for 10 MHz
.ndec = 45 // NSEL = 125 for 10 MHz
});
*/
/*
*
* 40 MHz INPUT (Recommended - avoids FM band harmonics)
*
* MSEL=768, NSEL=125, PSEL=20
* Fout = 40 × 768 / (125 × 20) = 30720 / 2500 = 12.288 MHz
* FCO = 2 × 40 × 768 / 125 = 61440 / 125 = 491.52 MHz
*
* Encoded values: MDEC=30542, NDEC=45, PDEC=31
* CLK2 harmonics: 80, 120, 160 MHz (none in FM 88-108 MHz band)
*
*/
// 40 MHz input → 12.288 MHz output (same as HackRF OG)
// Math: (40MHz * 768) / (125 * 20) * 2 = 12.288MHz
cgu::pll0audio::mdiv({.mdec = 30542UL}); // MSEL = 768
cgu::pll0audio::np_div({.pdec = 31,
.ndec = 45});
cgu::pll0audio::frac({.pllfract_ctrl = 0});
cgu::pll0audio::power_up();
// Lock and Routing (Keep as is)
{
uint32_t timeout = 100000;
while (!cgu::pll0audio::is_locked() && timeout > 0) {
timeout--;
}
}
cgu::pll0audio::clock_enable();
set_base_audio_clock_divider(1);
LPC_CGU->BASE_AUDIO_CLK.AUTOBLOCK = 1;
LPC_CGU->BASE_AUDIO_CLK.CLK_SEL = toUType(cgu::CLK_SEL::IDIVD);
#else
cgu::pll0audio::ctrl({
.pd = 1,
@@ -796,30 +1117,21 @@ void ClockManager::start_audio_pll() {
.pdec = 31,
.ndec = 45,
});
#endif
cgu::pll0audio::frac({
.pllfract_ctrl = 0,
});
cgu::pll0audio::power_up();
#ifndef PRALINE
while (!cgu::pll0audio::is_locked());
#else
// PRALINE FIX: Add timeout to prevent infinite hang if GP_CLKIN not present
{
uint32_t timeout = 100000;
while (!cgu::pll0audio::is_locked() && timeout > 0) {
timeout--;
}
}
#endif
cgu::pll0audio::clock_enable();
while (!cgu::pll0audio::is_locked());
cgu::pll0audio::clock_enable();
set_base_audio_clock_divider(1);
LPC_CGU->BASE_AUDIO_CLK.AUTOBLOCK = 1;
LPC_CGU->BASE_AUDIO_CLK.CLK_SEL = toUType(cgu::CLK_SEL::IDIVD);
#endif
}
void ClockManager::set_base_audio_clock_divider(const size_t divisor) {
@@ -828,12 +1140,46 @@ void ClockManager::set_base_audio_clock_divider(const size_t divisor) {
}
void ClockManager::stop_audio_pll() {
#ifdef PRALINE
/* PRALINE: Gracefully switch audio peripherals away from the PLL branch */
LPC_CGU->BASE_AUDIO_CLK.PD = 1; // Power down the branch first
LPC_CGU->BASE_AUDIO_CLK.CLK_SEL = toUType(cgu::CLK_SEL::IRC); // Reset to safe IRC source
#endif
cgu::pll0audio::clock_disable();
cgu::pll0audio::power_down();
#ifdef PRALINE
/* PRALINE: Add a safety timeout to the unlock check to prevent potential hangs */
uint32_t timeout = 100000;
while (cgu::pll0audio::is_locked() && timeout > 0) {
timeout--;
}
#else
while (cgu::pll0audio::is_locked());
#endif
}
void ClockManager::enable_clock_output(bool enable) {
#ifdef PRALINE
auto clkout_select = clock_generator_output_og_clkout;
if (enable) {
clock_generator.enable_output(clkout_select);
if (portapack::persistent_memory::clkout_freq() < 1000) {
clock_generator.set_ms_frequency(clkout_select, portapack::persistent_memory::clkout_freq() * 128000, si5351_vco_f, 7);
} else {
clock_generator.set_ms_frequency(clkout_select, portapack::persistent_memory::clkout_freq() * 1000, si5351_vco_f, 0);
}
auto si5351_clock_control_common = si5351a_clock_control_common;
const auto ref_pll = get_si5351a_reference_clock_generator_pll(reference.source);
clock_generator.set_clock_control(clkout_select, si5351_clock_control_common[clkout_select].ms_src(ref_pll).clk_pdn(ClockControl::ClockPowerDown::Power_On));
} else {
clock_generator.disable_output(clkout_select);
clock_generator.set_clock_control(clkout_select, ClockControl::power_off());
}
#else
if (hackrf_r9) {
gpio_r9_clkout_en.output();
gpio_r9_clkout_en.write(enable);
@@ -862,4 +1208,5 @@ void ClockManager::enable_clock_output(bool enable) {
clock_generator.disable_output(clkout_select);
clock_generator.set_clock_control(clkout_select, ClockControl::power_off());
}
#endif
}
+6
View File
@@ -77,6 +77,8 @@ class ClockManager {
void set_reference_ppb(const int32_t ppb);
#ifdef PRALINE
uint8_t get_resampling_n() const { return _resampling_n; }
// Si5351 diagnostic methods
uint8_t si5351_read_status() { return clock_generator.device_status(); }
uint8_t si5351_read_register(uint8_t reg) { return clock_generator.read_register(reg); }
@@ -112,6 +114,10 @@ class ClockManager {
ReferenceSource detect_reference_source();
Reference choose_reference();
bool loss_of_signal();
#ifdef PRALINE
uint8_t _resampling_n{0}; // Current decimation factor (log2)
#endif
};
#endif /*__CLOCK_MANAGER_H__*/
+194 -3
View File
@@ -37,8 +37,20 @@
#include "ch.h"
#include "lpc43xx_cpp.hpp"
using namespace lpc43xx;
#include "hackrf_gpio.hpp"
using namespace hackrf::one;
#include "irq_rtc.hpp"
#include "i2c_lld.h"
#include "i2cdevmanager.hpp"
#include "i2cdev_ppmod.hpp"
#include "lpc43xx.inc"
#include "nvic.h"
#include "lpc43xx_m0.h"
#include "rffc507x_spi.hpp"
#include <array>
@@ -134,7 +146,186 @@ void EventDispatcher::set_display_sleep(const bool sleep) {
// Let frame sync handler turn on backlight after repaint.
}
EventDispatcher::display_sleep = sleep;
};
}
void EventDispatcher::charge_deep_sleep(const bool sleep) {
bool detect = false;
uint8_t valid_mask = 0;
uint8_t percent = 0;
uint16_t voltage = 0;
int32_t current = 0;
constexpr I2CConfig i2c_config_12mhz{
.high_count = 15,
.low_count = 15,
};
if (sleep) {
auto dev = (i2cdev::I2cDev_PPmod*)i2cdev::I2CDevManager::get_dev_by_model(I2C_DEVMDL::I2CDECMDL_PPMOD);
if (dev) dev->send_poweroff_command();
rffc507x::spi::SPI().power_down();
portapack::shutdown(false, true);
// Unmount SD card and stop driver
f_mount(nullptr, reinterpret_cast<const TCHAR*>(_T("")), 0);
sdcDisconnect(&SDCD1);
sdcStop(&SDCD1);
// Signal application shutdown
ShutdownMessage shutdown_message;
shared_memory.application_queue.push(shutdown_message);
shared_memory.baseband_message = nullptr;
// Disable core interrupts and system tick
nvicDisableVector(DMA_IRQn);
nvicDisableVector(M4CORE_IRQn);
chSysDisable();
systick_stop();
SCB->ICSR |= SCB_ICSR_PENDSTCLR_Msk;
#ifdef PRALINE
// Power management and GPIO configuration for Praline hardware
gpio_vaa_disable.set();
gpio_1v2_enable.clear();
LPC_GPIO->DIR[0] &= ~0xFFFF4000;
LPC_GPIO->DIR[1] &= ~0xFFFF1000;
LPC_GPIO->DIR[2] &= ~((1 << 14) | (1 << 13) | (1 << 12) | (1 << 11) | (1 << 10) | (1 << 6) | (1 << 0));
LPC_GPIO->DIR[3] &= ~((1 << 7) | (1 << 5));
LPC_GPIO->DIR[5] &= ~(1 << 16);
#else
// Power management and GPIO configuration for legacy hardware
gpio_og_vaa_disable.set();
gpio_r9_vaa_disable.clear();
LPC_GPIO->DIR[0] &= ~0xFFFF4000;
LPC_GPIO->DIR[1] &= ~0xFFFF1000;
LPC_GPIO->DIR[2] &= ~((1 << 14) | (1 << 13) | (1 << 12) | (1 << 11) | (1 << 10) | (1 << 6) | (1 << 0));
LPC_GPIO->DIR[3] &= ~((1 << 7) | (1 << 5));
LPC_GPIO->DIR[5] &= ~(1 << 16);
#endif
// Power down peripherals (CGU cleanup)
LPC_RGU->RESET_CTRL[0] = (1 << 5); // USB0 Reset
LPC_CGU->PLL0USB_CTRL.PD = 1;
LPC_CGU->BASE_USB0_CLK.PD = 1;
LPC_CREG->CREG0 |= (1 << 5);
LPC_CGU->BASE_USB1_CLK.PD = 1;
LPC_CGU->BASE_UART0_CLK.PD = 1;
LPC_CGU->BASE_UART1_CLK.PD = 1;
LPC_CGU->BASE_UART2_CLK.PD = 1;
LPC_CGU->BASE_UART3_CLK.PD = 1;
LPC_CGU->BASE_SPI_CLK.PD = 1;
LPC_CGU->BASE_PERIPH_CLK.PD = 1;
LPC_CGU->BASE_SDIO_CLK.PD = 1;
LPC_CGU->BASE_SSP0_CLK.PD = 1;
LPC_CGU->BASE_SSP1_CLK.PD = 1;
LPC_CGU->BASE_LCD_CLK.PD = 1;
LPC_CGU->BASE_OUT_CLK.PD = 1;
(*(volatile uint32_t*)(&LPC_CGU->PLL0AUDIO_CTRL)) |= (1 << 0);
LPC_ADC0->CR &= ~(1 << 21);
LPC_ADC1->CR &= ~(1 << 21);
led_rx.off();
led_usb.off();
rtc_wakeup_init();
NVIC_EnableIRQ(I2C0_OR_I2C1_IRQn);
while (1) {
// --- Battery Status Check (I2C) ---
detect = battery::BatteryManagement::isDetected();
if (detect) {
battery::BatteryManagement::getBatteryInfo(valid_mask, percent, voltage, current);
bool is_full = (valid_mask == 31 && percent == 100 && current <= 10) ||
(valid_mask == 1 && percent == 100);
if (is_full) {
// Case 1: Battery full (All LEDs off)
led_rx.off();
led_tx.off();
} else if ((voltage < 4150 && current < 10) || valid_mask == 0) {
// Case 2: Not full but low current draw (<10mA) -> Charging error
led_tx.on(); // LED indicates error/idle
led_rx.off();
} else {
// Case 3: Actively charging
led_rx.on(); // LED indicates charging
led_tx.off();
}
} else {
// Case 4: Battery IC not detected -> Error or H2 or older, so don't show that as an error.
led_tx.on();
led_rx.on();
}
// Shut down I2C and power down the APB bus for sleep
portapack::i2c0.stop();
LPC_CGU->BASE_APB1_CLK.PD = 1;
// Save interrupt states before mass disable
uint32_t saved_iser0 = NVIC->ISER[0];
// Disable and clear all pending interrupts
NVIC->ICER[0] = 0xFFFFFFFF;
NVIC->ICPR[0] = 0xFFFFFFFF;
// Re-enable only necessary wakeup sources
NVIC_EnableIRQ(RTC_IRQn);
NVIC_EnableIRQ(EVENTROUTER_IRQn);
// Configure RTC wakeup interval
if (valid_mask != 0 || detect) {
rtc_wakeup(60);
} else {
rtc_wakeup(3);
}
LPC_RTC->ILR = 3;
LPC_EVENTROUTER->CLR_STAT = 0xFFFFFFFF;
NVIC_ClearPendingIRQ(RTC_IRQn);
NVIC_ClearPendingIRQ(EVENTROUTER_IRQn);
__disable_irq();
// Configure and enter Deep Sleep
SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
__DSB();
__ISB();
// CPU enters sleep here
__WFI();
// --- WAKEUP SEQUENCE ---
__enable_irq();
SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk;
// Cleanup RTC and restore peripheral clocks
LPC_RTC->AMR = 0xFF;
LPC_RTC->ILR = 3;
LPC_CGU->BASE_APB1_CLK.PD = 0;
LPC_RGU->RESET_CTRL[1] = (1 << 16);
// Short delay for power stability (3V3 rail)
for (volatile int d = 0; d < 10000; d++);
// Restart I2C controller
LPC_CGU->BASE_APB1_CLK.PD = 0;
portapack::i2c0.start(i2c_config_12mhz);
// Restore original interrupt enable states
NVIC->ISER[0] = saved_iser0;
} // End of while(1) deep sleep loop
} else {
portapack::display.wake(true);
}
}
eventmask_t EventDispatcher::wait() {
return chEvtWaitAny(ALL_EVENTS);
+2
View File
@@ -63,6 +63,8 @@ class EventDispatcher {
static void set_display_sleep(const bool sleep);
static void charge_deep_sleep(const bool sleep);
static inline void check_fifo_isr() {
if (!shared_memory.application_queue.is_empty()) {
events_flag_isr(EVT_MASK_APPLICATION);
+73 -4
View File
@@ -33,6 +33,76 @@ using namespace portapack;
namespace ui::external_app::acars_rx {
// ACARS frame field layout (0-based byte offsets):
// [0] SOH framing byte (skipped)
// [1..7] Aircraft registration (7 chars)
// [8] STX framing byte (skipped)
// [9..10] Label (2 chars)
// [11] Block ID (1 char)
// [12..14] Message number (3 chars)
// [15..20] Flight ID (6 chars)
// [21..N-3] Free-text payload (variable)
// [N-2..N-1] CRC-16/CCITT (2 bytes, MSB first, NOT part of payload)
//
// Minimum valid frame: 21-byte fixed header + 2 CRC bytes = 23 bytes.
// (A zero-length payload is legal per spec; we require at least 23 bytes.)
static constexpr std::string::size_type kAcarsCrcLen = 2;
static constexpr std::string::size_type kAcarsHeaderLen = 21;
static constexpr std::string::size_type kAcarsMinLen = kAcarsHeaderLen + kAcarsCrcLen;
// CRC-16/CCITT: poly 0x1021, init 0x0000, no reflection, no final XOR.
// This is the variant used by ACARS (same as XMODEM CRC).
static uint16_t acars_crc16(const std::string& data, std::string::size_type len) {
uint16_t crc = 0x0000;
for (std::string::size_type i = 0; i < len; ++i) {
crc ^= static_cast<uint16_t>(static_cast<uint8_t>(data[i])) << 8;
for (int bit = 0; bit < 8; ++bit) {
if (crc & 0x8000)
crc = static_cast<uint16_t>((crc << 1) ^ 0x1021);
else
crc = static_cast<uint16_t>(crc << 1);
}
}
return crc;
}
AcarsDecoded acars_decode(const std::string& raw) {
AcarsDecoded result;
if (raw.size() < kAcarsMinLen) {
result.txt = "ACARS message too short (" + std::to_string(raw.size()) +
" bytes, need " + std::to_string(kAcarsMinLen) + ")";
return result;
}
// Verify CRC: computed over everything except the last 2 bytes,
// then compared against those 2 bytes (MSB first).
const std::string::size_type payload_len = raw.size() - kAcarsCrcLen;
const uint16_t computed = acars_crc16(raw, payload_len);
const uint16_t received = (static_cast<uint16_t>(static_cast<uint8_t>(raw[raw.size() - 2])) << 8) |
static_cast<uint16_t>(static_cast<uint8_t>(raw[raw.size() - 1]));
result.crc_ok = (computed == received);
result.reg = raw.substr(1, 7);
result.label = raw.substr(9, 2);
result.block_id = raw[11];
result.msg_num = raw.substr(12, 3);
result.flight_id = raw.substr(15, 6);
// Payload sits between end of fixed header and the 2 trailing CRC bytes.
if (payload_len > kAcarsHeaderLen)
result.txt = raw.substr(kAcarsHeaderLen, payload_len - kAcarsHeaderLen);
return result;
}
std::string acars_format(const AcarsDecoded& msg) {
return std::string("ACARS Decoded Result\nCRC: ") + (msg.crc_ok ? "OK" : "FAIL") +
"\nRegistration: " + msg.reg +
"\nLabel: " + msg.label +
"\nBlockID: " + msg.block_id +
"\nMsgNum: " + msg.msg_num +
"\nFlightID: " + msg.flight_id +
"\nMessage: " + msg.txt;
}
void ACARSLogger::log_str(std::string msg) {
log_file.write_entry(msg);
}
@@ -77,17 +147,16 @@ void ACARSAppView::focus() {
void ACARSAppView::on_packet(const ACARSPacketMessage* packet) {
std::string console_info;
if (packet->state == 255) {
// got a packet, parse it, and display
rtc::RTC datetime;
rtc_time::now(datetime);
// todo parity error recovery
console_info = to_string_datetime(datetime, HMS);
console_info += ": ";
console_info += packet->message;
std::string message{packet->message, packet->message + packet->msg_len};
AcarsDecoded decoded = acars_decode(message);
console_info += acars_format(decoded);
console.writeln(console_info);
// Log raw data whatever it contains
if (logger && logging)
logger->log_str(console_info);
} else {
+21 -1
View File
@@ -33,6 +33,26 @@
namespace ui::external_app::acars_rx {
// Decoded ACARS message fields extracted from a raw frame.
// CRC-16/CCITT (poly 0x1021, init 0x0000) is verified against the two
// trailing bytes of the raw frame; crc_ok reflects that result.
struct AcarsDecoded {
bool crc_ok{false};
std::string reg{};
std::string label{};
std::string flight_id{};
std::string msg_num{};
char block_id{'\0'};
std::string txt{};
};
// Decode a raw ACARS frame: verify CRC-16/CCITT and extract fixed-offset fields.
// Returns a partially-filled AcarsDecoded (txt error only) if the frame is too short.
AcarsDecoded acars_decode(const std::string& raw);
// Format a decoded ACARS message for display or logging.
std::string acars_format(const AcarsDecoded& msg);
class ACARSLogger {
public:
Optional<File::Error> append(const std::filesystem::path& filename) {
@@ -106,4 +126,4 @@ class ACARSAppView : public View {
} // namespace ui::external_app::acars_rx
#endif /*__ACARS_APP_H__*/
#endif /*__ACARS_APP_H__*/
+83 -83
View File
@@ -1,83 +1,83 @@
/*
* Copyright (C) 2023 Bernd Herzog
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui.hpp"
#include "acars_app.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::acars_rx {
void initialize_app(ui::NavigationView& nav) {
nav.push<ACARSAppView>();
}
} // namespace ui::external_app::acars_rx
extern "C" {
__attribute__((section(".external_app.app_acars_rx.application_information"), used)) application_information_t _application_information_acars_rx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::acars_rx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "ACARS",
/*.bitmap_data = */ {
0x80,
0x01,
0xC0,
0x03,
0xC0,
0x03,
0xC0,
0x03,
0xC0,
0x03,
0xE0,
0x07,
0xF8,
0x1F,
0xFE,
0x7F,
0xFF,
0xFF,
0xFF,
0xFF,
0xC0,
0x03,
0xC0,
0x03,
0xC0,
0x03,
0xE0,
0x07,
0xF0,
0x0F,
0xF8,
0x1F,
},
/*.icon_color = */ ui::Color::orange().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_acars */ {'P', 'A', 'C', 'A'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
}
/*
* Copyright (C) 2023 Bernd Herzog
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui.hpp"
#include "acars_app.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::acars_rx {
void initialize_app(ui::NavigationView& nav) {
nav.push<ACARSAppView>();
}
} // namespace ui::external_app::acars_rx
extern "C" {
__attribute__((section(".external_app.app_acars_rx.application_information"), used)) application_information_t _application_information_acars_rx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::acars_rx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "ACARS",
/*.bitmap_data = */ {
0x80,
0x01,
0xC0,
0x03,
0xC0,
0x03,
0xC0,
0x03,
0xC0,
0x03,
0xE0,
0x07,
0xF8,
0x1F,
0xFE,
0x7F,
0xFF,
0xFF,
0xFF,
0xFF,
0xC0,
0x03,
0xC0,
0x03,
0xC0,
0x03,
0xE0,
0x07,
0xF0,
0x0F,
0xF8,
0x1F,
},
/*.icon_color = */ ui::Color::orange().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_acars */ {'P', 'A', 'C', 'A'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
}
+29 -25
View File
@@ -131,35 +131,39 @@ void TVView::on_channel_spectrum(
// I was hoping that by doing this, I can have a longer buffer like 39936, then the frame will looks better vertically
// however this is useless until now.
for (size_t i = 0; i < 256; i++) {
// video_buffer[i+count*256] = spectrum_rgb4_lut[spectrum.db[i]];
video_buffer_int[i + count * 256] = 255 - spectrum.db[i];
// Left the original comment, but rewrote the function.
// Shift the last 128 pixels of the previous packet to the front
// This overlap handles an x_correction shift of up to 128 pixels seamlessly.
for (size_t i = 0; i < 128; i++) {
window_buffer[i] = window_buffer[i + 256];
}
count = count + 1;
if (count == 52 - 1) {
ui::Color line_buffer[128];
Coord line;
uint32_t bmp_px;
/*for (line = 0; line < 104; line++)
{
for (bmp_px = 0; bmp_px < 128; bmp_px++)
{
//line_buffer[bmp_px] = video_buffer[bmp_px+line*128];
line_buffer[bmp_px] = spectrum_rgb4_lut[video_buffer_int[bmp_px+line*128 + x_correction]];
}
// Load the new 256 pixels into the remainder of the buffer
for (size_t i = 0; i < 256; i++) {
window_buffer[i + 128] = 255 - spectrum.db[i];
}
display.render_line({ 0, line + 100 }, 128, line_buffer);
}*/
for (line = 0; line < 208; line = line + 2) {
for (bmp_px = 0; bmp_px < 128; bmp_px++) {
// line_buffer[bmp_px] = video_buffer[bmp_px+line*128];
line_buffer[bmp_px] = spectrum_rgb4_lut[video_buffer_int[bmp_px + line / 2 * 128 + x_correction]];
}
ui::Color line_buffer[128];
display.render_line({0, line + 100}, 128, line_buffer);
display.render_line({0, line + 101}, 128, line_buffer);
}
// Render the first line of this batch (matches original doubled-height behavior)
for (size_t bmp_px = 0; bmp_px < 128; bmp_px++) {
line_buffer[bmp_px] = spectrum_rgb4_lut[window_buffer[bmp_px + x_correction]];
}
display.render_line({0, (Coord)(count * 4 + 100)}, 128, line_buffer);
display.render_line({0, (Coord)(count * 4 + 101)}, 128, line_buffer);
// Render the second line of this batch
for (size_t bmp_px = 0; bmp_px < 128; bmp_px++) {
line_buffer[bmp_px] = spectrum_rgb4_lut[window_buffer[bmp_px + 128 + x_correction]];
}
display.render_line({0, (Coord)(count * 4 + 102)}, 128, line_buffer);
display.render_line({0, (Coord)(count * 4 + 103)}, 128, line_buffer);
count++;
// Reset at 52 (52 * 2 lines = 104 lines total)
if (count >= 52) {
count = 0;
}
}
+3 -2
View File
@@ -79,8 +79,9 @@ class TVView : public Widget {
void paint(Painter& painter) override;
void on_channel_spectrum(const ChannelSpectrum& spectrum);
void on_adjust_xcorr(uint8_t xcorr);
// ui::Color video_buffer[13312];
uint8_t video_buffer_int[13312 + 128]{0}; // 128 is for the over length caused by x_correction
// 256 samples from current callback + 128 overlap from the previous callback
uint8_t window_buffer[384]{0};
uint32_t count = 0;
uint8_t x_correction = 0;
+1 -1
View File
@@ -45,7 +45,7 @@ __attribute__((section(".external_app.app_battleship.application_information"),
0xFF, 0xFF, // ################
0xFC, 0x3F, // ..############..
},
/*.icon_color = */ ui::Color::blue().v,
/*.icon_color = */ ui::Color::green().v,
/*.menu_location = */ app_location_t::GAMES,
/*.desired_menu_position = */ -1,
+89 -105
View File
@@ -6,11 +6,9 @@
* ------------------------------------------------------------
*/
#pragma GCC push_options
#pragma GCC optimize("Os")
#include "ui_battleship.hpp"
#include "portapack_shared_memory.hpp"
#include "utility.hpp"
#include "modems.hpp"
#include "bch_code.hpp"
using namespace portapack;
using namespace modems;
@@ -28,7 +26,6 @@ BattleshipView::BattleshipView(NavigationView& nav)
baseband::run_image(portapack::spi_flash::image_tag_pocsag2);
add_children({&text_title, &text_subtitle,
//&rect_radio_settings, &rect_audio_settings, &rect_team_selection,
&label_radio, &button_frequency,
&label_rf_amp, &checkbox_rf_amp,
&label_lna, &field_lna,
@@ -151,8 +148,6 @@ BattleshipView::BattleshipView(NavigationView& nav)
field_tx_gain.set_parent_rect({185, 118, 32, 16});
checkbox_sound.set_parent_rect({17, 187, 80, 24});
field_volume.set_parent_rect({165, 187, 32, 16});
// button_red_team.set_parent_rect({25, 242, 85, 45});
// button_blue_team.set_parent_rect({130, 242, 85, 45});
// Make menu elements focusable
button_frequency.set_focusable(true);
@@ -196,34 +191,22 @@ void BattleshipView::init_game() {
}
void BattleshipView::show_hide_menu(bool menu_vis) {
text_title.hidden(!menu_vis);
text_subtitle.hidden(!menu_vis);
// rect_radio_settings.hidden(!menu_vis); rect_audio_settings.hidden(!menu_vis); rect_team_selection.hidden(!menu_vis);
label_radio.hidden(!menu_vis);
button_frequency.hidden(!menu_vis);
label_rf_amp.hidden(!menu_vis);
checkbox_rf_amp.hidden(!menu_vis);
label_lna.hidden(!menu_vis);
field_lna.hidden(!menu_vis);
label_vga.hidden(!menu_vis);
field_vga.hidden(!menu_vis);
label_tx_gain.hidden(!menu_vis);
field_tx_gain.hidden(!menu_vis);
label_audio.hidden(!menu_vis);
checkbox_sound.hidden(!menu_vis);
label_volume.hidden(!menu_vis);
field_volume.hidden(!menu_vis);
label_team.hidden(!menu_vis);
button_red_team.hidden(!menu_vis);
button_blue_team.hidden(!menu_vis);
rssi.hidden(menu_vis);
button_rotate.hidden(menu_vis);
button_place.hidden(menu_vis);
button_menu.hidden(menu_vis);
Widget* const menu_widgets[] = {
&text_title, &text_subtitle, &label_radio, &button_frequency,
&label_rf_amp, &checkbox_rf_amp, &label_lna, &field_lna,
&label_vga, &field_vga, &label_tx_gain, &field_tx_gain,
&label_audio, &checkbox_sound, &label_volume, &field_volume,
&label_team, &button_red_team, &button_blue_team};
for (auto* w : menu_widgets) {
w->hidden(!menu_vis);
}
Widget* const game_widgets[] = {
&rssi, &button_rotate, &button_place, &button_menu};
for (auto* w : game_widgets) {
w->hidden(menu_vis);
}
// button_rotate.set_focusable(false); //no need, since can't focus on hidden
// button_place.set_focusable(false);
// button_menu.set_focusable(false);
set_dirty();
}
@@ -340,40 +323,23 @@ void BattleshipView::paint(Painter& painter) {
if (game_state == GameState::MENU) {
draw_menu_screen(painter);
// Custom paint team buttons
if (!button_red_team.hidden()) {
Rect r = button_red_team.screen_rect();
painter.fill_rectangle(r, Color::dark_red());
painter.draw_rectangle(r, Color::red());
auto draw_team_btn = [&painter](Button& btn, Color bg, Color border, const char* name) {
if (btn.hidden()) return;
Rect r = btn.screen_rect();
painter.fill_rectangle(r, bg);
painter.draw_rectangle(r, border);
if (button_red_team.has_focus()) {
if (btn.has_focus()) {
painter.draw_rectangle({r.location().x() - 1, r.location().y() - 1, r.size().width() + 2, r.size().height() + 2}, Color::yellow());
}
auto style_white = Style{
.font = ui::font::fixed_8x16,
.background = Color::dark_red(),
.foreground = Color::white()};
painter.draw_string(r.center() - Point(24, 16), style_white, "RED");
painter.draw_string(r.center() - Point(24, 0), style_white, "TEAM");
}
auto style = Style{.font = ui::font::fixed_8x16, .background = bg, .foreground = Color::white()};
painter.draw_string(r.center() - Point(24, 16), style, name);
painter.draw_string(r.center() - Point(24, 0), style, "TEAM");
};
if (!button_blue_team.hidden()) {
Rect r = button_blue_team.screen_rect();
painter.fill_rectangle(r, Color::dark_blue());
painter.draw_rectangle(r, Color::blue());
if (button_blue_team.has_focus()) {
painter.draw_rectangle({r.location().x() - 1, r.location().y() - 1, r.size().width() + 2, r.size().height() + 2}, Color::yellow());
}
auto style_white = Style{
.font = ui::font::fixed_8x16,
.background = Color::dark_blue(),
.foreground = Color::white()};
painter.draw_string(r.center() - Point(24, 16), style_white, "BLUE");
painter.draw_string(r.center() - Point(24, 0), style_white, "TEAM");
}
draw_team_btn(button_red_team, Color::dark_red(), Color::red(), "RED");
draw_team_btn(button_blue_team, Color::dark_blue(), Color::blue(), "BLUE");
return;
}
@@ -417,27 +383,25 @@ void BattleshipView::paint(Painter& painter) {
void BattleshipView::draw_menu_screen(Painter& painter) {
painter.draw_hline({12, 20 + 16}, screen_width - 24, Color::dark_cyan());
painter.fill_rectangle({13, 59, screen_width - 26, 116}, Color::dark_grey());
painter.draw_hline({12, 58}, screen_width - 24, Color::cyan());
painter.draw_hline({12, 157}, screen_width - 24, Color::cyan());
const struct {
Rect rect;
Point line1_pos;
Point line2_pos;
} boxes[] = {
{{13, 59, screen_width - 26, 116}, {12, 58}, {12, 157}},
{{13, 165, screen_width - 24, 57}, {12, 164}, {12, 223}},
{{13, 232, screen_width - 26, 67}, {12, 232}, {12, 300}}};
painter.fill_rectangle({13, 165, screen_width - 24, 57}, Color::dark_grey());
painter.draw_hline({12, 164}, screen_width - 24, Color::cyan());
painter.draw_hline({12, 223}, screen_width - 24, Color::cyan());
painter.fill_rectangle({13, 232, screen_width - 26, 67}, Color::dark_grey());
painter.draw_hline({12, 232}, screen_width - 24, Color::cyan());
painter.draw_hline({12, 300}, screen_width - 24, Color::cyan());
for (const auto& box : boxes) {
painter.fill_rectangle(box.rect, Color::dark_grey());
painter.draw_hline(box.line1_pos, screen_width - 24, Color::cyan());
painter.draw_hline(box.line2_pos, screen_width - 24, Color::cyan());
}
// Radio status indicator
Point indicator_pos{UI_POS_MAXWIDTH - 20, 59};
if (is_transmitting) {
painter.fill_rectangle({indicator_pos, {6, 6}}, Color::red());
painter.draw_rectangle({indicator_pos.x() - 1, indicator_pos.y() - 1, 8, 8}, Color::light_grey());
} else {
painter.fill_rectangle({indicator_pos, {6, 6}}, Color::green());
painter.draw_rectangle({indicator_pos.x() - 1, indicator_pos.y() - 1, 8, 8}, Color::light_grey());
}
painter.fill_rectangle({indicator_pos, {6, 6}}, is_transmitting ? Color::red() : Color::green());
painter.draw_rectangle({indicator_pos.x() - 1, indicator_pos.y() - 1, 8, 8}, Color::light_grey());
}
void BattleshipView::draw_grid(Painter& painter, uint16_t grid_x, uint16_t grid_y, const std::array<std::array<CellState, GRID_SIZE>, GRID_SIZE>& grid, bool show_ships, bool is_offense_grid) {
@@ -464,11 +428,14 @@ void BattleshipView::draw_cell(Painter& painter, uint16_t cell_x, uint16_t cell_
if (game_state == GameState::PLACING_SHIPS && !is_offense_grid && current_ship_index < 5) {
uint8_t ship_size = my_ships[current_ship_index].size();
uint8_t dx = placing_horizontal ? 1 : 0;
uint8_t dy = placing_horizontal ? 0 : 1;
uint16_t grid_x = (cell_x - 1) / CELL_SIZE;
uint16_t grid_y = (cell_y - GRID_OFFSET_Y - 6) / CELL_SIZE;
for (uint8_t i = 0; i < ship_size; i++) {
uint16_t preview_x = placing_horizontal ? cursor_x + i : cursor_x;
uint16_t preview_y = placing_horizontal ? cursor_y : cursor_y + i;
uint16_t grid_x = (cell_x - 1) / CELL_SIZE;
uint16_t grid_y = (cell_y - GRID_OFFSET_Y - 6) / CELL_SIZE;
uint16_t preview_x = cursor_x + (i * dx);
uint16_t preview_y = cursor_y + (i * dy);
if (grid_x == preview_x && grid_y == preview_y && preview_x < GRID_SIZE && preview_y < GRID_SIZE) {
return;
}
@@ -540,9 +507,12 @@ void BattleshipView::draw_ship_preview(Painter& painter) {
uint8_t size = ship.size();
bool can_place = can_place_ship(cursor_x, cursor_y, size, placing_horizontal);
uint8_t dx = placing_horizontal ? 1 : 0;
uint8_t dy = placing_horizontal ? 0 : 1;
for (uint8_t i = 0; i < size; i++) {
uint8_t x = placing_horizontal ? cursor_x + i : cursor_x;
uint8_t y = placing_horizontal ? cursor_y : cursor_y + i;
uint8_t x = cursor_x + (i * dx);
uint8_t y = cursor_y + (i * dy);
if (x < GRID_SIZE && y < GRID_SIZE) {
uint16_t cell_x = GRID_OFFSET_X + x * CELL_SIZE + 1;
@@ -561,18 +531,21 @@ bool BattleshipView::can_place_ship(uint8_t x, uint8_t y, uint8_t size, bool hor
return false;
}
uint8_t dx = horizontal ? 1 : 0;
uint8_t dy = horizontal ? 0 : 1;
for (uint8_t i = 0; i < size; i++) {
uint8_t check_x = horizontal ? x + i : x;
uint8_t check_y = horizontal ? y : y + i;
uint8_t check_x = x + (i * dx);
uint8_t check_y = y + (i * dy);
if (my_grid[check_y][check_x] != CellState::EMPTY) {
return false;
}
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int adj_x = check_x + dx;
int adj_y = check_y + dy;
for (int ddy = -1; ddy <= 1; ddy++) {
for (int ddx = -1; ddx <= 1; ddx++) {
int adj_x = check_x + ddx;
int adj_y = check_y + ddy;
if (adj_x >= 0 && adj_x < GRID_SIZE &&
adj_y >= 0 && adj_y < GRID_SIZE) {
@@ -604,10 +577,11 @@ void BattleshipView::place_ship() {
ship.horizontal = placing_horizontal;
ship.placed = true;
uint8_t dx = placing_horizontal ? 1 : 0;
uint8_t dy = placing_horizontal ? 0 : 1;
for (uint8_t i = 0; i < size; i++) {
uint8_t x = placing_horizontal ? cursor_x + i : cursor_x;
uint8_t y = placing_horizontal ? cursor_y : cursor_y + i;
my_grid[y][x] = CellState::SHIP;
my_grid[cursor_y + (i * dy)][cursor_x + (i * dx)] = CellState::SHIP;
}
current_ship_index++;
@@ -644,9 +618,14 @@ void BattleshipView::place_ship() {
void BattleshipView::send_message(const GameMessage& msg) {
static const char* msg_strings[] = {"READY", "SHOT:", "HIT:", "MISS:", "SUNK:", "WIN"};
std::string message = msg_strings[static_cast<int>(msg.type)];
std::string message;
message.reserve(16);
message.append(msg_strings[static_cast<int>(msg.type)]);
if (msg.type != MessageType::READY && msg.type != MessageType::WIN) {
message += to_string_dec_uint(msg.x) + "," + to_string_dec_uint(msg.y);
message.append(to_string_dec_uint(msg.x));
message.append(",");
message.append(to_string_dec_uint(msg.y));
}
configure_radio_tx();
@@ -836,11 +815,12 @@ void BattleshipView::process_shot(uint8_t x, uint8_t y) {
if (!ship.placed) continue;
bool hit_this_ship = false;
for (uint8_t i = 0; i < ship.size(); i++) {
uint8_t check_x = ship.horizontal ? ship.x + i : ship.x;
uint8_t check_y = ship.horizontal ? ship.y : ship.y + i;
if (check_x == x && check_y == y) {
uint8_t dx = ship.horizontal ? 1 : 0;
uint8_t dy = ship.horizontal ? 0 : 1;
for (uint8_t i = 0; i < ship.size(); i++) {
if ((ship.x + i * dx) == x && (ship.y + i * dy) == y) {
hit_this_ship = true;
ship.hits++;
break;
@@ -852,9 +832,7 @@ void BattleshipView::process_shot(uint8_t x, uint8_t y) {
ships_remaining--;
for (uint8_t i = 0; i < ship.size(); i++) {
uint8_t sunk_x = ship.horizontal ? ship.x + i : ship.x;
uint8_t sunk_y = ship.horizontal ? ship.y : ship.y + i;
my_grid[sunk_y][sunk_x] = CellState::SUNK;
my_grid[ship.y + (i * dy)][ship.x + (i * dx)] = CellState::SUNK;
}
break;
}
@@ -887,7 +865,12 @@ void BattleshipView::process_shot(uint8_t x, uint8_t y) {
}
void BattleshipView::update_score() {
current_score = "W:" + to_string_dec_uint(wins) + " L:" + to_string_dec_uint(losses);
current_score.clear();
current_score.reserve(16);
current_score.append("W:");
current_score.append(to_string_dec_uint(wins));
current_score.append(" L:");
current_score.append(to_string_dec_uint(losses));
}
bool BattleshipView::on_touch(const TouchEvent event) {
@@ -980,3 +963,4 @@ bool BattleshipView::on_key(const KeyEvent key) {
}
} // namespace ui::external_app::battleship
#pragma GCC pop_options
@@ -9,6 +9,11 @@
#ifndef __UI_BATTLESHIP_H__
#define __UI_BATTLESHIP_H__
#include "portapack_shared_memory.hpp"
#include "utility.hpp"
#include "modems.hpp"
#include "bch_code.hpp"
#include "ui.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
+1 -1
View File
@@ -43,7 +43,7 @@ __attribute__((section(".external_app.app_blackjack.application_information"), u
0x80, 0x01, // .......##.......
0x00, 0x00, // ................
},
ui::Color::red().v, // Red color for diamonds
ui::Color::green().v, // Red color for diamonds
app_location_t::GAMES,
-1,
+1 -1
View File
@@ -24,7 +24,7 @@ __attribute__((section(".external_app.app_cvs_spam.application_information"), us
/*.app_name = */ "CVS Spam",
/*.bitmap_data = */ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81},
/*.icon_color = */ ui::Color::red().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_detector_rx.application_information"),
0x0C,
0xF0,
0x0F},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
+177 -46
View File
@@ -26,6 +26,7 @@
#include "ui_freqman.hpp"
#include "baseband_api.hpp"
#include "file.hpp"
#include "file_path.hpp"
#include "oversample.hpp"
#include "ui_font_fixed_8x16.hpp"
@@ -35,36 +36,112 @@ using portapack::memory::map::backup_ram;
namespace ui::external_app::detector_rx {
// Function to map the value from one range to another
int32_t DetectorRxView::map(int32_t value, int32_t fromLow, int32_t fromHigh, int32_t toLow, int32_t toHigh) {
return toLow + (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow);
}
void DetectorRxView::focus() {
field_lna.focus();
button_index.focus();
}
DetectorRxView::~DetectorRxView() {
// reset performance counters request to default
shared_memory.request_m4_performance_counter = 0;
receiver_model.disable();
audio::output::stop();
baseband::shutdown();
}
void DetectorRxView::on_timer() {
freq_index++;
if (freq_mode == 0 && freq_index >= tetra_uplink_monitoring_frequencies_hz.size()) freq_index = 0; // TETRA UP
if (freq_mode == 1 && freq_index >= lora_monitoring_frequencies_hz.size()) freq_index = 0; // Lora
if (freq_mode == 2 && freq_index >= remotes_monitoring_frequencies_hz.size()) freq_index = 0; // Remotes
std::string DetectorRxView::format_freq_mhz(int64_t freq_hz) {
int64_t mhz = freq_hz / 1000000;
int64_t khz_frac = (freq_hz % 1000000) / 1000;
return "< " + to_string_dec_uint(mhz) + "." + to_string_dec_uint(khz_frac, 3, '0') + " MHz >";
}
if (freq_mode == 2)
freq_ = remotes_monitoring_frequencies_hz[freq_index];
else if (freq_mode == 1)
freq_ = lora_monitoring_frequencies_hz[freq_index];
else
freq_ = tetra_uplink_monitoring_frequencies_hz[freq_index];
receiver_model.set_target_frequency(freq_);
void DetectorRxView::load_freqman() {
freqman_load_options options{};
options.load_freqs = true;
options.load_ranges = true;
options.load_hamradios = false;
options.load_repeaters = false;
if (!load_freqman_file(freq_file_stem, frequency_list, options) || frequency_list.empty()) {
button_file.set_text("No file!");
button_index.set_text("");
text_entry_desc.set("");
button_freq.set_text("");
frequency_list.clear();
return;
}
current_index = 0;
init_current_entry();
button_file.set_text(freq_file_stem);
}
void DetectorRxView::init_current_entry() {
if (frequency_list.empty()) return;
auto& entry = *frequency_list[current_index];
if (entry.type == freqman_type::Range) {
minfreq = entry.frequency_a;
maxfreq = entry.frequency_b;
current_freq = minfreq;
current_step = is_valid(entry.step) ? freqman_entry_get_step_value(entry.step) : DETECTOR_BW;
} else {
current_freq = entry.frequency_a;
minfreq = current_freq;
maxfreq = current_freq;
current_step = DETECTOR_BW;
}
update_entry_display();
update_freq_display();
receiver_model.set_target_frequency(current_freq);
}
void DetectorRxView::update_entry_display() {
if (frequency_list.empty()) return;
auto& entry = *frequency_list[current_index];
button_index.set_text(
to_string_dec_uint(current_index + 1) + "/" +
to_string_dec_uint(frequency_list.size()));
text_entry_desc.set(entry.description);
}
void DetectorRxView::update_freq_display() {
if (auto_scan && (minfreq != maxfreq)) {
if (last_update_was_auto_range_type != 1) {
button_freq.set_text("RANGE SCAN...");
last_update_was_auto_range_type = 1;
}
} else {
button_freq.set_text(format_freq_mhz(current_freq));
last_update_was_auto_range_type = 0;
}
}
void DetectorRxView::on_timer() {
if (frequency_list.empty() || !auto_scan) return;
auto& entry = *frequency_list[current_index];
if (entry.type == freqman_type::Range) {
current_freq += current_step;
if (current_freq > maxfreq) {
if (auto_advance) {
current_index = (current_index + 1) % frequency_list.size();
init_current_entry();
return;
}
current_freq = minfreq;
}
receiver_model.set_target_frequency(current_freq);
update_freq_display();
} else if (auto_advance) {
// Single frequency: advance to next entry
current_index = (current_index + 1) % frequency_list.size();
init_current_entry();
}
}
DetectorRxView::DetectorRxView(NavigationView& nav)
@@ -75,21 +152,22 @@ DetectorRxView::DetectorRxView(NavigationView& nav)
&field_vga,
&field_rf_amp,
&field_volume,
&text_frequency,
&freq_stats_rssi,
&freq_stats_db,
&button_file,
&button_index,
&text_entry_desc,
&text_beep_squelch,
&field_beep_squelch,
&freq_stats_db,
&freq_stats_rssi,
&button_freq,
&button_auto_scan,
&button_auto_advance,
&rssi,
&rssi_graph,
&field_mode,
});
// activate vertical bar mode
rssi.set_vertical_rssi(true);
freq_ = receiver_model.target_frequency();
field_beep_squelch.set_value(beep_squelch);
field_beep_squelch.on_change = [this](int32_t v) {
beep_squelch = v;
@@ -97,29 +175,85 @@ DetectorRxView::DetectorRxView(NavigationView& nav)
rssi_graph.set_nb_columns(256);
// FILE button opens file picker
button_file.on_select = [this](Button&) {
auto open_view = nav_.push<FileLoadView>(".TXT");
open_view->push_dir(freqman_dir);
open_view->on_changed = [this](std::filesystem::path new_file_path) {
if (new_file_path.native().find((u"/" / freqman_dir).native()) != 0) {
button_file.set_text("Invalid file");
return;
}
freq_file_stem = new_file_path.stem().string();
load_freqman();
};
};
// Index encoder: rotate to change entry, click does nothing
button_index.on_change = [this]() {
if (frequency_list.empty()) return;
int32_t delta = button_index.get_encoder_delta();
button_index.set_encoder_delta(0);
if (delta == 0) return;
// Use signed arithmetic for index wraparound to avoid unsigned promotion issues.
const int32_t list_size = static_cast<int32_t>(frequency_list.size());
int32_t idx = static_cast<int32_t>(current_index);
if (delta > 0) {
idx = (idx + 1) % list_size;
} else {
idx = (idx - 1 + list_size) % list_size;
}
current_index = static_cast<size_t>(idx);
init_current_entry();
};
// Frequency encoder: rotate to step within range
button_freq.on_change = [this]() {
if (frequency_list.empty()) return;
auto& entry = *frequency_list[current_index];
if (entry.type != freqman_type::Range) {
button_freq.set_encoder_delta(0);
return;
}
int32_t delta = button_freq.get_encoder_delta();
button_freq.set_encoder_delta(0);
if (delta == 0) return;
if (delta > 0) {
current_freq += current_step;
if (current_freq > maxfreq) current_freq = minfreq;
} else {
current_freq -= current_step;
if (current_freq < minfreq) current_freq = maxfreq;
}
receiver_model.set_target_frequency(current_freq);
update_freq_display();
};
// Auto-scan toggle
button_auto_scan.on_select = [this](Button&) {
auto_scan = !auto_scan;
button_auto_scan.set_text(auto_scan ? "AUTOSCAN" : "NO SCAN");
update_freq_display();
};
button_auto_scan.set_text(auto_scan ? "AUTOSCAN" : "NO SCAN");
// Auto-advance toggle
button_auto_advance.on_select = [this](Button&) {
auto_advance = !auto_advance;
button_auto_advance.set_text(auto_advance ? "AUTOADV" : "NO ADV");
};
button_auto_advance.set_text(auto_advance ? "AUTOADV" : "NO ADV");
change_mode();
rssi.set_peak(true, 3000);
// FILL STEP OPTIONS
freq_stats_rssi.set_style(Theme::getInstance()->bg_darkest);
freq_stats_db.set_style(Theme::getInstance()->bg_darkest);
field_mode.on_change = [this](size_t, int32_t value) {
freq_mode = value;
freq_index = 0;
switch (value) {
case 1: // Lora
text_frequency.set(" 433, 868, 915 Mhz");
break;
case 2: // Remotes
text_frequency.set(" 433, 315 Mhz");
break;
default:
case 0: // TETRA UP
text_frequency.set(" 380-390 Mhz");
break;
}
};
load_freqman();
}
void DetectorRxView::on_statistics_update(const ChannelStatistics& statistics) {
@@ -130,25 +264,23 @@ void DetectorRxView::on_statistics_update(const ChannelStatistics& statistics) {
rssi_graph.add_values(rssi.get_min(), rssi.get_avg(), rssi.get_max(), statistics.max_db);
// refresh db
if (last_max_db != statistics.max_db) {
last_max_db = statistics.max_db;
freq_stats_db.set("Power: " + to_string_dec_int(statistics.max_db) + " db");
rssi.set_db(statistics.max_db);
}
// refresh rssi
if (last_min_rssi != rssi_graph.get_graph_min() || last_avg_rssi != rssi_graph.get_graph_avg() || last_max_rssi != rssi_graph.get_graph_max()) {
last_min_rssi = rssi_graph.get_graph_min();
last_avg_rssi = rssi_graph.get_graph_avg();
last_max_rssi = rssi_graph.get_graph_max();
freq_stats_rssi.set("RSSI: " + to_string_dec_uint(last_min_rssi) + "/" + to_string_dec_uint(last_avg_rssi) + "/" + to_string_dec_uint(last_max_rssi));
freq_stats_rssi.set("RSSI:" + to_string_dec_uint(last_min_rssi) + "/" + to_string_dec_uint(last_avg_rssi) + "/" + to_string_dec_uint(last_max_rssi));
}
if (statistics.max_db > beep_squelch) {
baseband::request_audio_beep(map(statistics.max_db, -100, 20, 400, 2600), 24000, 150);
}
} /* on_statistic_updates */
}
size_t DetectorRxView::change_mode() {
audio::output::stop();
@@ -160,14 +292,13 @@ size_t DetectorRxView::change_mode() {
receiver_model.set_modulation(ReceiverModel::Mode::Capture);
baseband::set_sample_rate(DETECTOR_BW, get_oversample_rate(DETECTOR_BW));
// The radio needs to know the effective sampling rate.
auto actual_sampling_rate = get_actual_sample_rate(DETECTOR_BW);
receiver_model.set_sampling_rate(actual_sampling_rate);
receiver_model.set_baseband_bandwidth(filter_bandwidth_for_sampling_rate(actual_sampling_rate));
audio::set_rate(audio_sampling_rate);
audio::output::start();
receiver_model.set_headphone_volume(receiver_model.headphone_volume()); // WM8731 hack.
receiver_model.set_headphone_volume(receiver_model.headphone_volume());
receiver_model.enable();
+53 -72
View File
@@ -29,6 +29,7 @@
#include "audio.hpp"
#include "baseband_api.hpp"
#include "file.hpp"
#include "freqman.hpp"
#include "freqman_db.hpp"
#include "portapack_persistent_memory.hpp"
#include "radio_state.hpp"
@@ -60,20 +61,35 @@ class DetectorRxView : public View {
int32_t map(int32_t value, int32_t fromLow, int32_t fromHigh, int32_t toLow, int32_t toHigh);
size_t change_mode();
void on_statistics_update(const ChannelStatistics& statistics);
void set_display_freq(int64_t freq);
void on_timer();
void load_freqman();
void init_current_entry();
void update_entry_display();
void update_freq_display();
std::string format_freq_mhz(int64_t freq_hz);
freqman_db frequency_list{};
size_t current_index{0};
int64_t current_freq{0};
int64_t minfreq{0};
int64_t maxfreq{0};
int32_t current_step{DETECTOR_BW};
std::string freq_file_stem{"DETECTOR"};
bool auto_scan{true};
bool auto_advance{false};
uint8_t last_update_was_auto_range_type = -1;
uint8_t freq_index = 0;
rf::Frequency freq_ = {433920000};
int32_t beep_squelch = 0;
audio::Rate audio_sampling_rate = audio::Rate::Hz_48000;
uint8_t freq_mode = 0;
app_settings::SettingsManager settings_{
"rx_detector",
app_settings::Mode::RX,
{
{"beep_squelch"sv, &beep_squelch},
{"freq_file"sv, &freq_file_stem},
{"auto_scan"sv, &auto_scan},
{"auto_advance"sv, &auto_advance},
}};
Labels labels{
@@ -93,41 +109,55 @@ class DetectorRxView : public View {
AudioVolumeField field_volume{
{UI_POS_X_RIGHT(2), UI_POS_Y(0)}};
OptionsField field_mode{
{UI_POS_X(0), UI_POS_Y(1)},
9,
{
{"TETRA UP", 0},
{"Lora", 1},
{"Remotes", 2},
}};
// Row 1: filename + auto advance
Button button_file{
{UI_POS_X(0), UI_POS_Y(1), UI_POS_WIDTH(20), UI_POS_DEFAULT_HEIGHT},
""};
Text text_frequency{
{UI_POS_X_RIGHT(20), UI_POS_Y(1), UI_POS_WIDTH(20), UI_POS_DEFAULT_HEIGHT},
Button button_auto_advance{
{UI_POS_X_RIGHT(9), UI_POS_Y(1), UI_POS_WIDTH(9), UI_POS_DEFAULT_HEIGHT},
"NO ADV"};
// Row 2: index encoder + description + auto scan
ButtonWithEncoder button_index{
{UI_POS_X(0), UI_POS_Y(2), UI_POS_WIDTH(4), UI_POS_DEFAULT_HEIGHT},
""};
Text text_entry_desc{
{UI_POS_X(4), UI_POS_Y(2), UI_POS_WIDTH(17), UI_POS_DEFAULT_HEIGHT},
""};
Button button_auto_scan{
{UI_POS_X_RIGHT(9), UI_POS_Y(2), UI_POS_WIDTH(9), UI_POS_DEFAULT_HEIGHT},
"AUTO SCAN"};
// Row 3: frequency encoder + bip level
ButtonWithEncoder button_freq{
{UI_POS_X(0), UI_POS_Y(3), UI_POS_WIDTH(20), UI_POS_DEFAULT_HEIGHT},
""};
Text text_beep_squelch{
{UI_POS_X_RIGHT(9), UI_POS_Y(2), UI_POS_WIDTH(4), UI_POS_DEFAULT_HEIGHT},
{UI_POS_X_RIGHT(9), UI_POS_Y(3), UI_POS_WIDTH(4), UI_POS_DEFAULT_HEIGHT},
"Bip>"};
NumberField field_beep_squelch{
{UI_POS_X_RIGHT(5), UI_POS_Y(2)},
{UI_POS_X_RIGHT(5), UI_POS_Y(3)},
4,
{-100, 20},
1,
' ',
};
// RSSI: XX/XX/XXX
Text freq_stats_rssi{
{UI_POS_X(0), UI_POS_Y(2), UI_POS_WIDTH(15), UI_POS_DEFAULT_HEIGHT},
};
// Power: -XXX db
// Row 4: Power + RSSI on same line
Text freq_stats_db{
{UI_POS_X(0), UI_POS_Y(3), UI_POS_WIDTH(15), UI_POS_DEFAULT_HEIGHT},
{UI_POS_X(0), UI_POS_Y(4), UI_POS_WIDTH(15), UI_POS_DEFAULT_HEIGHT},
};
Text freq_stats_rssi{
{UI_POS_X(15), UI_POS_Y(4), UI_POS_WIDTH(15), UI_POS_DEFAULT_HEIGHT},
};
// Row 5+: RSSI graph + vertical bar
RSSIGraph rssi_graph{
{UI_POS_X(0), UI_POS_Y(5), UI_POS_WIDTH_REMAINING(5), UI_POS_HEIGHT_REMAINING(6)},
};
@@ -147,55 +177,6 @@ class DetectorRxView : public View {
[this](const Message* const) {
this->on_timer();
}};
const std::vector<uint32_t> remotes_monitoring_frequencies_hz = {
// Around 315 MHz (common for older remotes, key fobs in some regions)
// Window centered on 315 MHz, covers 314.625 - 315.375 MHz
315000000,
// Around 433.92 MHz (very common for remotes, sensors, key fobs globally)
// Window centered on 433.92 MHz, covers 433.545 - 434.295 MHz
433920000,
};
const std::vector<uint32_t> lora_monitoring_frequencies_hz = {
// EU433 Band (Europe, typically 433.05 MHz to 434.79 MHz)
// Scanning the approximate range 433.0 MHz to 434.8 MHz with 750kHz steps
433375000, // Covers 433.000 - 433.750 MHz
434125000, // Covers 433.750 - 434.500 MHz (includes 433.92 MHz)
434875000, // Covers 434.500 - 435.250 MHz (covers up to 434.79 MHz)
// EU868 Band (Europe, typically 863 MHz to 870 MHz, specific channels around 868 MHz)
// Targeting common LoRaWAN channel groups (approx 867.0 - 868.6 MHz) with 750kHz steps
867375000, // Covers 867.000 - 867.750 MHz
868125000, // Covers 867.750 - 868.500 MHz
868875000, // Covers 868.500 - 869.250 MHz (covers up to 868.6 MHz)
// US915 Band (North America, typically 902 MHz to 928 MHz, specific channels around 915 MHz)
// Providing a few sample windows around the 915 MHz area with 750kHz steps.
// This band is wide; a full scan would require many more frequencies.
914250000, // Covers 913.875 - 914.625 MHz
915000000, // Covers 914.625 - 915.375 MHz (Centered on 915 MHz)
915750000, // Covers 915.375 - 916.125 MHz
};
const std::vector<uint32_t> tetra_uplink_monitoring_frequencies_hz = {
// Band starts at 380,000,000 Hz, ends at 390,000,000 Hz.
// First center: 380,000,000 + 375,000 = 380,375,000 Hz
// Last center: 380,375,000 + 13 * 750,000 = 390,125,000 Hz (14 frequencies total for this band)
380375000, // Covers 380.000 - 380.750 MHz
381125000, // Covers 380.750 - 381.500 MHz
381875000, // Covers 381.500 - 382.250 MHz
382625000, // Covers 382.250 - 383.000 MHz
383375000, // Covers 383.000 - 383.750 MHz
384125000, // Covers 383.750 - 384.500 MHz
384875000, // Covers 384.500 - 385.250 MHz
385625000, // Covers 385.250 - 386.000 MHz
386375000, // Covers 386.000 - 386.750 MHz
387125000, // Covers 386.750 - 387.500 MHz
387875000, // Covers 387.500 - 388.250 MHz
388625000, // Covers 388.250 - 389.000 MHz
389375000, // Covers 389.000 - 389.750 MHz
390125000, // Covers 389.750 - 390.500 MHz
};
};
} // namespace ui::external_app::detector_rx
+1 -1
View File
@@ -58,7 +58,7 @@ __attribute__((section(".external_app.app_doom.application_information"), used))
0x00,
0x00,
},
ui::Color::red().v,
ui::Color::green().v,
app_location_t::GAMES,
-1,
{0, 0, 0, 0},
+59
View File
@@ -0,0 +1,59 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "beacon.hpp"
#include <cstdio>
#include "string_format.hpp"
// Some but not all methods of beacon class have been externalized in .cpp file
// This has been done to try and optimize application size by preventing the compiler to inline methods
namespace ui::external_app::epirb_rx {
size_t Beacon::formatSummary(char* buffer, bool with_time) {
size_t result = 0;
if (with_time) {
result += formatTime(buffer);
buffer[result++] = '-';
}
result += sprintf((buffer + result), "%4s-%5s-", shortId().c_str(), getType());
if (location.isUnknown()) {
result += sprintf((buffer + result), " ");
} else {
result += location.toString((buffer + result), Location::LocationFormat::MAIDENHEAD_LOCATOR);
}
result += sprintf((buffer + result), "[%s%s%s]", isFrameValid() ? (bch1Corrected || bch2Corrected) ? STR_COLOR_YELLOW : STR_COLOR_GREEN : STR_COLOR_RED, getSatus().c_str(), STR_COLOR_WHITE);
return result;
}
bool Beacon::isFrameValid() {
return isBch1Valid() && ((!hasBch2) || isBch2Valid()) && (!isEmpty);
}
std::string Beacon::shortId() {
std::string result = std::string(hexId);
return (result.size() >= 4) ? result.substr(0, 4) : result;
}
size_t Beacon::formatTime(char* buffer) {
return sprintf(buffer, "%02d:%02d:%02d", date.hour(), date.minute(), date.second());
}
} // namespace ui::external_app::epirb_rx
+856
View File
@@ -0,0 +1,856 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __BEACON_RX_H__
#define __BEACON_RX_H__
#include "country.hpp"
#include "location.hpp"
#include "rtc_time.hpp"
#include "resources.hpp"
namespace ui::external_app::epirb_rx {
// Size for beacon frame buffer
#define BEACON_DATA_SIZE 18 // Max 144 bits => 18 bytes
// Constants for BCH control code calculation
#define BCH_21_POLYNOMIAL 0b1001101101100111100011UL
#define BCH_21_POLY_LENGTH 22
#define BCH_12_POLYNOMIAL 0b1010100111001UL
#define BCH_12_POLY_LENGTH 13
// See content of sdcard/EPIRB/RES/BEACON.RES
#define ADDITIONAL_DATA_RESOURCE_START 25
#define LONG_ADDITIONAL_DATA_RESOURCE_START 33
#define EMERGENCY_RESOURCE_START 39
#define EMERGENCY_OTHER_RESOURCE_START 49
#define AUX_DEVICE_RESOURCE_START 53
/**
* This is the main class for beaon handling
*/
class Beacon {
public:
// Real beacon or test beacon ?
enum class FrameMode { NORMAL,
SELF_TEST,
UNKNOWN };
// Type of main location device
enum class MainLocatingDevice { UNDEFINED,
INTERNAL_NAV,
EXTERNAL_NAV };
// Type of aux location device
enum class AuxLocatingDevice { UNDEFINED,
NONE,
NONE_OR_OTHER,
OTHER,
MHZ121_5,
SART };
// Protcol type
enum class ProtocolType {
UNKNOWN,
USER,
STANDARD_LOCATION,
NATIONAL_LOCATION,
RLS_LOCATION,
ELT_DT_LOCATION,
SPARE
};
// Protocol
enum class Protocol {
USER_EPIRB_MARITIME,
USER_EPIRB_RADIO,
USER_ELT,
USER_SERIAL,
USER_TEST,
USER_ORB,
USER_NAT,
USER_2G,
STD_EPIRB,
STD_ELT_24,
STD_ELT_SERIAL,
STD_ELT_AIRCRAFT,
STD_EPIRB_SERIAL,
STD_PLB_SERIAL,
STD_SHIP,
STD_TEST,
NAT_ELT,
NAT_EPIRB,
NAT_PLB,
NAT_TEST,
RLS,
ELT_DT,
SPARE,
UNKNOWN
};
#define UNKNOWN_LABEL "Unk."
// Returns true for User protocol beacons
bool protocolIsUser() { return (protocolType == ProtocolType::USER); };
// Returns true for National Location protocol beacons
bool protocolIsNational() { return (protocolType == ProtocolType::NATIONAL_LOCATION); };
// Returns true for Standard Location protocol beacons
bool protocolIsStandard() { return (protocolType == ProtocolType::STANDARD_LOCATION); };
// Returns true for RLS location protocol beacons
bool protocolIsRls() { return (protocolType == ProtocolType::RLS_LOCATION); };
// Returns true for RLS or ELT Location protocol beacons
bool protocolIsRlsOrElt() { return (protocolType == ProtocolType::RLS_LOCATION || protocolType == ProtocolType::ELT_DT_LOCATION); };
// Returns true for unknown protocol beacons
bool protocolIsUnknown() { return (protocolType == ProtocolType::UNKNOWN); };
// Returns the protocol name
const char* getProtocolName() {
switch (protocolType) {
case ProtocolType::STANDARD_LOCATION:
return "Standard";
case ProtocolType::NATIONAL_LOCATION:
return "National";
case ProtocolType::RLS_LOCATION:
return "RLS";
case ProtocolType::ELT_DT_LOCATION:
return "ELT(DT)";
case ProtocolType::USER:
return longFrame ? "User Location" : "User";
case ProtocolType::SPARE:
return "Spare";
default:
return UNKNOWN_LABEL;
}
}
// Get protocol type for this beacon
ProtocolType getProtocolType() {
switch (protocol) {
case Protocol::USER_EPIRB_MARITIME:
case Protocol::USER_EPIRB_RADIO:
case Protocol::USER_ELT:
case Protocol::USER_SERIAL:
case Protocol::USER_TEST:
case Protocol::USER_ORB:
case Protocol::USER_NAT:
case Protocol::USER_2G:
return ProtocolType::USER;
case Protocol::STD_EPIRB:
case Protocol::STD_ELT_24:
case Protocol::STD_ELT_SERIAL:
case Protocol::STD_ELT_AIRCRAFT:
case Protocol::STD_PLB_SERIAL:
case Protocol::STD_SHIP:
case Protocol::STD_TEST:
return ProtocolType::STANDARD_LOCATION;
case Protocol::NAT_ELT:
case Protocol::NAT_EPIRB:
case Protocol::NAT_PLB:
case Protocol::NAT_TEST:
return ProtocolType::NATIONAL_LOCATION;
case Protocol::RLS:
return ProtocolType::RLS_LOCATION;
case Protocol::ELT_DT:
return ProtocolType::ELT_DT_LOCATION;
case Protocol::SPARE:
return ProtocolType::SPARE;
case Protocol::UNKNOWN:
default:
return ProtocolType::UNKNOWN;
}
}
// True for long frames, fals for short grames
bool longFrame{true};
// True if protocol flag is set for this frame
bool protocolFlag{false};
// Frame mode (Test or Real)
FrameMode frameMode{FrameMode::UNKNOWN};
// Main location device
MainLocatingDevice mainLocatingDevice{MainLocatingDevice::UNDEFINED};
// Axiliary location device
AuxLocatingDevice auxLocatingDevice{AuxLocatingDevice::UNDEFINED};
// Protocol code for this beacon
long protocolCode{0};
// Protocol of this beacon
Protocol protocol{Protocol::UNKNOWN};
// Protocol type of this beacon
ProtocolType protocolType{ProtocolType::UNKNOWN};
// Country of this beacon
Country country{};
// Frame data
uint8_t frame[BEACON_DATA_SIZE];
// Location of this beacon
Location location{};
// HexId of this beacon
uint64_t identifier{0};
// Date of reception of this beacon
rtc::RTC date{};
// Trus if this beacon has additional data
bool hasAdditionalData{false};
// The additional data tring
char additionalData[48]{0};
// True if this beacon has a serial number
bool hasSerialNumber{false};
// The serial number string
char serialNumber[32]{0};
// Beacon's Hex ID string
char hexId[32]{0};
// BCH1 code value
uint32_t bch1{};
// BCH1 calculated value
uint32_t computedBch1{};
// True if data has been corrected to match BCH1 code
bool bch1Corrected{false};
// True if this beacon has a BCH2 correction code
bool hasBch2{false};
// BCH2 code value
uint32_t bch2{};
// BCH2 calculated value
uint32_t computedBch2{};
// True if data has been corrected to match BCH2 code
bool bch2Corrected{false};
// True if this beacon is empty (not initialized)
bool isEmpty{true};
// True if thsi beacon contains emergency data
bool hasEmergency{false};
// True if emenrgency data is automatic for this beacon
bool isAutoamticEmergency{false};
// True if this beacon is a Maritime beacon
bool isMaritime{false};
// Emergency type string
char emergencyType[32]{0};
/**
* Returns the requested bits in this beacon's frame
*/
uint64_t getBits(int startBit, int endBit) {
uint64_t result = 0;
startBit--;
int numBits = endBit - startBit;
const uint8_t* pData = &(frame[startBit / 8]);
uint8_t b = *pData;
int bitOffset = 7 - (startBit % 8);
for (int i = 0; i < numBits; ++i) {
result <<= 1;
result |= ((b >> bitOffset) & 0x01);
if (--bitOffset < 0) {
b = *(++pData);
bitOffset = 7;
}
}
return result;
}
/**
* Compute a BCH control code for the given bits and poly
*/
uint64_t computeBCH(int startBit, int endBit, unsigned long poly, int polyLength) {
int dataLength = endBit - startBit + 1;
int totalLength = dataLength + polyLength - 1;
uint64_t result = getBits(startBit, startBit + polyLength - 1);
for (int i = polyLength; i <= totalLength; i++) {
bool firstBit = result >> (polyLength - 1);
if (firstBit) result = result ^ poly;
if (i < totalLength) {
result = result << 1;
if (i < dataLength) result |= getBits(startBit + i, startBit + i);
}
}
return result;
}
/**
* Compute BCH1 code
*/
uint64_t computeBCH1() { return computeBCH(25, 85, BCH_21_POLYNOMIAL, BCH_21_POLY_LENGTH); }
/**
* Compute BCH2 code
*/
uint64_t computeBCH2() { return computeBCH(107, 132, BCH_12_POLYNOMIAL, BCH_12_POLY_LENGTH); }
/**
* Convert this frame's data to an hex string
*/
static size_t toHexString(char* buffer, uint8_t* frame, bool withSpace, int start, int end) {
size_t result = 0;
for (uint8_t i = start; i < end; i++) {
if (withSpace && i > start) buffer[result++] = ' ';
result += sprintf((buffer + result), "%02X", frame[i]);
}
buffer[result] = 0;
return result;
}
Beacon() {}
Beacon(const Beacon& other) = delete;
Beacon& operator=(const Beacon& other) = delete;
/**
* Set the data for this Beacon and parse it
*/
void setFrame(const uint8_t* frameBuffer) {
frameMode = FrameMode::UNKNOWN;
mainLocatingDevice = MainLocatingDevice::UNDEFINED;
auxLocatingDevice = AuxLocatingDevice::UNDEFINED;
protocolCode = 0;
protocol = Protocol::UNKNOWN;
protocolType = ProtocolType::UNKNOWN;
country.code = 0;
country.alphaCode[0] = 0;
country.shortName[0] = 0;
location.clear();
identifier = 0;
hasAdditionalData = false;
additionalData[0] = 0;
hasSerialNumber = false;
serialNumber[0] = 0;
hexId[0] = 0;
bch1 = 0;
computedBch1 = 0;
hasBch2 = false;
bch1Corrected = false;
bch2 = 0;
computedBch2 = 0;
bch2Corrected = false;
isEmpty = true;
hasEmergency = false;
isAutoamticEmergency = false;
isMaritime = false;
emergencyType[0] = 0;
std::memcpy(frame, (const void*)frameBuffer, BEACON_DATA_SIZE);
parseFrame();
}
/**
* Flip the specified bit in this beacon's data
*/
void flipBit(int bit) {
int byteIdx = (bit - 1) / 8;
int bitIdx = 7 - ((bit - 1) % 8);
frame[byteIdx] ^= (1 << bitIdx);
}
/**
* Single bit error correction to match BCH1 or BCH2 code
*/
void simpleCorrection(bool isBCH1) {
for (int i = (isBCH1 ? 25 : 107); i <= (isBCH1 ? 85 : 132); i++) {
flipBit(i);
if ((isBCH1 ? (computeBCH1() == bch1) : (computeBCH2() == bch2))) {
if (isBCH1) {
computedBch1 = bch1;
bch1Corrected = true;
} else {
computedBch2 = bch2;
bch2Corrected = true;
}
break;
}
flipBit(i); // Restore bit value
}
}
/**
* Return the string representation of this beacon's type
*/
const char* getType() {
if ((protocol == Protocol::USER_EPIRB_MARITIME) || (protocol == Protocol::USER_EPIRB_RADIO) || (protocol == Protocol::STD_EPIRB) || (protocol == Protocol::STD_EPIRB_SERIAL) || (protocol == Protocol::NAT_EPIRB)) return "EPIRB";
if ((protocol == Protocol::USER_ELT) || (protocol == Protocol::STD_ELT_24) || (protocol == Protocol::STD_ELT_SERIAL) || (protocol == Protocol::STD_ELT_AIRCRAFT) || (protocol == Protocol::NAT_ELT) || (protocol == Protocol::ELT_DT)) return "ELT";
if ((protocol == Protocol::STD_PLB_SERIAL) || (protocol == Protocol::NAT_PLB)) return "PLB";
if ((protocol == Protocol::USER_TEST) || (protocol == Protocol::STD_TEST) || (protocol == Protocol::NAT_TEST)) return "TEST";
if (protocol == Protocol::USER_SERIAL) return "SRIAL";
if (protocol == Protocol::USER_ORB) return "ORB";
if (protocol == Protocol::USER_NAT) return "NAT";
if (protocol == Protocol::USER_2G) return "2G";
if (protocol == Protocol::STD_SHIP) return "SHIP";
if (protocol == Protocol::RLS) return "RLS";
if (protocol == Protocol::SPARE) return "SPARE";
return UNKNOWN_LABEL;
}
/**
* Returns true if this beacon has a main location device
*/
bool hasMainLocatingDevice() { return (mainLocatingDevice != MainLocatingDevice::UNDEFINED); }
/**
* Returns this beacon's main location device string representation
*/
const char* getMainLocatingDeviceName() {
if (mainLocatingDevice == MainLocatingDevice::EXTERNAL_NAV) return "Exernal";
if (mainLocatingDevice == MainLocatingDevice::INTERNAL_NAV) return "Internal";
return UNKNOWN_LABEL;
}
/**
* Returns true if this beacon has a main location device
*/
bool hasAuxLocatingDevice() { return (auxLocatingDevice != AuxLocatingDevice::UNDEFINED); }
/**
* Returns true if this beacon has a main location device
*/
const char* getAuxLocatingDeviceName() {
return ResourceManager::get_beacon_resource(AUX_DEVICE_RESOURCE_START + ((int)auxLocatingDevice));
}
/**
* Set the serial number for this beacon
*/
void setSerialNumber(uint32_t serial) {
sprintf(serialNumber, "%ld (0x%08lX)", serial, serial);
}
/**
* Returns true if BCH1 code is valid
*/
bool isBch1Valid() { return (bch1 == computedBch1); }
/**
* Returns true if BCH2 code is valid
*/
bool isBch2Valid() { return (bch2 == computedBch2); }
/**
* Returns true if frame is valid
*/
bool isFrameValid();
/**
* Returns true if frame is orbito
*/
bool isOrbito() { return (protocol == Protocol::USER_ORB); }
/**
* Write the hex preresentation of this frame in the provided buffer
*/
size_t hexString(char* buffer, bool withHeader) {
return toHexString(buffer, frame, false, (withHeader ? 0 : 3), (longFrame ? 18 : 14));
}
/**
* Returns the short ID for this beacon
*/
std::string shortId();
/**
* Returns the string representation of the status of this frame
*/
std::string getSatus() {
if (isFrameValid())
return "OK";
else
return "KO";
}
/**
* Format this beacon's time
*/
size_t formatTime(char* buffer);
/**
* Format this beacon's summary
*/
size_t formatSummary(char* buffer, bool with_time);
private:
/* Baudot code matrix */
static constexpr char BAUDOT_CODE[64] = {' ', '5', ' ', '9', ' ', ' ', ' ', ' ', ' ', ' ', '4', ' ', '8', '0', ' ', ' ',
'3', ' ', ' ', ' ', ' ', '6', ' ', '/', '-', '2', ' ', ' ', '7', '1', ' ', ' ',
' ', 'T', ' ', 'O', ' ', 'H', 'N', 'M', ' ', 'L', 'R', 'G', 'I', 'P', 'C', 'V',
'E', 'Z', 'D', 'B', 'S', 'Y', 'F', 'X', 'A', 'W', 'J', ' ', 'U', 'Q', 'K', '\0'};
/**
* Parse this beacon's protocol
*/
void parseProtocol() {
protocolFlag = getBits(26, 26);
if (protocolFlag)
protocolCode = getBits(37, 39);
else
protocolCode = getBits(37, 40);
if (!longFrame || protocolFlag == 1) {
switch (protocolCode) {
case 0b000:
protocol = Protocol::USER_ORB;
break;
case 0b001:
protocol = Protocol::USER_ELT;
break;
case 0b010:
protocol = Protocol::USER_EPIRB_MARITIME;
isMaritime = true;
break;
case 0b011:
protocol = Protocol::USER_SERIAL;
break;
case 0b100:
protocol = Protocol::USER_NAT;
break;
case 0b101:
protocol = Protocol::USER_2G;
break;
case 0b110:
protocol = Protocol::USER_EPIRB_RADIO;
isMaritime = true;
break;
case 0b111:
protocol = Protocol::USER_TEST;
break;
default:
protocol = Protocol::UNKNOWN;
}
} else {
switch (protocolCode) {
case 0b0010:
protocol = Protocol::STD_EPIRB;
break;
case 0b0011:
protocol = Protocol::STD_ELT_24;
break;
case 0b0100:
protocol = Protocol::STD_ELT_SERIAL;
break;
case 0b0101:
protocol = Protocol::STD_ELT_AIRCRAFT;
break;
case 0b0110:
protocol = Protocol::STD_EPIRB_SERIAL;
break;
case 0b0111:
protocol = Protocol::STD_PLB_SERIAL;
break;
case 0b1000:
protocol = Protocol::NAT_ELT;
break;
case 0b1001:
protocol = Protocol::ELT_DT;
break;
case 0b1010:
protocol = Protocol::NAT_EPIRB;
break;
case 0b1011:
protocol = Protocol::NAT_PLB;
break;
case 0b1100:
protocol = Protocol::STD_SHIP;
break;
case 0b1101:
protocol = Protocol::RLS;
break;
case 0b1110:
protocol = Protocol::STD_TEST;
break;
case 0b1111:
protocol = Protocol::NAT_TEST;
break;
default:
protocol = Protocol::UNKNOWN;
}
}
}
/**
* Parse this beacon's additional data
*/
void parseAdditionalData() {
hasAdditionalData = false;
hasSerialNumber = false;
if (protocolFlag) {
if (protocolCode == 0b011) {
uint8_t serialUserProtocol = getBits(40, 42);
hasAdditionalData = true;
switch (serialUserProtocol) {
case 0b100:
case 0b010:
isMaritime = true;
// fallthrough
case 0b000:
case 0b001:
case 0b011:
case 0b110:
strcpy(additionalData, ResourceManager::get_beacon_resource(ADDITIONAL_DATA_RESOURCE_START + serialUserProtocol));
break;
default:
hasAdditionalData = false;
}
hasSerialNumber = true;
setSerialNumber((serialUserProtocol == 0b011) ? getBits(44, 67) : (serialUserProtocol == 0b001) ? getBits(62, 73)
: getBits(44, 63));
}
if (!longFrame) {
hasEmergency = getBits(107, 107);
if (hasEmergency) {
isAutoamticEmergency = getBits(108, 108);
if (isMaritime) {
uint8_t emmergency = getBits(109, 112);
switch (emmergency) {
case 0b0001:
case 0b0010:
case 0b0011:
case 0b0100:
case 0b0101:
case 0b0110:
case 0b0111:
case 0b1000:
strcpy(emergencyType, ResourceManager::get_beacon_resource(EMERGENCY_RESOURCE_START + emmergency));
break;
default:
strcpy(emergencyType, ResourceManager::get_beacon_resource(EMERGENCY_RESOURCE_START));
}
} else {
bool fire = getBits(109, 109);
bool med = getBits(110, 110);
bool disabled = getBits(111, 111);
char* emmergency_pointer = emergencyType;
if (fire) emmergency_pointer += sprintf(emmergency_pointer, "%s", ResourceManager::get_beacon_resource(EMERGENCY_OTHER_RESOURCE_START));
if (med) {
if (fire) emmergency_pointer += sprintf(emmergency_pointer, "%c", '+');
emmergency_pointer += sprintf(emmergency_pointer, "%s", ResourceManager::get_beacon_resource(EMERGENCY_OTHER_RESOURCE_START + 1));
}
if (disabled) {
if (fire || med) emmergency_pointer += sprintf(emmergency_pointer, "%c", '+');
sprintf(emmergency_pointer, "%s", ResourceManager::get_beacon_resource(EMERGENCY_OTHER_RESOURCE_START + 2));
}
}
}
}
} else if (longFrame) {
switch (protocolCode) {
case 0b0010:
hasSerialNumber = true;
setSerialNumber(getBits(61, 64));
break;
case 0b1100: {
hasAdditionalData = true;
uint32_t mmsi = getBits(41, 60);
sprintf(additionalData, ResourceManager::get_beacon_resource(LONG_ADDITIONAL_DATA_RESOURCE_START), mmsi, mmsi);
} break;
case 0b0011: {
hasAdditionalData = true;
hasSerialNumber = true;
setSerialNumber(getBits(41, 64));
strcpy(additionalData, ResourceManager::get_beacon_resource(LONG_ADDITIONAL_DATA_RESOURCE_START + 1));
} break;
case 0b0100:
case 0b0110:
case 0b0111: {
hasAdditionalData = true;
hasSerialNumber = true;
uint32_t csTaNumber = getBits(41, 50);
sprintf(additionalData, ResourceManager::get_beacon_resource(LONG_ADDITIONAL_DATA_RESOURCE_START + 2), csTaNumber);
setSerialNumber(getBits(51, 64));
} break;
case 0b0101: {
hasAdditionalData = true;
hasSerialNumber = true;
uint32_t data = getBits(41, 45);
char char1 = BAUDOT_CODE[data + 32];
data = getBits(46, 50);
char char2 = BAUDOT_CODE[data + 32];
data = getBits(51, 55);
char char3 = BAUDOT_CODE[data + 32];
sprintf(additionalData, ResourceManager::get_beacon_resource(LONG_ADDITIONAL_DATA_RESOURCE_START + 3), char1, char2, char3);
setSerialNumber(getBits(56, 64));
} break;
case 0b1000:
case 0b1010:
case 0b1011:
case 0b1111: {
hasSerialNumber = true;
hasAdditionalData = true;
setSerialNumber(getBits(41, 58));
uint32_t natNum = getBits(127, 132);
sprintf(additionalData, ResourceManager::get_beacon_resource(LONG_ADDITIONAL_DATA_RESOURCE_START + 4), natNum);
} break;
}
}
}
/**
* Parse this beacon's locating device
*/
void parseLocatingDevices() {
bool mainLoc;
if (protocolIsStandard() || protocolIsNational()) {
mainLoc = getBits(111, 111);
mainLocatingDevice = mainLoc ? MainLocatingDevice::INTERNAL_NAV : MainLocatingDevice::EXTERNAL_NAV;
} else if (protocolIsUser() || protocolIsRls()) {
mainLoc = getBits(107, 107);
mainLocatingDevice = mainLoc ? MainLocatingDevice::INTERNAL_NAV : MainLocatingDevice::EXTERNAL_NAV;
}
if (protocolIsStandard() || protocolIsNational()) {
auxLocatingDevice = getBits(112, 112) ? AuxLocatingDevice::MHZ121_5 : AuxLocatingDevice::NONE_OR_OTHER;
} else if (protocolIsRls()) {
auxLocatingDevice = getBits(108, 108) ? AuxLocatingDevice::MHZ121_5 : AuxLocatingDevice::NONE_OR_OTHER;
} else if (protocolIsUser() && protocolCode != 0b100) {
uint8_t aux = getBits(84, 85);
if (aux == 0b00)
auxLocatingDevice = AuxLocatingDevice::NONE;
else if (aux == 0b01)
auxLocatingDevice = AuxLocatingDevice::MHZ121_5;
else if (aux == 0b10)
auxLocatingDevice = AuxLocatingDevice::SART;
else
auxLocatingDevice = AuxLocatingDevice::OTHER;
}
}
/**
* Parse this beacon's frame data
*/
void parseFrame() {
long latofmin, latofsec, lonofmin, lonofsec;
bool latoffset, lonoffset;
longFrame = getBits(25, 25);
parseProtocol();
protocolType = getProtocolType();
CountryManager::get_country(getBits(27, 36), country);
if (frame[2] == 0xD0)
frameMode = FrameMode::SELF_TEST;
else if (frame[2] == 0x2F)
frameMode = FrameMode::NORMAL;
else
frameMode = FrameMode::UNKNOWN;
if (longFrame) {
if (protocolIsUser() && !isOrbito()) {
location.latitude.orientation = (frame[13] & 0x10) >> 4;
location.latitude.degrees = ((frame[13] & 0x0F) << 3 | (frame[14] & 0xE0) >> 5);
location.latitude.minutes = ((frame[14] & 0x1E) >> 1) * 4;
location.longitude.orientation = (frame[14] & 0x01);
location.longitude.degrees = (frame[15]);
location.longitude.minutes = ((frame[16] & 0xF0) >> 4) * 4;
} else if (protocolIsNational()) {
latoffset = (frame[14] & 0x80) >> 7;
location.latitude.orientation = (frame[7] & 0x20) >> 5;
location.latitude.degrees = ((frame[7] & 0x1F) << 2 | (frame[8] & 0xC0) >> 6);
location.latitude.minutes = ((frame[8] & 0x3E) >> 1) * 2;
latofmin = (frame[14] & 0x60) >> 5;
latofsec = ((frame[14] & 0x1E) >> 1) * 4;
location.latitude.apply_offset(latoffset, latofmin, latofsec);
lonoffset = (frame[14] & 0x01);
location.longitude.orientation = (frame[8] & 0x01);
location.longitude.degrees = (frame[9]);
location.longitude.minutes = ((frame[10] & 0xF8) >> 3) * 2;
lonofmin = (frame[15] & 0xC0) >> 6;
lonofsec = ((frame[15] & 0x3C) >> 2) * 4;
location.longitude.apply_offset(lonoffset, lonofmin, lonofsec);
} else if (protocolIsStandard()) {
latoffset = (frame[14] & 0x80) >> 7;
location.latitude.orientation = (frame[8] & 0x80) >> 7;
location.latitude.degrees = (frame[8] & 0x7F);
location.latitude.minutes = ((frame[9] & 0xC0) >> 6) * 15;
latofmin = (frame[14] & 0x7C) >> 2;
latofsec = ((frame[14] & 0x03) << 2 | (frame[15] & 0xC0) >> 6) * 4;
location.latitude.apply_offset(latoffset, latofmin, latofsec);
lonoffset = (frame[15] & 0x20) >> 5;
location.longitude.orientation = (frame[9] & 0x20) >> 5;
location.longitude.degrees = ((frame[9] & 0x1F) << 3 | (frame[10] & 0xE0) >> 5);
location.longitude.minutes = ((frame[10] & 0x18) >> 3) * 15;
lonofmin = (frame[15] & 0x1F);
lonofsec = ((frame[16] & 0xF0) >> 4) * 4;
location.longitude.apply_offset(lonoffset, lonofmin, lonofsec);
} else if (protocolIsRlsOrElt()) {
latoffset = (frame[14] & 0x20) >> 5;
location.latitude.orientation = (frame[8] & 0x20) >> 5;
location.latitude.degrees = ((frame[8] & 0x1F) << 2) | ((frame[9] & 0xC0) >> 6);
location.latitude.minutes = ((frame[9] & 0x20) >> 5) * 30;
latofmin = (frame[14] & 0x1E) >> 1;
latofsec = ((frame[14] & 0x01) << 3 | (frame[15] & 0xE0) >> 5) * 4;
location.latitude.apply_offset(latoffset, latofmin, latofsec);
lonoffset = (frame[15] & 0x10) >> 4;
location.longitude.orientation = (frame[9] & 0x10) >> 4;
location.longitude.degrees = ((frame[9] & 0x0F) << 4 | (frame[10] & 0xF0) >> 4);
location.longitude.minutes = ((frame[10] & 0x08) >> 3) * 30;
lonofmin = (frame[15] & 0x0F);
lonofsec = ((frame[16] & 0xF0) >> 4) * 4;
location.longitude.apply_offset(lonoffset, lonofmin, lonofsec);
}
}
parseAdditionalData();
parseLocatingDevices();
identifier = getBits(26, 85);
uint32_t hexIdHigh = (uint32_t)(identifier >> 32);
uint32_t hexIdLow = (uint32_t)identifier;
if (protocolIsStandard()) {
// default value of bits 65 to 74 = 0 111111111 / default value of bits 75 to 85 = 0 1111111111
hexIdLow &= 0b11111111'11100000'00000000'00000000;
hexIdLow |= 0b00000000'00001111'11111011'11111111;
} else if (protocolIsNational()) {
// default value of bits 59 to 71 = 0 1111111 00000 / default value of bits 72 to 85 = 0 11111111 00000
hexIdLow &= 0b11111000'00000000'00000000'00000000;
hexIdLow |= 0b00000011'11111000'00011111'11100000;
} else if (protocolIsRlsOrElt()) {
// default value of bits 67 to 75 = 0 11111111 / default value of bits 76 to 85 = 0 111111111
hexIdLow &= 0b11111111'11111000'00000000'00000000;
hexIdLow |= 0b00000000'00000011'11111101'11111111;
}
std::sprintf(hexId, "%07lX%08lX", hexIdHigh, hexIdLow);
if (isOrbito() && !longFrame) {
isEmpty = true;
for (size_t i = 3; i < BEACON_DATA_SIZE; i++) {
if (frame[i] != 0) {
isEmpty = false;
break;
}
}
} else
isEmpty = false;
bch1 = getBits(86, 106);
computedBch1 = computeBCH1();
// Try and correct single bit error on BCH1 (bits 25-85)
if (computedBch1 != bch1) {
simpleCorrection(true);
}
hasBch2 = longFrame && !isOrbito();
if (hasBch2) {
bch2 = getBits(133, 144);
computedBch2 = computeBCH2();
// Try and correct single bit error on BCH2 (bits 107 - 132)
if (computedBch2 != bch2) {
simpleCorrection(false);
}
}
static bool isCorrecting = false;
// If BCH1 or BCH2 has been corrected, we need to parse frame again to update beacon properties
if (!isCorrecting && (bch1Corrected || bch2Corrected)) {
// Prevent recursion
isCorrecting = true;
parseFrame();
isCorrecting = false;
}
}
};
} // namespace ui::external_app::epirb_rx
#endif // __BEACON_RX_H__
+95
View File
@@ -0,0 +1,95 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "beacon_db.hpp"
namespace ui::external_app::epirb_rx {
/**
* Add a beacon to the database.
* @return the added beacon reference.
*/
Beacon& BeaconDB::add_beacon() {
Beacon& result = recent_beacons[recent_beacon_pos];
recent_beacon_pos = (recent_beacon_pos + 1) % BEACON_HISTORY_SIZE;
if (recent_beacon_pos == 0) recent_beacon_full = true;
return result;
}
/**
* Get the size of the beacon database
* @return the size of the beacon database
*/
size_t BeaconDB::size() {
return recent_beacon_full ? BEACON_HISTORY_SIZE : recent_beacon_pos;
}
/**
* Returns true if the database is empty
* @return true if the database is empty
*/
bool BeaconDB::empty() {
return (!recent_beacon_full && (recent_beacon_pos == 0));
}
/**
* Returns the beacon at the provided index
*/
Beacon& BeaconDB::get_beacon(size_t index) {
// Start from last beacon et go backward
int16_t pos = (int16_t)recent_beacon_pos - 1 - index;
while (pos < 0) pos += BEACON_HISTORY_SIZE;
return recent_beacons[pos % BEACON_HISTORY_SIZE];
}
/**
* Set currently selected beacon
* @param index the selected index
*/
void BeaconDB::set_current_beacon(size_t index) {
current_beacon_index = index;
}
/**
* Get currently selected index
* @return the currently selected index
*/
size_t BeaconDB::get_current_beacon_index() {
return current_beacon_index;
}
/**
* Get the currently selected beacon
* @return the currently selected beacon
*/
Beacon& BeaconDB::get_current_beacon() {
return get_beacon(current_beacon_index);
}
/**
* Clear beacon database
*/
void BeaconDB::clear() {
recent_beacon_pos = 0;
recent_beacon_full = false;
}
} // namespace ui::external_app::epirb_rx
+56
View File
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __BEACON_DB_H__
#define __BEACON_DB_H__
#include "beacon.hpp"
namespace ui::external_app::epirb_rx {
// Size of beacon database calculated to match the beacon list component size
#define BEACON_HISTORY_SIZE 13
class BeaconDB {
public:
Beacon& add_beacon();
Beacon& get_beacon(size_t index);
Beacon& get_current_beacon();
size_t get_current_beacon_index();
void set_current_beacon(size_t index);
size_t size();
bool empty();
void clear();
private:
// Actual beacon database array
Beacon recent_beacons[BEACON_HISTORY_SIZE];
// Position of the insertion pointer
int8_t recent_beacon_pos{0};
// Beacon selection handling
size_t current_beacon_index{0};
// True when database is full
bool recent_beacon_full{false};
};
} // namespace ui::external_app::epirb_rx
#endif /* __BEACON_DB_H__ */
+122
View File
@@ -0,0 +1,122 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __COUNTRY_RX_H__
#define __COUNTRY_RX_H__
#include "string_format.hpp"
#include "file_reader.hpp"
#include "file_path.hpp"
namespace ui::external_app::epirb_rx {
#define DISABLE_COUNTRY_CACHE
// Country struct
struct Country {
int16_t code;
char alphaCode[4]; // 3 chars + null
char shortName[11]; // 10 chars + null
};
class CountryManager {
public:
static void get_country(int code, Country& out) {
#ifndef DISABLE_COUNTRY_CACHE
// Check cache
for (int i = 0; i < cache_count; i++) {
if (cache[i].code == code) {
out = cache[i];
if (i > 0) { // Promotion
Country tmp = cache[i];
for (int j = i; j > 0; j--) cache[j] = cache[j - 1];
cache[0] = tmp;
}
return;
}
}
#endif
// Cache miss => load from file
if (load_from_file(code, out)) {
#ifndef DISABLE_COUNTRY_CACHE
// Insert in cache
int limit = (cache_count < 16) ? cache_count : 15;
for (int j = limit; j > 0; j--) cache[j] = cache[j - 1];
cache[0] = out;
if (cache_count < 16) cache_count++;
#endif
} else {
out.code = code;
out.alphaCode[0] = '\0';
out.shortName[0] = '\0';
}
}
private:
#ifndef DISABLE_COUNTRY_CACHE
static Country cache[16];
static int cache_count;
#endif
static bool load_from_file(int target_code, Country& out) {
FIL file;
if (f_open(&file, (epirb_dir / u"RES/COUNTRY.RES").tchar(), FA_READ) != FR_OK) return false;
TCHAR line[48];
bool found = false;
while (f_gets(line, sizeof(line) / sizeof(TCHAR), &file)) {
// Light parsing method
TCHAR* p = line;
// Parse CODE
int c = 0;
while (*p >= '0' && *p <= '9') c = c * 10 + (*p++ - '0');
if (c != target_code || *p != ':') continue;
p++; // Skip ':'
out.code = (int16_t)c;
// Parse ALPHA CODE (3 chars)
for (int i = 0; i < 3 && *p != ':'; i++) out.alphaCode[i] = (char)*p++;
out.alphaCode[3] = '\0';
if (*p != ':') continue;
p++; // Skip ':'
// Parse SHORT NAME
int i = 0;
while (i < static_cast<int>(sizeof(out.shortName) - 1) && *p != '\r' && *p != '\n' && *p != '\0') {
out.shortName[i++] = (char)*p++;
}
out.shortName[i] = '\0';
found = true;
break;
}
f_close(&file);
return found;
}
};
} // namespace ui::external_app::epirb_rx
#endif // __COUNTRY_RX_H__
+149
View File
@@ -0,0 +1,149 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "location.hpp"
#include <cstdio>
#include "string_format.hpp"
namespace ui::external_app::epirb_rx {
void Location::Angle::clear() {
degrees = 255;
minutes = 0;
seconds = 0;
orientation = false;
floatValue = 255;
}
float Location::Angle::getFloatValue() {
if (floatValue >= 255) {
floatValue = (float)degrees;
floatValue += ((float)minutes / 60.0f);
floatValue += ((float)seconds / 3600.0f);
if (orientation) {
floatValue = -floatValue;
}
}
return floatValue;
}
void Location::Angle::apply_offset(bool positive, long ofmin, long ofsec) {
if (positive) {
minutes += ofmin;
seconds += ofsec;
} else {
minutes -= ofmin;
if (minutes < 0) {
minutes += 60;
degrees -= 1;
}
seconds -= ofsec;
if (seconds < 0) {
seconds += 60;
minutes -= 1;
}
}
}
void Location::clear() {
latitude.clear();
longitude.clear();
}
bool Location::isUnknown() {
return (latitude.degrees >= 255 || longitude.degrees >= 255);
}
char Location::gps_letterize(int x) {
return (char)x + 65;
}
size_t Location::gps_compute_locator(char* buffer, float lat, float lon, int precision) {
size_t result = 0;
lon += 180.0f;
lat += 90.0f;
int A = lon / 20;
int B = lat / 10;
lon -= A * 20;
lat -= B * 10;
int C = lon / 2;
int D = lat / 1;
lon -= C * 2;
lat -= D * 1;
int E = lon / (5.0f / 60.0f);
int F = lat / (2.5f / 60.0f);
lon -= E * (5.0f / 60.0f);
lat -= F * (2.5f / 60.0f);
int G = lon / (5.0f / 600.0f);
int H = lat / (2.5f / 600.0f);
buffer[result++] = char('A' + A);
buffer[result++] = char('A' + B);
if (precision >= 4) {
buffer[result++] = char('0' + C);
buffer[result++] = char('0' + D);
}
if (precision >= 6) {
buffer[result++] = char('a' + E);
buffer[result++] = char('a' + F);
}
if (precision >= 8) {
buffer[result++] = char('0' + G);
buffer[result++] = char('0' + H);
}
buffer[result] = 0;
return result;
}
size_t Location::toString(char* buffer, LocationFormat format, int precision) {
if (isUnknown()) {
return sprintf(buffer, "%s", "GPS not synchronized");
}
switch (format) {
case LocationFormat::SEXAGESIMAL: {
return sprintf(buffer, "%ld\xB0%02ld'%02ld\"%c, %ld\xB0%02ld'%02ld\"%c", // 0xB0 is degree ° symbol in our 8x16 font
latitude.degrees, latitude.minutes, latitude.seconds, latitude.orientation ? 'S' : 'N',
longitude.degrees, longitude.minutes, longitude.seconds, longitude.orientation ? 'W' : 'E');
}
case LocationFormat::MAIDENHEAD_LOCATOR:
return gps_compute_locator(buffer, latitude.getFloatValue(), longitude.getFloatValue(), precision);
default:
case LocationFormat::DECIMAL:
return sprintf(buffer, "%s, %s", to_string_decimal(latitude.getFloatValue(), 5).c_str(), to_string_decimal(longitude.getFloatValue(), 5).c_str());
}
}
void Location::formatFloatLocation(char* buffer, const char* format) {
sprintf(buffer, format, to_string_decimal(latitude.getFloatValue(), 6).c_str(), to_string_decimal(longitude.getFloatValue(), 6).c_str());
}
} // namespace ui::external_app::epirb_rx
+76
View File
@@ -0,0 +1,76 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __LOCATION_RX_H__
#define __LOCATION_RX_H__
#include <cstddef>
namespace ui::external_app::epirb_rx {
class Location {
public:
class Angle {
public:
long degrees = 0;
long minutes = 0;
long seconds = 0;
bool orientation = false; // false = N/E, true = S/W
Angle() {}
Angle(long degrees)
: degrees(degrees) {}
void clear();
float getFloatValue();
// Apply an offset (minutes / seconds) with sign-based borrow into minutes/degrees.
// Out-of-line to keep parseFrame from inlining the same arithmetic 6 times.
void apply_offset(bool positive, long ofmin, long ofsec);
private:
float floatValue = 255.0f;
};
enum class LocationFormat { DECIMAL,
SEXAGESIMAL,
MAIDENHEAD_LOCATOR };
Angle latitude = Angle(127);
Angle longitude = Angle(255);
void clear();
bool isUnknown();
static char gps_letterize(int x);
// For code size optimization reasons, string manipulation is performed with char buffers
// with no char buffer size check. Caller methods take care of providing large enough buffers
static size_t gps_compute_locator(char* buffer, float lat, float lon, int precision = 6);
size_t toString(char* buffer, LocationFormat format, int precision = 6);
void formatFloatLocation(char* buffer, const char* format);
};
} // namespace ui::external_app::epirb_rx
#endif // __LOCATION_RX_H__
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_epirb_rx.application_information"), us
0x00,
0x00,
},
/*.icon_color = */ ui::Color::red().v,
/*.icon_color = */ ui::Color::green().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
+100
View File
@@ -0,0 +1,100 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __RESOUCES_H__
#define __RESOUCES_H__
#include <cstring>
#include <vector>
#include "file_reader.hpp"
#include "file_path.hpp"
namespace ui::external_app::epirb_rx {
#define UNKNOWN_LABEL "Unk."
extern std::vector<std::string> beacon_res;
extern std::vector<std::string> freq;
/**
* This class is used to load string resources from SD card.
* This is done mostly to reduce application size and keep it under the 32kb limit.
* It's also used to load frequency values, allowing users to customize frequency list by editing FREQ.TXT file on SD card.
*/
class ResourceManager {
public:
// Singleton getter
static ResourceManager* getInstance();
// Singleton instance
static ResourceManager* current;
// Used from standalone app, to prevent memleak
static void destroy();
// Get a string from BEACON.RES file
static const char* get_beacon_resource(uint8_t line) {
ResourceManager* rm = getInstance();
if (rm->beacon_res.empty()) {
load_file((epirb_dir / u"RES/BEACON.RES"), rm->beacon_res);
}
if (line < rm->beacon_res.size()) {
return rm->beacon_res[line].c_str();
}
return UNKNOWN_LABEL;
}
// Get frequency values
static const std::vector<std::string>& get_frequencies() {
ResourceManager* rm = getInstance();
if (rm->freq.empty()) {
load_file((epirb_dir / u"FREQ.TXT"), rm->freq);
}
return rm->freq;
}
private:
// BEACON.RES content
std::vector<std::string> beacon_res{};
// FREQ.TXT content
std::vector<std::string> freq{};
static void load_file(const std::filesystem::path& path, std::vector<std::string>& vect) {
FIL file;
if (f_open(&file, path.tchar(), FA_READ) == FR_OK) {
TCHAR line_buffer[32];
// Read the file line by line
while (f_gets(line_buffer, sizeof(line_buffer) / sizeof(TCHAR), &file)) {
std::string s;
for (int i = 0; line_buffer[i] != '\0' && line_buffer[i] != '\n' && line_buffer[i] != '\r'; i++) {
// Convert each TCHAR in char
s += (char)line_buffer[i];
}
vect.push_back(std::move(s));
}
f_close(&file);
}
if (vect.empty()) vect.push_back(UNKNOWN_LABEL);
}
};
} // namespace ui::external_app::epirb_rx
#endif // __RESOUCES_H__
+143
View File
@@ -0,0 +1,143 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui_beaconlist.hpp"
#include <algorithm>
namespace ui::external_app::epirb_rx {
BeaconUIList::BeaconUIList(Rect parent_rect)
: View{parent_rect} {
this->set_focusable(true);
}
void BeaconUIList::paint(Painter& painter) {
auto rect = screen_rect();
// Clear view
painter.fill_rectangle(rect, Theme::getInstance()->bg_darkest->background);
if (!db_ || (db_->empty())) {
return;
}
auto base_style = Theme::getInstance()->bg_darkest;
for (auto offset = 0u; offset < BEACON_HISTORY_SIZE; ++offset) {
// The whole frame needs to be cleared so every line 'slot'
// is redrawn even when `text` just left empty.
auto text = std::string{};
auto index = start_index_ + offset;
auto line_position = rect.location() + Point{0, 1 + (int)offset * char_height};
auto is_selected = offset == selected_index_;
auto style = base_style;
if (index < db_->size()) {
// Get beacon entry and format it's summary
auto& entry = db_->get_beacon(index);
char buffer[64];
entry.formatSummary(buffer, true);
text = std::string(buffer);
}
if (index == db_->get_current_beacon_index())
// If this is the currently displayed beacon change color
style = Theme::getInstance()->bg_medium;
// Draw entry line
painter.draw_string(
line_position, (is_selected ? style->invert() : *style), text);
}
// Draw a bounding rectangle when focused.
painter.draw_rectangle(rect, (has_focus() ? Theme::getInstance()->bg_darkest->foreground : Theme::getInstance()->bg_darkest->background));
}
void BeaconUIList::on_show() {
set_dirty();
}
bool BeaconUIList::on_key(const KeyEvent key) {
if (!db_ || db_->empty())
return false;
if (key == KeyEvent::Select && on_select) {
// Select this beacon
on_select(get_index());
set_dirty();
return true;
}
auto delta = 0;
// Change position in the list
if (key == KeyEvent::Up && get_index() > 0)
delta = -1;
else if (key == KeyEvent::Down && get_index() < db_->size() - 1)
delta = 1;
else
return false;
adjust_selected_index(delta);
set_dirty();
return true;
}
bool BeaconUIList::on_encoder(EncoderEvent delta) {
if (!db_ || db_->empty())
return false;
// Change position in the list according to encoder
adjust_selected_index(delta);
set_dirty();
return true;
}
size_t BeaconUIList::get_index() const {
return start_index_ + selected_index_;
}
void BeaconUIList::set_db(BeaconDB& db) {
db_ = &db;
start_index_ = 0;
selected_index_ = 0;
set_dirty();
}
void BeaconUIList::adjust_selected_index(int delta) {
int32_t new_index = selected_index_ + delta;
// The selection went off the top of the screen, move up.
if (new_index < 0) {
start_index_ = std::max<int32_t>(start_index_ + new_index, 0);
selected_index_ = 0;
}
// Selection is off the bottom of the screen, move down.
else if (new_index >= (int32_t)BEACON_HISTORY_SIZE) {
start_index_ = std::min<int32_t>(start_index_ + delta, db_->size() - BEACON_HISTORY_SIZE);
selected_index_ = BEACON_HISTORY_SIZE - 1;
}
// Otherwise, scroll within the screen, but not past the end.
else {
selected_index_ = std::min<int32_t>(new_index, db_->size() - 1);
}
}
} // namespace ui::external_app::epirb_rx
@@ -0,0 +1,61 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __UI_BEACONLIST_H__
#define __UI_BEACONLIST_H__
#include "ui.hpp"
#include "ui_painter.hpp"
#include "ui_widget.hpp"
#include "beacon_db.hpp"
namespace ui::external_app::epirb_rx {
/**
* Beacon list component
*/
class BeaconUIList : public View {
public:
std::function<void(size_t)> on_select{};
BeaconUIList(Rect parent_rect);
BeaconUIList(const BeaconUIList& other) = delete;
BeaconUIList& operator=(const BeaconUIList& other) = delete;
void paint(Painter& painter) override;
void on_show() override;
bool on_key(const KeyEvent key) override;
bool on_encoder(EncoderEvent delta) override;
size_t get_index() const;
void set_db(BeaconDB& db);
private:
void adjust_selected_index(int index);
BeaconDB* db_{nullptr};
size_t start_index_{0};
size_t selected_index_{0};
};
} // namespace ui::external_app::epirb_rx
#endif /*__UI_BEACONLIST_H__*/
File diff suppressed because it is too large Load Diff
+323 -296
View File
@@ -1,297 +1,324 @@
/*
* Copyright (C) 2024 EPIRB Decoder Implementation
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __UI_EPIRB_RX_H__
#define __UI_EPIRB_RX_H__
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "ui_geomap.hpp"
#include "event_m0.hpp"
#include "signal.hpp"
#include "message.hpp"
#include "log_file.hpp"
#include "baseband_packet.hpp"
/* #include <cstdint>
#include <cstddef>
#include <string>
#include <array> */
namespace ui::external_app::epirb_rx {
// EPIRB 406 MHz beacon types
enum class BeaconType : uint8_t {
OrbitingLocationBeacon = 0,
PersonalLocatorBeacon = 1,
EmergencyLocatorTransmitter = 2,
SerialELT = 3,
NationalELT = 4,
Other = 15
};
// EPIRB distress and emergency types
enum class EmergencyType : uint8_t {
Fire = 0,
Flooding = 1,
Collision = 2,
Grounding = 3,
Sinking = 4,
Disabled = 5,
Abandoning = 6,
Piracy = 7,
Man_Overboard = 8,
Other = 15
};
struct EPIRBLocation {
float latitude; // degrees, -90 to +90
float longitude; // degrees, -180 to +180
bool valid;
EPIRBLocation()
: latitude(0.0f), longitude(0.0f), valid(false) {}
EPIRBLocation(float lat, float lon)
: latitude(lat), longitude(lon), valid(true) {}
};
enum class PacketStatus : uint8_t {
Valid = 0,
Corrected = 1,
Error = 2
};
struct EPIRBBeacon {
uint32_t beacon_id;
BeaconType beacon_type;
EmergencyType emergency_type;
EPIRBLocation location;
uint32_t country_code;
std::string vessel_name;
rtc::RTC timestamp;
uint32_t sequence_number;
PacketStatus packet_status;
uint8_t error_count;
EPIRBBeacon()
: beacon_id(0), beacon_type(BeaconType::Other), emergency_type(EmergencyType::Other), location(), country_code(0), vessel_name(), timestamp(), sequence_number(0), packet_status(PacketStatus::Error), error_count(0) {}
};
class EPIRBDecoder {
public:
static EPIRBBeacon decode_packet(const baseband::Packet& packet);
private:
static EPIRBLocation decode_location(const std::array<uint8_t, 16>& data);
static BeaconType decode_beacon_type(uint8_t type_bits);
static EmergencyType decode_emergency_type(uint8_t emergency_bits);
static uint32_t decode_country_code(const std::array<uint8_t, 16>& data);
static std::string decode_vessel_name(const std::array<uint8_t, 16>& data);
// BCH error correction methods
static PacketStatus perform_bch_check(std::array<uint8_t, 16>& data, uint8_t& error_count);
static uint32_t calculate_bch_syndrome(const std::array<uint8_t, 16>& data);
static bool correct_single_error(std::array<uint8_t, 16>& data, uint32_t syndrome);
static uint8_t count_bit_errors(const std::array<uint8_t, 16>& original, const std::array<uint8_t, 16>& corrected);
};
class EPIRBLogger {
public:
Optional<File::Error> append(const std::filesystem::path& filename) {
return log_file.append(filename);
}
void on_packet(const EPIRBBeacon& beacon);
private:
LogFile log_file{};
};
// Forward declarations of formatting functions
std::string format_beacon_type(BeaconType type);
std::string format_emergency_type(EmergencyType type);
std::string format_packet_status(PacketStatus status);
ui::Color get_packet_status_color(PacketStatus status);
class EPIRBBeaconDetailView : public ui::View {
public:
std::function<void(void)> on_close{};
EPIRBBeaconDetailView(ui::NavigationView& nav);
EPIRBBeaconDetailView(const EPIRBBeaconDetailView&) = delete;
EPIRBBeaconDetailView& operator=(const EPIRBBeaconDetailView&) = delete;
void set_beacon(const EPIRBBeacon& beacon);
const EPIRBBeacon& beacon() const { return beacon_; }
void focus() override;
void paint(ui::Painter&) override;
ui::GeoMapView* get_geomap_view() { return geomap_view; }
private:
EPIRBBeacon beacon_{};
ui::Button button_done{
{125, 224, 96, 24},
"Done"};
ui::Button button_see_map{
{19, 224, 96, 24},
"See on map"};
ui::GeoMapView* geomap_view{nullptr};
ui::Rect draw_field(
ui::Painter& painter,
const ui::Rect& draw_rect,
const ui::Style& style,
const std::string& label,
const std::string& value);
};
class EPIRBAppView : public ui::View {
public:
EPIRBAppView(ui::NavigationView& nav);
~EPIRBAppView();
void set_parent_rect(const ui::Rect new_parent_rect) override;
void paint(ui::Painter&) override;
void focus() override;
std::string title() const override { return "EPIRB RX"; }
private:
app_settings::SettingsManager settings_{
"rx_epirb", app_settings::Mode::RX};
ui::NavigationView& nav_;
std::vector<EPIRBBeacon> recent_beacons{};
std::unique_ptr<EPIRBLogger> logger{};
EPIRBBeaconDetailView beacon_detail_view{nav_};
static constexpr auto header_height = 4 * 16;
ui::Text label_frequency{
{UI_POS_X(0), UI_POS_Y(0), 4 * 8, 1 * 16},
"Freq"};
ui::OptionsField options_frequency{
{5 * 8, UI_POS_Y(0)},
7,
{
{"406.028", 406028000},
{"406.025", 406025000},
{"406.037", 406037000},
{"433.025", 433025000},
{"144.875", 144875000},
}};
ui::RFAmpField field_rf_amp{
{13 * 8, UI_POS_Y(0)}};
ui::LNAGainField field_lna{
{15 * 8, UI_POS_Y(0)}};
ui::VGAGainField field_vga{
{18 * 8, UI_POS_Y(0)}};
ui::RSSI rssi{
{UI_POS_X(21), 0, UI_POS_WIDTH_REMAINING(24), 4}};
ui::Channel channel{
{UI_POS_X(21), 5, UI_POS_WIDTH_REMAINING(24), 4}};
ui::AudioVolumeField field_volume{
{screen_width - 2 * 8, UI_POS_Y(0)}};
// Status display
ui::Text label_status{
{UI_POS_X(0), 1 * 16, 15 * 8, 1 * 16},
"Listening..."};
ui::Text label_beacons_count{
{16 * 8, 1 * 16, 14 * 8, 1 * 16},
"Beacons: 0"};
ui::Text label_packet_stats{
{UI_POS_X(0), 3 * 16, 29 * 8, 1 * 16},
""};
// Latest beacon info display
ui::Text label_latest{
{UI_POS_X(0), 2 * 16, 8 * 8, 1 * 16},
"Latest:"};
ui::Text text_latest_info{
{8 * 8, 2 * 16, 22 * 8, 1 * 16},
""};
// Beacon list
ui::Console console{
{0, 4 * 16, 240, 152}};
ui::Button button_map{
{0, 224, 60, 24},
"Map"};
ui::Button button_clear{
{64, 224, 60, 24},
"Clear"};
ui::Button button_log{
{128, 224, 60, 24},
"Log"};
SignalToken signal_token_tick_second{};
uint32_t beacons_received = 0;
uint32_t packets_valid = 0;
uint32_t packets_corrected = 0;
uint32_t packets_error = 0;
MessageHandlerRegistration message_handler_packet{
Message::ID::EPIRBPacket,
[this](Message* const p) {
const auto message = static_cast<const EPIRBPacketMessage*>(p);
this->on_packet(message->packet);
}};
void on_packet(const baseband::Packet& packet);
void on_beacon_decoded(const EPIRBBeacon& beacon);
void on_show_map();
void on_clear_beacons();
void on_toggle_log();
void on_tick_second();
void update_display();
std::string format_beacon_summary(const EPIRBBeacon& beacon);
std::string format_location(const EPIRBLocation& location);
};
} // namespace ui::external_app::epirb_rx
/*
* Copyright (C) 2024 EPIRB Decoder Implementation
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __UI_EPIRB_RX_H__
#define __UI_EPIRB_RX_H__
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "ui_geomap.hpp"
// Specan is disable to keep application size below the 32k limit
// #define SPECAN
// Comment to disable timout reset on select and save approx 200 bytes of flash
#ifndef PRALINE
// Application does not fit on Praline with RESET_TIMER enabled
#define RESET_TIMER
#endif
// Comment to disable squelch control
#define SQUELCH
// Comment to disable beacon selection by encoder on detail tab
#define DETAIL_TAB_BEACON_SEL
// #define LOGGER
#ifdef SPECAN
#include "ui_spectrum.hpp"
#endif
#include "ui_tabview.hpp"
#include "ui_qrcode.hpp"
#include "event_m0.hpp"
#include "message.hpp"
#include "log_file.hpp"
#include "baseband_packet.hpp"
#include "audio.hpp"
#include "beacon.hpp"
#include "beacon_db.hpp"
#include "ui_beaconlist.hpp"
#include "resources.hpp"
namespace ui::external_app::epirb_rx {
/**
* Status of a packet
*/
enum class PacketStatus : uint8_t {
Valid = 0,
Corrected = 1,
Error = 2
};
// Position of tabs in tab view
#define EPIRB_TAB_POS_Y (UI_POS_Y(4) + 3 * 8)
// Height of tabs in tab view
#define EPIRB_TAB_HEIGHT (screen_height - EPIRB_TAB_POS_Y - UI_POS_HEIGHT(1))
#ifdef LOGGER
class EPIRBLogger {
public:
Optional<File::Error> append(const std::filesystem::path& filename) {
return log_file.append(filename);
}
void on_packet(Beacon& beacon);
private:
LogFile log_file{};
};
#endif
/**
* Dedicated TextArea component used to optimize application code size
*/
class TextArea : public Widget {
public:
TextArea(Rect parent_rect);
#ifdef RESET_TIMER
std::function<void(TextArea&)> on_select{};
bool on_key(const KeyEvent key) override;
#endif
void set_content(std::string_view value);
void paint(Painter& painter) override;
private:
std::string content{};
};
// Forward declaration
class EPIRBAppView;
/**
* View for beacon detail tab
*/
class EPIRBDetailView : public View {
public:
EPIRBDetailView(Rect parent_rect, EPIRBAppView& parent);
void set_beacon(Beacon& beacon);
#ifdef DETAIL_TAB_BEACON_SEL
bool on_encoder(EncoderEvent delta) override;
#endif
private:
TextArea text_beacon{{UI_POS_X(0), UI_POS_Y(0), UI_POS_MAXWIDTH, EPIRB_TAB_HEIGHT}};
EPIRBAppView& parent_app;
};
#define EPIRB_RX_DEFAULT_LATITUDE 43.604f
#define EPIRB_RX_DEFAULT_LONGITUDE 1.458f
/**
* View for beacon map tab
*/
class EPIRBMapView : public View {
public:
EPIRBMapView(Rect parent_rect);
void paint(Painter& painter) override;
void on_show() override;
void set_main_marker(const std::string& label, float lat, float lon);
void clear_markers();
void add_marker(GeoMarker& marker);
void hide_map(bool hide);
void repaint();
private:
GeoMap geomap{{0, 0, UI_POS_MAXWIDTH, EPIRB_TAB_HEIGHT}};
float lat_{EPIRB_RX_DEFAULT_LATITUDE};
float lon_{EPIRB_RX_DEFAULT_LONGITUDE};
bool map_hidden{true};
};
#define QR_WIDTH 126
#define QR_HEIGHT 127
/**
* Vieaw for Beacon QR tab
*/
class EPRIBQRView : public View {
public:
EPRIBQRView(Rect parent_rect);
EPRIBQRView(const EPRIBQRView&) = delete;
EPRIBQRView& operator=(const EPRIBQRView&) = delete;
void set_beacon(Beacon* beacon);
void update_qr();
void update_display();
private:
bool show_map{true};
Beacon* current_beacon{nullptr};
char qr_url[128];
OptionsField options_qr{
{UI_POS_X(5), UI_POS_Y(1)},
6,
{{"Map", 0},
{"Detail", 1}}};
QRCodeImage qr_code{
{UI_POS_MAXWIDTH - QR_WIDTH - UI_POS_X(1), UI_POS_Y(1), QR_WIDTH, QR_HEIGHT}};
TextArea text_data{{UI_POS_X(0), UI_POS_Y(1), UI_POS_MAXWIDTH, EPIRB_TAB_HEIGHT - UI_POS_Y(1)}};
};
#ifdef SPECAN
class EPIRBRxView : public spectrum::WaterfallView {
public:
EPIRBRxView(EPIRBAppView& parent, Rect parent_rect);
void on_show() override;
void on_hide() override;
private:
EPIRBAppView& app_view;
};
#endif
class EPIRBAppView final : public ui::View {
public:
EPIRBAppView(ui::NavigationView& nav);
~EPIRBAppView();
void focus() override;
void refresh();
// Message to configure rx baseband
EPIRBRXConfig epirb_rx_config_message{};
void send_config();
// Beacons database
BeaconDB beacon_db{};
// Update display when beacon selection changed0
void on_beacon_change();
std::string title() const override { return "EPIRB RX"; }
private:
uint8_t squelch{50};
// The delay between each frame
uint32_t countdown{50};
app_settings::SettingsManager settings_{
"rx_epirb",
app_settings::Mode::RX,
{
{"epirb_squelch"sv, &squelch},
{"countdown"sv, &countdown},
}};
ui::NavigationView& nav_;
#ifdef LOGGER
std::unique_ptr<EPIRBLogger> logger{};
#endif
OptionsField options_frequency{
{UI_POS_X(0), UI_POS_Y(0)},
7,
{}};
ui::RFAmpField field_rf_amp{
{UI_POS_X(8), UI_POS_Y(0)}};
ui::LNAGainField field_lna{
{UI_POS_X(10), UI_POS_Y(0)}};
ui::VGAGainField field_vga{
{UI_POS_X(13), UI_POS_Y(0)}};
ui::RSSI rssi{
{UI_POS_X(16), UI_POS_Y(0), UI_POS_WIDTH_REMAINING(22), 4}};
ui::Channel channel{
{UI_POS_X(16), UI_POS_Y(0) + 5, UI_POS_WIDTH_REMAINING(22), 4}};
// ui::Audio audio{
// {UI_POS_X(16), UI_POS_Y(0) + 10, UI_POS_WIDTH_REMAINING(22), 4}};
ui::AudioVolumeField field_volume{
{UI_POS_WIDTH_REMAINING(2), UI_POS_Y(0)}};
#ifdef SQUELCH
NumberField field_squelch{
{UI_POS_WIDTH_REMAINING(5), UI_POS_Y(0)},
2,
{0, 99},
1,
' '};
#endif
// Status display
TextArea text_status{{UI_POS_X(0), UI_POS_Y(1), UI_POS_MAXWIDTH, UI_POS_HEIGHT(3)}};
TextArea text_timeout{
{UI_POS_X(13), UI_POS_Y(1), UI_POS_WIDTH(3), UI_POS_HEIGHT(1)}};
SignalToken signal_token_tick_second{};
// Timeout string
int16_t timeout{0};
// Tab View
Rect view_rect = {0, EPIRB_TAB_POS_Y, UI_POS_MAXWIDTH, EPIRB_TAB_HEIGHT};
BeaconUIList view_list{view_rect};
EPIRBDetailView view_detail{view_rect, (*this)};
EPIRBMapView view_map{view_rect};
#ifdef SPECAN
EPIRBRxView view_rx{*this, view_rect};
#endif
EPRIBQRView view_qr{view_rect};
TabView tab_view{
{"List", Theme::getInstance()->fg_cyan->foreground, &view_list},
{"Detail", Theme::getInstance()->fg_green->foreground, &view_detail},
{"Map", Theme::getInstance()->fg_yellow->foreground, &view_map},
#ifdef SPECAN
{"RX", Theme::getInstance()->fg_orange->foreground, &view_rx},
#endif
{"QR", Theme::getInstance()->fg_orange->foreground, &view_qr}};
uint16_t beacons_received = 0;
uint16_t packets_valid = 0;
uint16_t packets_corrected = 0;
uint16_t packets_error = 0;
MessageHandlerRegistration message_handler_packet{
Message::ID::EPIRBPacket,
[this](Message* const p) { on_packet(p); }};
static void decode_packet(const baseband::Packet& packet, Beacon& beacon);
void on_packet(Message* const p);
void update_map();
void on_tick_second();
void update_display();
};
} // namespace ui::external_app::epirb_rx
#endif // __UI_EPIRB_RX_H__
+356
View File
@@ -0,0 +1,356 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __BEACON_H__
#define __BEACON_H__
#include "portapack.hpp"
#include "ui_epirb_tx.hpp"
#include "location.hpp"
namespace ui::external_app::epirb_tx {
/**
* Get bits frop the provided frame
* @param data the frame data
* @param startBit the start bit number (one based to match documentation)
* @param endBit the end bit number (one based to match documentation)
* @return the selected bits (max 64)
*/
static uint64_t get_bits(uint8_t* data, int startBit, int endBit) {
uint64_t result = 0;
// 0 bases bit count
startBit--;
int numBits = endBit - startBit;
// get a pointer to the starting byte...
const uint8_t* pData = &(data[startBit / 8]);
uint8_t b = *pData;
// calculate the starting bit within that byte...
int bitOffset = 7 - (startBit % 8);
// iterate for the desired number of bits...
for (int i = 0; i < numBits; ++i) {
// make room for the next bit...
result <<= 1;
// copy the bit...
result |= ((b >> bitOffset) & 0x01);
// reached the end of the current byte?
if (--bitOffset < 0) {
b = *(++pData); // go to the next byte...
bitOffset = 7; // restart at the first bit in that byte...
}
}
// all done...
return result;
}
/**
* Compute a BCH code
* @param frame the frame data
* @param startBit the bit to start BCH calculation
* @param endBit the bit to stop calculation
* @param poly the BCH polynome
* @param polyLength the BCH polynome length
* @return the BCH code
*/
static uint64_t compute_bch(uint8_t* frame, int startBit, int endBit, unsigned long poly, int polyLength) { // Length of data to be checked (not including the BCH code)
int dataLength = endBit - startBit + 1;
// Total lengh (including the BCH code that will be padded to zeros (BCH code length is polyLengh-1))
int totalLength = dataLength + polyLength - 1;
// Start with the first polyLength bits
uint64_t result = get_bits(frame, startBit, startBit + polyLength - 1);
for (int i = polyLength; i <= totalLength; i++) { // Iterate on each bit after the first polyLength batch
bool firstBit = result >> (polyLength - 1);
if (firstBit) { // We have a leading 1 => xor the result with the poly
result = result ^ poly;
}
if (i < totalLength) { // Move to next bit
result = result << 1;
if (i < dataLength) { // Append next bit
result |= get_bits(frame, startBit + i, startBit + i);
} // else : 0 padding after data length
}
}
return result;
}
// 21 bits BCH polynomial
#define BCH_21_POLYNOMIAL 0b1001101101100111100011UL
#define BCH_21_POLY_LENGTH 22
// 12 bits BCH polynomial
#define BCH_12_POLYNOMIAL 0b1010100111001UL
#define BCH_12_POLY_LENGTH 13
/**
* Combyte BCH1 code for the provided frame
*/
static uint64_t compute_bch1(uint8_t* frame) {
return compute_bch(frame, 25, 85, BCH_21_POLYNOMIAL, BCH_21_POLY_LENGTH);
}
/**
* Combyte BCH2 code for the provided frame
*/
static uint64_t compute_bch2(uint8_t* frame) {
return compute_bch(frame, 107, 132, BCH_12_POLYNOMIAL, BCH_12_POLY_LENGTH);
}
/**
* Set a bit in the provided frame
* @param buf the frame
* @param bit the position of the bit to set (0 based)
* @param v the bit value
*/
static void set_bit(uint8_t* buf, int bit, bool v) {
int byte = bit >> 3;
int off = 7 - (bit & 7);
if (v)
buf[byte] |= (1 << off);
else
buf[byte] &= ~(1 << off);
}
/**
* Push bits to the provided frame
* @param buf the frame
* @param pos the current frame possition (in/out, will be incremented during the opreration)
* @param v the bits to push (max 64)
* @param n the number of bits to push
*/
static void push_bits(uint8_t* buf, int& pos, uint64_t v, int n) {
for (int i = n - 1; i >= 0; i--)
set_bit(buf, pos++, (v >> i) & 1);
}
/**
* Convert a beacon to hex string representation
* @param frame the frame to convert
* @param start true for the first half of the frame, false for the second half
* @return the hex string representation of the specieid half of the frame
*/
std::string beacon_to_hex_string(const uint8_t* frame, bool start) {
static const char hex[] = "0123456789ABCDEF";
std::string out;
out.resize(18);
int offset = start ? 0 : 9;
for (int i = 0; i < 9; i++) {
uint8_t b = frame[offset + i];
out[i * 2] = hex[b >> 4];
out[i * 2 + 1] = hex[b & 0x0F];
}
return out;
}
/**
* Generate a beacon in the provided buffer
* @param frame the buffer to generate the frame in
* @param params the beacon parameters
* @return the size of the generated frame
*/
size_t generate_beacon(uint8_t* frame, const BeaconParams& params) {
// Clear the content of the frame
memset(frame, 0, 18);
int pos = 0;
uint32_t deg, min, sec;
// bit sync
for (int i = 0; i < 15; i++)
push_bits(frame, pos, 1, 1);
// frame sync
push_bits(frame, pos, params.is_test ? 0b011010000 : 0b000101111, 9);
// PDF-1 (Protexted Data field 1)
int pdf1_start = pos;
push_bits(frame, pos, 1, 1); // format flag (long)
bool is_user = (params.protocol == BeaconProtocol::USER);
bool is_standard = (params.protocol == BeaconProtocol::STANDARD);
push_bits(frame, pos, is_user, 1); // protocol flag
push_bits(frame, pos, params.country, 10); // country code
switch (params.type) {
case BeaconType::EPIRB:
if (is_user)
push_bits(frame, pos, 0b010, 3);
else if (is_standard)
push_bits(frame, pos, 0b0010, 4);
else
push_bits(frame, pos, 0b1010, 4);
break;
case BeaconType::PLB:
if (is_user)
push_bits(frame, pos, 0b011, 3);
else if (is_standard)
push_bits(frame, pos, 0b0111, 4);
else
push_bits(frame, pos, 0b1011, 4);
break;
default:
case BeaconType::ELT:
if (is_user)
push_bits(frame, pos, 0b001, 3);
else if (is_standard)
push_bits(frame, pos, 0b0011, 4);
else
push_bits(frame, pos, 0b1000, 4);
break;
}
// Fill the rest of PDF 1 with zeros
while (pos < pdf1_start + 61)
push_bits(frame, pos, 0, 1);
if (is_user) {
// User Location Protocol: no position in PDF1
if (params.type == BeaconType::PLB) {
// Set bits for PLB
set_bit(frame, 40 - 1, 1);
set_bit(frame, 41 - 1, 1);
set_bit(frame, 42 - 1, 0);
}
set_bit(frame, 85 - 1, params.has_121_5);
} else if (is_standard) {
// Standard Location Protocol
// North / south
set_bit(frame, 65 - 1, params.location.south);
// E / W
set_bit(frame, 75 - 1, params.location.west);
pos = 66 - 1;
// Latitude 1/4 degrees (9 bits)
deg = (params.location.lat_deg << 2) + (params.location.lat_min / 15);
push_bits(frame, pos, deg, 9);
pos = 76 - 1;
// Longitude 1/4 degrees (10 bits)
deg = (params.location.long_deg << 2) + (params.location.long_min / 15);
push_bits(frame, pos, deg, 10);
pos = pdf1_start + 61;
} else {
// National Location Protocol
// North / south
set_bit(frame, 59 - 1, params.location.south);
// E / W
set_bit(frame, 72 - 1, params.location.west);
pos = 60 - 1;
// Latitude degrees (7 bits)
push_bits(frame, pos, params.location.lat_deg, 7);
// Latitude min (5 bits, 2 min increment)
min = params.location.lat_min / 2;
push_bits(frame, pos, min, 5);
pos = 73 - 1;
// Longitude degrees (8 bits)
push_bits(frame, pos, params.location.long_deg, 8);
// Longiitude min (5 bits, 2 min increment)
min = params.location.long_min / 2;
push_bits(frame, pos, min, 5);
pos = pdf1_start + 61;
}
// Set BCH1
uint64_t bch1 = compute_bch1(frame);
push_bits(frame, pos, bch1, 21);
// PDF-2 (Protexted Data Field 2)
int pdf2_start = pos;
if (is_user) {
// User Location Protocol
push_bits(frame, pos, params.is_internal, 1);
// Latitude N/S
push_bits(frame, pos, params.location.south, 1);
// Latitude degrees (7 bits)
push_bits(frame, pos, params.location.lat_deg, 7);
// Latitude minutes (4 bits, 4 minutes precision)
min = params.location.lat_min / 4;
push_bits(frame, pos, min, 4);
// Longitude E/W
push_bits(frame, pos, params.location.west, 1);
// Longitude degrees (8 bits)
push_bits(frame, pos, params.location.long_deg, 8);
// Longitude minutes (4 bits, 4 minutes precision)
min = params.location.long_min / 4;
push_bits(frame, pos, min, 4);
} else if (is_standard) {
// Standard Location Protocol
push_bits(frame, pos, 0b1101, 4);
push_bits(frame, pos, params.is_internal, 1);
push_bits(frame, pos, params.has_121_5, 1);
// Latiitude
// +
push_bits(frame, pos, 1, 1);
// Min
min = params.location.lat_min % 15;
push_bits(frame, pos, min, 5);
// Sec (4 bits, 4 sec precision)
sec = params.location.lat_sec / 4;
push_bits(frame, pos, sec, 4);
// Longitude
// +
push_bits(frame, pos, 1, 1);
// Min
min = params.location.long_min % 15;
push_bits(frame, pos, min, 5);
// Sec (4 bits, 4 sec precision)
sec = params.location.long_sec / 4;
push_bits(frame, pos, sec, 4);
} else {
// National Location Protocol
push_bits(frame, pos, 0b1101, 4);
push_bits(frame, pos, params.is_internal, 1);
push_bits(frame, pos, params.has_121_5, 1);
// Lat
// +
push_bits(frame, pos, 1, 1);
// Min
push_bits(frame, pos, (params.location.lat_min % 2), 2);
// Sec (4 bits, 4 sec precision)
sec = params.location.lat_sec / 4;
push_bits(frame, pos, sec, 4);
// LLon
// +
push_bits(frame, pos, 1, 1);
// Min
push_bits(frame, pos, (params.location.long_min % 2), 2);
// Sec (4 bits, 4 sec precision)
sec = params.location.long_sec / 4;
push_bits(frame, pos, sec, 4);
}
while (pos < pdf2_start + 26)
push_bits(frame, pos, 0, 1);
// Compute BCH 2
uint64_t bch2 = compute_bch2(frame);
push_bits(frame, pos, bch2, 12);
return 18;
}
} // namespace ui::external_app::epirb_tx
#endif /*__BEACON_H__*/
+272
View File
@@ -0,0 +1,272 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __LOCATION_H__
#define __LOCATION_H__
#include "portapack.hpp"
#include "ui_epirb_tx.hpp"
#include <cmath>
#include <cstdio>
namespace ui::external_app::epirb_tx {
/**
* Convert decimal coordinates to sexagesimal coordinates
* @param value the decimal value
* @param negative output N(false)/S(true) or E(false)/W(true) value
* @param deg output degrees value
* @param min output minutes value
* @param sec output seconds value
*/
static void decimal_to_dms(float value, bool& negative, int16_t& deg, int8_t& min, int8_t& sec) {
negative = value < 0;
value = std::fabs(value);
deg = (int16_t)value;
float m = (value - deg) * 60.0f;
min = (int8_t)m;
float s = (m - min) * 60.0f;
sec = (int8_t)(s + 0.5f);
if (sec == 60) {
sec = 0;
min++;
}
if (min == 60) {
min = 0;
deg++;
}
}
/**
* Convert sexagesimal coordinates to decimal
* @param negative N(false)/S(true) or E(false)/W(true) value
* @param deg degrees value
* @param min minutes value
* @param sec seconds value
* @return value the decimal value
*/
static float dms_to_decimal(bool negative, int16_t deg, int8_t min, int8_t sec) {
float v = deg + min / 60.0f + sec / 3600.0f;
return negative ? -v : v;
}
/**
* Convert maidenhead locator to decima coordinates
* @param loc the locator
* @param lat output latitude
* @param lon output longitude
*/
static void maidenhead_to_decimal(const std::string& loc, float& lat, float& lon) {
static const float lon_step[] =
{
20.0f,
2.0f,
1.0f / 12.0f,
1.0f / 120.0f,
1.0f / 2880.0f};
static const float lat_step[] =
{
10.0f,
1.0f,
1.0f / 24.0f,
1.0f / 240.0f,
1.0f / 5760.0f};
lon = -180.0f;
lat = -90.0f;
int pairs = loc.size() / 2;
if (pairs > 5)
pairs = 5;
if (pairs > 0) {
for (int i = 0; i < pairs; i++) {
char c1 = loc[i * 2];
char c2 = loc[i * 2 + 1];
if (c1 >= 'a' && c1 <= 'z') c1 -= ('a' - 'A');
if (c2 >= 'a' && c2 <= 'z') c2 -= ('a' - 'A');
float lon_size = lon_step[i];
float lat_size = lat_step[i];
int v1, v2;
if (i % 2 == 0) // letters
{
v1 = c1 - 'A';
v2 = c2 - 'A';
} else // digits
{
v1 = c1 - '0';
v2 = c2 - '0';
}
lon += v1 * lon_size;
lat += v2 * lat_size;
}
// Cell center
lon += lon_step[pairs - 1] / 2.0f;
lat += lat_step[pairs - 1] / 2.0f;
}
}
/**
* Convert decimal coordinates to maidenhead locator
* @param lat the latitude
* @param lon the longitude
* @param precision (optional, defaults to 8) the number of charater for the maidenhead locator
* @return the locator
*/
static std::string decimal_to_maidenhead(float lat, float lon, int precision = 8) {
lon += 180.0f;
lat += 90.0f;
int A = lon / 20;
int B = lat / 10;
lon -= A * 20;
lat -= B * 10;
int C = lon / 2;
int D = lat / 1;
lon -= C * 2;
lat -= D * 1;
int E = lon / (5.0f / 60.0f);
int F = lat / (2.5f / 60.0f);
lon -= E * (5.0f / 60.0f);
lat -= F * (2.5f / 60.0f);
int G = lon / (5.0f / 600.0f);
int H = lat / (2.5f / 600.0f);
std::string locator;
locator += char('A' + A);
locator += char('A' + B);
if (precision >= 4) {
locator += char('0' + C);
locator += char('0' + D);
}
if (precision >= 6) {
locator += char('a' + E);
locator += char('a' + F);
}
if (precision >= 8) {
locator += char('0' + G);
locator += char('0' + H);
}
return locator;
}
/**
* Init the provided Location values from its locator
*/
void init_from_locator(Location& loc) {
maidenhead_to_decimal(loc.locator, loc.latitude, loc.longitude);
decimal_to_dms(loc.latitude,
loc.south,
loc.lat_deg,
loc.lat_min,
loc.lat_sec);
decimal_to_dms(loc.longitude,
loc.west,
loc.long_deg,
loc.long_min,
loc.long_sec);
}
/**
* Init the provided Location values from its decimal coordinates
*/
void init_from_decimal(Location& loc) {
decimal_to_dms(loc.latitude,
loc.south,
loc.lat_deg,
loc.lat_min,
loc.lat_sec);
decimal_to_dms(loc.longitude,
loc.west,
loc.long_deg,
loc.long_min,
loc.long_sec);
loc.locator = decimal_to_maidenhead(loc.latitude, loc.longitude);
}
/**
* Init the provided Location values from its sexagesimal coordinates
*/
void init_from_dms(Location& loc) {
loc.latitude = dms_to_decimal(
loc.south,
loc.lat_deg,
loc.lat_min,
loc.lat_sec);
loc.longitude = dms_to_decimal(
loc.west,
loc.long_deg,
loc.long_min,
loc.long_sec);
loc.locator = decimal_to_maidenhead(loc.latitude, loc.longitude);
}
/**
* Convert the provided Loaction to it's latitude string (format <xxx°yy'zz"N>)
*/
std::string to_latitude_string(const Location& location) {
char buffer[20];
// Format : <xxx°yy'zz"N>
sprintf(buffer, "%3d\260%02d'%02d\"%c", location.lat_deg, location.lat_min, location.lat_sec, location.south ? 'S' : 'N');
return std::string(buffer);
}
/**
* Convert the provided Loaction to it's longitude string (format <xxx°yy'zz"W>)
*/
std::string to_longitude_string(const Location& location) {
char buffer[20];
// Format : <xxx°yy'zz"W>
sprintf(buffer, "%3d\260%02d'%02d\"%c", location.long_deg, location.long_min, location.long_sec, location.west ? 'W' : 'E');
return std::string(buffer);
}
} // namespace ui::external_app::epirb_tx
#endif /*__LOCATION_H__*/
+82
View File
@@ -0,0 +1,82 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui.hpp"
#include "ui_epirb_tx.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::epirb_tx {
void initialize_app(ui::NavigationView& nav) {
nav.push<EPIRBTXAppView>();
}
} // namespace ui::external_app::epirb_tx
extern "C" {
__attribute__((section(".external_app.app_epirb_tx.application_information"), used)) application_information_t _application_information_epirb_tx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::epirb_tx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "EPIRB TX",
/*.bitmap_data = */ {
0x00,
0x00,
0x00,
0x00,
0x7C,
0x3E,
0xFE,
0x7F,
0xFF,
0xFF,
0xF7,
0xEF,
0xE3,
0xC7,
0xE3,
0xC7,
0xE3,
0xC7,
0xE3,
0xC7,
0xF7,
0xEF,
0xFF,
0xFF,
0xFE,
0x7F,
0x7C,
0x3E,
0x00,
0x00,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::green().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_epirb_tx */ {'P', 'E', 'P', 'T'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
}
+660
View File
@@ -0,0 +1,660 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui_epirb_tx.hpp"
#include "tonesets.hpp"
#include "portapack.hpp"
#include "baseband_api.hpp"
#include "string_format.hpp"
#include "file_reader.hpp"
#include "file_path.hpp"
#include "ui_geomap.hpp"
#include "ui_alphanum.hpp"
#include <cstring>
#include <stdio.h>
#include "beacon.hpp"
using namespace portapack;
namespace ui::external_app::epirb_tx {
void EPIRBTXAppView::focus() {
button_tx.focus();
}
EPIRBTXAppView::~EPIRBTXAppView() {
// Restore original frequency before leaving
transmitter_model.set_target_frequency(original_frequency);
transmitter_model.disable();
baseband::shutdown();
}
/**
* Conversion from hex char to half byte
*/
static uint8_t hexval(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 0;
}
/**
* Convert from hex chars to uint8_t
*/
static uint8_t hexToByte(char high, char low) {
return (hexval(high) << 4) | hexval(low);
}
std::string EPIRBTXAppView::frame_to_hex_string(bool start) {
return beacon_to_hex_string(epirb_tx_message.data, start);
}
void EPIRBTXAppView::generate_frame(BeaconParams params) {
epirb_tx_message.data_len = generate_beacon(epirb_tx_message.data, params);
}
void EPIRBTXAppView::on_timer() {
// Timer is called on display refresh
if (loop) {
if (loop_enabled) {
// chTimeNow() returns milliseconds on our version of ChibiOS / Hardware
auto now = chTimeNow();
auto elapsed = ((now - last_frame_time) / 1000);
std::string timeout = to_string_dec_uint((uint32_t)(delay > elapsed ? delay - elapsed : 0));
if (timeout != text_timeout.get()) {
// Update timeout text every seconds
text_timeout.set(timeout);
}
if (now > (last_frame_time + (delay * 1000))) {
if (mode_file && slideshow_enabled) {
// Move on to next frame
selected_beacon++;
if (selected_beacon >= beacons.size()) selected_beacon = 0;
// Update selection
file_mode_ui->options_frame.set_selected_index(selected_beacon);
}
// Send a new frame after the delay
start_tx();
}
} else {
// Stop send loop
loop = false;
}
}
}
void EPIRBTXAppView::update_bpsk_frequency() {
bool was_transmitting = false;
if (transmitting && (am_enabled || transmitting_bpsk)) {
// We need to stop transmission before changing frequency
transmitter_model.disable();
was_transmitting = true;
}
transmitter_model.set_target_frequency(bpsk_frequency);
// Update displayed frequency
tx_view.on_show();
if (was_transmitting) {
// Start over
start_tx();
}
}
void EPIRBTXAppView::update_am_transmission() {
if (am_enabled && transmitting && !transmitting_bpsk) {
// Start am transmission
// Restore am frequency
epirb_tx_message.mode_bpsk = false;
transmitter_model.set_target_frequency(am_frequency);
// Send config to baseband
baseband::set_epirb_tx_config(epirb_tx_message);
// Start transmitting
transmitter_model.enable();
} else if (transmitting && !transmitting_bpsk) {
// Stop am transmission
transmitter_model.disable();
tx_view.set_transmitting(false);
}
}
void EPIRBTXAppView::update_frame(bool updateConfig) {
if (mode_file) {
// In file mode, currently selected beacon has changed => load the new one
Beacon& beacon = beacons[selected_beacon];
// Set desciption
file_mode_ui->text_description.set(beacon.description.substr(0, max_text_width_ext));
file_mode_ui->text_description_end.set(beacon.description.size() > max_text_width_ext ? "-" + beacon.description.substr(max_text_width_ext, max_text_width_ext + max_text_width_ext - 1) : "");
// Udapte frame content on display
text_frame.set(beacon.frame.substr(0, 18));
text_frame_end.set(beacon.frame.size() > 18 ? beacon.frame.substr(18, 36) : "");
// Prepare tx configuration
epirb_tx_message.data_len = std::min<size_t>((beacon.frame.size() / 2), 18);
for (uint8_t i = 0; i < epirb_tx_message.data_len; i++) {
epirb_tx_message.data[i] = hexToByte(
beacon.frame[2 * i],
beacon.frame[2 * i + 1]);
}
} else {
// In manual mode, generate frame content for current beacon params
generate_frame(beacon_params);
// Update frame content on display
text_frame.set(frame_to_hex_string(true));
text_frame_end.set(frame_to_hex_string(false));
}
if (updateConfig && send_on_change && loop) {
// Need to update config / send new beacon
if (am_enabled) {
// Already transmitting => update config
last_frame_time = chTimeNow();
update_config();
} else {
// Not yet transmitting => start tx
start_tx();
}
}
}
void EPIRBTXAppView::update_config() {
if (!epirb_tx_message.mode_bpsk) {
// Previously in AM mode => restore bpsk frequency
transmitter_model.set_target_frequency(bpsk_frequency);
// Update displayed frequency
tx_view.on_show();
}
// Set mode to bpsk
epirb_tx_message.mode_bpsk = true;
transmitting_bpsk = true;
// Set pre/post count
epirb_tx_message.pre_count = (160 * TONES_SAMPLERATE) / 1000; // 160 ms carrier (COSPAS spec.)
epirb_tx_message.post_count = (100 * TONES_SAMPLERATE) / 1000; // 100 ms
// Send config to baseband
baseband::set_epirb_tx_config(epirb_tx_message);
}
void EPIRBTXAppView::set_tx_button_state(bool active) {
button_tx.set_text(active ? "START" : "STOP");
button_tx.set_style(active ? &style_tx_start : &style_tx_stop);
}
void EPIRBTXAppView::start_tx() {
last_frame_time = chTimeNow();
update_config();
loop = loop_enabled;
transmitter_model.enable();
tx_view.set_transmitting(true);
set_tx_button_state(false);
transmitting = true;
}
void EPIRBTXAppView::stop_tx() {
loop = false;
transmitter_model.disable();
tx_view.set_transmitting(false);
set_tx_button_state(true);
transmitting = false;
}
void EPIRBTXAppView::on_tx_progress(const uint32_t progress, const bool done) {
(void)progress;
if (done) {
transmitting_bpsk = false;
if (am_enabled) {
// BPSK frame sent, switch back to 121.5 AM signal
epirb_tx_message.mode_bpsk = false;
// Start am transmission
update_am_transmission();
} else {
// End of BPSK frame
transmitter_model.disable();
tx_view.set_transmitting(false);
if (!loop) {
// Not looping => update transmission state
set_tx_button_state(true);
transmitting = false;
}
}
}
}
void EPIRBTXAppView::update_location(bool updateLocatorField) {
locator = beacon_params.location.locator;
if (updateLocatorField) text_field_beacon_locator.set_text(beacon_params.location.locator);
text_beacon_latitude_value.set(to_latitude_string(beacon_params.location));
text_beacon_longitude_value.set(to_longitude_string(beacon_params.location));
}
void EPIRBTXAppView::update_mode() {
// Hide / show widgets for file mode or manual mode
using option_t = std::pair<std::string, int32_t>;
using options_t = std::vector<option_t>;
if (mode_file) {
// Load available beacons from BEACONS.TXT files (or default).
load_beacons();
if (!file_mode_ui) {
file_mode_ui = std::make_unique<FileModeWidgets>();
// Setup options_frame content with loaded beacons
options_t entries;
for (const auto& beacon : beacons)
entries.emplace_back(beacon.title, entries.size());
file_mode_ui->options_frame.set_options(entries);
if (selected_beacon >= beacons.size())
// BEACONS.TXT file has changed since last launch, default index to 0
selected_beacon = 0;
file_mode_ui->options_frame.set_selected_index(selected_beacon);
file_mode_ui->options_frame.on_change = [this](size_t index, OptionsField::value_t) {
selected_beacon = index;
update_frame();
set_dirty();
};
file_mode_ui->text_beacon.set_style(Theme::getInstance()->fg_light);
file_mode_ui->text_description_label.set_style(Theme::getInstance()->fg_light);
add_child(&file_mode_ui->text_beacon);
add_child(&file_mode_ui->options_frame);
add_child(&file_mode_ui->text_description_label);
add_child(&file_mode_ui->text_description);
add_child(&file_mode_ui->text_description_end);
add_child(&file_mode_ui->checkbox_slideshow);
// Restore settings
file_mode_ui->checkbox_slideshow.set_value(slideshow_enabled);
// Add callback
file_mode_ui->checkbox_slideshow.on_select = [this](Checkbox&, bool v) {
slideshow_enabled = v;
};
}
} else {
// Clear beacons to save ram for Map display and Locatior editor
if (file_mode_ui) {
remove_child(&file_mode_ui->text_beacon);
remove_child(&file_mode_ui->options_frame);
remove_child(&file_mode_ui->text_description_label);
remove_child(&file_mode_ui->text_description);
remove_child(&file_mode_ui->text_description_end);
remove_child(&file_mode_ui->checkbox_slideshow);
file_mode_ui.reset();
}
beacons.clear();
beacons.shrink_to_fit();
}
text_beacon_type.hidden(mode_file);
text_beacon_country.hidden(mode_file);
checkbox_beacon_internal.hidden(mode_file);
text_beacon_locator.hidden(mode_file);
text_beacon_latitude.hidden(mode_file);
text_beacon_latitude_value.hidden(mode_file);
text_beacon_longitude.hidden(mode_file);
text_beacon_longitude_value.hidden(mode_file);
button_mangps.hidden(mode_file);
options_beacon_type.hidden(mode_file);
options_beacon_protocol.hidden(mode_file);
options_beacon_country.hidden(mode_file);
text_field_beacon_locator.hidden(mode_file);
}
EPIRBTXAppView::EPIRBTXAppView(
NavigationView& nav)
: nav_{nav} {
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
add_children({&labels,
&options_mode,
&text_beacon_type,
&options_beacon_type,
&options_beacon_protocol,
&text_beacon_country,
&options_beacon_country,
&checkbox_beacon_internal,
&text_beacon_locator,
&text_beacon_latitude,
&text_beacon_latitude_value,
&text_beacon_longitude,
&text_beacon_longitude_value,
&button_mangps,
&text_field_beacon_locator,
&text_frame,
&text_frame_end,
&text_timeout,
&checkbox_loop,
&field_delay,
&button_tx,
&checkbox_am,
&field_am_frequency,
&checkbox_send_on_change,
&options_am_channel,
&options_bpsk_channel,
&tx_view});
text_beacon_type.set_style(Theme::getInstance()->fg_light);
text_beacon_country.set_style(Theme::getInstance()->fg_light);
text_beacon_locator.set_style(Theme::getInstance()->fg_light);
text_beacon_latitude.set_style(Theme::getInstance()->fg_light);
text_beacon_longitude.set_style(Theme::getInstance()->fg_light);
// Restore settings
checkbox_am.set_value(am_enabled);
checkbox_loop.set_value(loop_enabled);
checkbox_send_on_change.set_value(send_on_change);
options_mode.set_by_value(!mode_file);
transmitter_model.set_target_frequency(bpsk_frequency);
field_am_frequency.set_value(am_frequency);
options_am_channel.set_by_value(am_channel);
options_am_channel.set_style((am_channel == (uint8_t)AmChannel::REAL) ? Theme::getInstance()->fg_red : Theme::getInstance()->bg_darkest);
manual_am_frequency = am_frequency;
options_bpsk_channel.set_by_value(bpsk_channel);
manual_bpsk_frequency = bpsk_frequency;
field_delay.set_value(delay);
options_beacon_type.set_by_value(beacon_type);
options_beacon_protocol.set_by_value(beacon_protocol);
options_beacon_country.set_by_value(beacon_country);
checkbox_beacon_internal.set_value(beacon_internal);
beacon_params.type = (BeaconType)beacon_type;
beacon_params.has_121_5 = am_enabled;
beacon_params.location.locator = locator;
beacon_params.is_internal = beacon_internal;
init_from_locator(beacon_params.location);
update_mode();
update_location();
options_mode.on_change = [this](size_t, OptionsField::value_t value) {
mode_file = (((BeaconMode)value) == BeaconMode::FILE);
update_mode();
update_frame();
set_dirty();
};
options_beacon_type.on_change = [this](size_t, OptionsField::value_t value) {
beacon_params.type = (BeaconType)value;
beacon_type = value;
update_frame();
set_dirty();
};
options_beacon_protocol.on_change = [this](size_t, OptionsField::value_t value) {
beacon_params.protocol = (BeaconProtocol)value;
beacon_protocol = value;
update_frame();
set_dirty();
};
options_beacon_country.on_change = [this](size_t, OptionsField::value_t v) {
beacon_params.country = v;
beacon_country = v;
update_frame();
set_dirty();
};
options_am_channel.on_change = [this](size_t, OptionsField::value_t v) {
bool is_real = false;
switch ((AmChannel)v) {
case AmChannel::REAL:
is_real = true;
am_frequency = AM_REAL_FREQUENCY;
break;
case AmChannel::MANUAL:
am_frequency = manual_am_frequency;
break;
default:
v = (uint8_t)AmChannel::TEST;
// fallthrough
case AmChannel::TEST:
am_frequency = AM_TEST_FREQUENCY;
break;
}
// Actual frequency change will be done by field_am_frequency.on_change()
field_am_frequency.set_value(am_frequency);
am_channel = v;
options_am_channel.set_style(is_real ? Theme::getInstance()->fg_red : Theme::getInstance()->bg_darkest);
set_dirty();
};
options_bpsk_channel.on_change = [this](size_t, OptionsField::value_t v) {
switch ((BpskChannel)v) {
case BpskChannel::MANUAL:
bpsk_frequency = manual_bpsk_frequency;
break;
case BpskChannel::B:
bpsk_frequency = BPSK_FREQUENCY_B;
break;
case BpskChannel::C:
bpsk_frequency = BPSK_FREQUENCY_C;
break;
case BpskChannel::F:
bpsk_frequency = BPSK_FREQUENCY_F;
break;
case BpskChannel::G:
bpsk_frequency = BPSK_FREQUENCY_G;
break;
case BpskChannel::J:
bpsk_frequency = BPSK_FREQUENCY_J;
break;
case BpskChannel::K:
bpsk_frequency = BPSK_FREQUENCY_K;
break;
case BpskChannel::N:
bpsk_frequency = BPSK_FREQUENCY_N;
break;
case BpskChannel::O:
bpsk_frequency = BPSK_FREQUENCY_O;
break;
default:
v = (uint8_t)BpskChannel::HAM;
// fallthrough
case BpskChannel::HAM:
bpsk_frequency = BPSK_FREQUENCY_HAM;
break;
}
bpsk_channel = v;
update_bpsk_frequency();
set_dirty();
};
checkbox_beacon_internal.on_select = [this](Checkbox&, bool v) {
beacon_internal = v;
beacon_params.is_internal = v;
update_frame();
set_dirty();
};
text_field_beacon_locator.on_select = [this](TextField&) mutable {
auto te_view = nav_.push<AlphanumView>(locator, 10, ENTER_KEYBOARD_MODE_ALPHA);
te_view->on_changed = [this](std::string& value) {
beacon_params.location.locator = value;
init_from_locator(beacon_params.location);
update_location();
update_frame();
set_dirty();
};
};
button_mangps.on_select = [this](Button&) {
nav_.push<GeoMapView>(
0,
GeoPos::alt_unit::METERS,
GeoPos::spd_unit::HIDDEN,
beacon_params.location.latitude,
beacon_params.location.longitude,
[this](int32_t, float lat, float lon, int32_t) {
beacon_params.location.latitude = lat;
beacon_params.location.longitude = lon;
init_from_decimal(beacon_params.location);
// Update locator field
update_location();
update_frame();
set_dirty();
});
};
field_am_frequency.on_change = [this](rf::Frequency freq) {
am_frequency = freq;
if (transmitting && !transmitting_bpsk && am_enabled)
// Update transmitter frequency
transmitter_model.set_target_frequency(am_frequency);
};
// Init frame content / baseband param with currently setup beacon
update_frame(false);
checkbox_loop.on_select = [this](Checkbox&, bool v) {
loop_enabled = v;
};
field_delay.on_change = [this](int32_t v) {
delay = v;
};
checkbox_am.on_select = [this](Checkbox&, bool v) {
beacon_params.has_121_5 = v;
am_enabled = v;
update_am_transmission();
// We update the additional location device data in the frame based on this
if (!mode_file) update_frame(false);
};
// AM frequency field edit
field_am_frequency.on_edit = [this]() {
auto new_view = nav_.push<FrequencyKeypadView>(field_am_frequency.value());
new_view->on_changed = [this](rf::Frequency f) {
switch (f) {
case AM_REAL_FREQUENCY:
am_channel = (uint8_t)AmChannel::REAL;
break;
case AM_TEST_FREQUENCY:
am_channel = (uint8_t)AmChannel::TEST;
break;
default:
manual_am_frequency = f;
am_channel = (uint8_t)AmChannel::MANUAL;
break;
}
// Actual frequency change will be done by options_am_channel.on_change()
options_am_channel.set_by_value(am_channel);
set_dirty();
};
};
checkbox_send_on_change.on_select = [this](Checkbox&, bool v) {
send_on_change = v;
};
tx_view.on_edit_frequency = [this]() {
auto new_view = nav_.push<FrequencyKeypadView>(transmitter_model.target_frequency());
new_view->on_changed = [this](rf::Frequency f) {
bpsk_frequency = f;
switch (f) {
case BPSK_FREQUENCY_HAM:
bpsk_channel = (uint8_t)BpskChannel::HAM;
break;
case BPSK_FREQUENCY_B:
bpsk_channel = (uint8_t)BpskChannel::B;
break;
case BPSK_FREQUENCY_C:
bpsk_channel = (uint8_t)BpskChannel::C;
break;
case BPSK_FREQUENCY_F:
bpsk_channel = (uint8_t)BpskChannel::F;
break;
case BPSK_FREQUENCY_G:
bpsk_channel = (uint8_t)BpskChannel::G;
break;
case BPSK_FREQUENCY_J:
bpsk_channel = (uint8_t)BpskChannel::J;
break;
case BPSK_FREQUENCY_K:
bpsk_channel = (uint8_t)BpskChannel::K;
break;
case BPSK_FREQUENCY_N:
bpsk_channel = (uint8_t)BpskChannel::N;
break;
case BPSK_FREQUENCY_O:
bpsk_channel = (uint8_t)BpskChannel::O;
break;
default:
bpsk_channel = (uint8_t)BpskChannel::MANUAL;
manual_bpsk_frequency = bpsk_frequency;
break;
}
// Actual frequency change will be done by options_bpsk_channel.on_change()
options_bpsk_channel.set_by_value(bpsk_channel);
set_dirty();
};
};
tx_view.on_start = [this]() {
start_tx();
};
tx_view.on_stop = [this]() {
stop_tx();
};
button_tx.on_select = [this](Button&) {
if (!transmitting)
start_tx();
else
stop_tx();
};
}
/**
* Load beacons from /EPIRB/BEACONS.TXT file on sd card
*/
void EPIRBTXAppView::load_beacons() {
File beacons_file;
auto error = beacons_file.open(epirb_dir / u"BEACONS.TXT");
beacons.clear();
if (!error) {
// BEACONS.TXT file exists
auto reader = FileLineReader(beacons_file);
for (const auto& line : reader) {
// Skip comment lines
if (line.length() == 0 || line[0] == '#')
continue;
// Split line with ';' separator
auto cols = split_string(line, ';');
if (cols.size() != 3)
continue;
// Read current beacon
Beacon beacon{};
beacon.title = trim(cols[0]);
beacon.description = trim(cols[1]);
// Make sure frame is not longer tha 18 bytes / 36 hex character
beacon.frame = trim(cols[2]).substr(0, 36);
size_t size = beacon.frame.size();
if (size <= 0)
continue; // Invalid line.
// Beacon is valid, add it to the list
beacons.emplace_back(std::move(beacon));
}
}
if (beacons.empty()) {
// No beacons file or empty flile: just add default beacon
beacons.push_back(default_beacon);
}
}
} // namespace ui::external_app::epirb_tx
+417
View File
@@ -0,0 +1,417 @@
/*
* Copyright (C) 2026 Frederic BORRY - ADRASEC 31
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __EPIRB_TX_H__
#define __EPIRB_TX_H__
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_transmitter.hpp"
#include "portapack.hpp"
#include "message.hpp"
#include "tonesets.hpp"
#define BEACON_HEXA_SIZE 36
#define BEACON_HEXA_HALF_SIZE 18
#define BEACON_SIZE 18
#define AM_TEST_FREQUENCY 121375000
#define AM_REAL_FREQUENCY 121500000
#define BPSK_FREQUENCY_HAM 433025000
#define BPSK_FREQUENCY_B 406025000
#define BPSK_FREQUENCY_C 406028000
#define BPSK_FREQUENCY_F 406037000
#define BPSK_FREQUENCY_G 406040000
#define BPSK_FREQUENCY_J 406049000
#define BPSK_FREQUENCY_K 406052000
#define BPSK_FREQUENCY_N 406061000
#define BPSK_FREQUENCY_O 406064000
namespace ui::external_app::epirb_tx {
enum class BeaconMode {
FILE = 0,
MODE_MANUAL = 1
};
enum class BeaconType {
EPIRB = 0,
ELT = 1,
PLB = 2
};
enum class BeaconProtocol {
USER = 0,
STANDARD = 1,
NATIONAL = 2
};
enum class AmChannel {
TEST = 0,
REAL = 1,
MANUAL = 2
};
enum class BpskChannel {
HAM = 0,
B = 1,
C = 2,
F = 3,
G = 4,
J = 5,
K = 6,
N = 7,
O = 8,
MANUAL = 10
};
struct Location {
std::string locator;
bool south;
int16_t lat_deg;
int8_t lat_min;
int8_t lat_sec;
float latitude;
bool west;
int16_t long_deg;
int8_t long_min;
int8_t long_sec;
float longitude;
};
struct BeaconParams {
BeaconType type;
BeaconProtocol protocol;
uint32_t country;
bool is_test;
bool is_internal;
bool has_121_5;
Location location;
};
class EPIRBTXAppView : public View {
public:
EPIRBTXAppView(NavigationView& nav);
~EPIRBTXAppView();
void focus() override;
std::string title() const override { return "EPIRB TX"; };
private:
void start_tx();
void stop_tx();
void update_config();
void on_tx_progress(const uint32_t progress, const bool done);
void on_timer();
void load_beacons();
void set_tx_button_state(bool active);
std::string frame_to_hex_string(bool start);
void generate_frame(BeaconParams params);
void update_frame(bool updateConfig = true);
void update_bpsk_frequency();
void update_am_transmission();
void update_mode();
void update_location(bool updateLocatorField = true);
struct Beacon {
std::string title{};
std::string description{};
std::string frame{};
};
NavigationView& nav_;
std::vector<Beacon> beacons{};
Beacon default_beacon{"Self test", "Serial User Location Protocol", "FFFED0D6E6202820000C29FF51041775302D"};
BeaconParams beacon_params{BeaconType::ELT, BeaconProtocol::STANDARD, 227, true, true, true, {"JN03RO", false, 0, 0, 0, 0, false, 0, 0, 0, 0}};
// Currently selected beacon index (from BEACONS.TXT file / options_frame combo)
uint32_t selected_beacon{0};
// Frequency of the transmitter before starting the app (used to restore frequency when leaving)
rf::Frequency original_frequency{0};
// Frequency of the AM emergency signal
rf::Frequency am_frequency{AM_TEST_FREQUENCY};
// Frequency of the 406 MHz BPSK signal
rf::Frequency bpsk_frequency{BPSK_FREQUENCY_HAM};
// Selected am channel
uint8_t am_channel{(uint8_t)AmChannel::TEST};
// Selected bpsk channel
uint8_t bpsk_channel{(uint8_t)BpskChannel::HAM};
// Manual AM frequency value
rf::Frequency manual_am_frequency{AM_TEST_FREQUENCY};
// Manual BPSK frequency value
rf::Frequency manual_bpsk_frequency{BPSK_FREQUENCY_HAM};
// True when using a beacon from the BEACONS.TXT file
bool mode_file{false};
// True when slideshow is enabled for file mode (change beacon after every transmission)
bool slideshow_enabled{false};
// True when looping on sending beacons is enabled
bool loop_enabled{true};
// True if AM emergency signal transmission is enabled
bool am_enabled{true};
// True if we want to send a new frame each time the user changes the current beacon
bool send_on_change{true};
// The current locator string
std::string locator{"JN03RO"};
// The delay between each frame when on loop mode
uint32_t delay{50};
uint8_t beacon_type{(uint8_t)BeaconType::EPIRB};
// Currently selected beacon protocol
uint8_t beacon_protocol{(uint8_t)BeaconProtocol::USER};
// Currently selected beacon country
uint32_t beacon_country{227};
// Current beacon's internal state (true for internal location system)
bool beacon_internal{true};
TxRadioState radio_state_{
0 /* frequency */,
1750000 /* bandwidth */,
TONES_SAMPLERATE /* sampling rate */
};
app_settings::SettingsManager settings_{
"tx_epirb",
app_settings::Mode::TX,
{
{"sbeacon"sv, &selected_beacon},
{"amfreq"sv, &am_frequency},
{"bpskfreq"sv, &bpsk_frequency},
{"amchan"sv, &am_channel},
{"bpskchan"sv, &bpsk_channel},
{"loop"sv, &loop_enabled},
{"delay"sv, &delay},
{"file"sv, &mode_file},
{"slideshow"sv, &slideshow_enabled},
{"am"sv, &am_enabled},
{"soc"sv, &send_on_change},
{"type"sv, &beacon_type},
{"proto"sv, &beacon_protocol},
{"country"sv, &beacon_country},
{"internal"sv, &beacon_internal},
{"locator"sv, &locator},
}};
// Time of the last sent frame
uint32_t last_frame_time{0};
// True when transmission is enabled
bool transmitting{false};
// True when transmitting a BPSK frame
bool transmitting_bpsk{false};
// True when currently looping on sending beacons
bool loop{false};
// Current EPIRBTXDataMessage for baseband
EPIRBTXDataMessage epirb_tx_message{};
const size_t max_text_width = UI_POS_WIDTH_REMAINING(6) / UI_POS_DEFAULT_WIDTH;
const size_t max_text_width_ext = UI_POS_WIDTH_REMAINING(0) / UI_POS_DEFAULT_WIDTH;
Labels labels{
{{UI_POS_X(0), UI_POS_Y(0)}, "Source:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(6)}, "Frame:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(10)}, "Next frame in s.", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(12)}, "AM frequency: MHz", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(14)}, "AM chan.:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(15)}, "BPSK chan.:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(17), UI_POS_Y(9)}, "s.", Theme::getInstance()->fg_light->foreground}};
// For file mode
struct FileModeWidgets {
Text text_beacon{
{UI_POS_X(0), UI_POS_Y(1), UI_POS_WIDTH(7), UI_POS_DEFAULT_HEIGHT},
"Beacon:"};
// Beacon selection from BEACONS.TXT
OptionsField options_frame{
{UI_POS_X(7), UI_POS_Y(1)},
30,
{}};
Text text_description_label{
{UI_POS_X(0), UI_POS_Y(2), UI_POS_WIDTH(12), UI_POS_DEFAULT_HEIGHT},
"Description:"};
Text text_description{
{UI_POS_X(0), UI_POS_Y(3), UI_POS_WIDTH_REMAINING(0), UI_POS_DEFAULT_HEIGHT},
""};
Text text_description_end{
{UI_POS_X(0), UI_POS_Y(4), UI_POS_WIDTH_REMAINING(0), UI_POS_DEFAULT_HEIGHT},
""};
Checkbox checkbox_slideshow{
{UI_POS_X(0), UI_POS_Y(5)},
9,
"Slideshow",
true};
};
std::unique_ptr<FileModeWidgets> file_mode_ui{};
// For manual mode
Text text_beacon_type{
{UI_POS_X(0), UI_POS_Y(1), UI_POS_WIDTH(8), UI_POS_DEFAULT_HEIGHT},
"Type:"};
Text text_beacon_country{
{UI_POS_X(0), UI_POS_Y(2), UI_POS_WIDTH(8), UI_POS_DEFAULT_HEIGHT},
"Country:"};
Checkbox checkbox_beacon_internal{
{UI_POS_X_RIGHT(12), UI_POS_Y(2)},
12,
"Internal",
true};
Text text_beacon_locator{
{UI_POS_X(0), UI_POS_Y(3), UI_POS_WIDTH(8), UI_POS_DEFAULT_HEIGHT},
"Locator:"};
Text text_beacon_latitude{
{UI_POS_X(0), UI_POS_Y(4), UI_POS_WIDTH(8), UI_POS_DEFAULT_HEIGHT},
"Lat.:"};
Text text_beacon_longitude{
{UI_POS_X(0), UI_POS_Y(5), UI_POS_WIDTH(8), UI_POS_DEFAULT_HEIGHT},
"Long.:"};
Text text_beacon_latitude_value{
{UI_POS_X(7), UI_POS_Y(4), UI_POS_WIDTH(12), UI_POS_DEFAULT_HEIGHT},
""};
Text text_beacon_longitude_value{
{UI_POS_X(7), UI_POS_Y(5), UI_POS_WIDTH(12), UI_POS_DEFAULT_HEIGHT},
""};
OptionsField options_beacon_type{
{UI_POS_X(9), UI_POS_Y(1)},
7,
{{"EPIRB", (uint8_t)BeaconType::EPIRB},
{"ELT", (uint8_t)BeaconType::ELT},
{"PLB", (uint8_t)BeaconType::PLB}}};
OptionsField options_beacon_protocol{
{UI_POS_X(9 + 7), UI_POS_Y(1)},
30,
{{"User", (uint8_t)BeaconProtocol::USER},
{"Standard", (uint8_t)BeaconProtocol::STANDARD},
{"National", (uint8_t)BeaconProtocol::NATIONAL}}};
OptionsField options_beacon_country{
{UI_POS_X(9), UI_POS_Y(2)},
7,
{{"France", 227},
{"USA", 366},
{"Germany", 211},
{"Russia", 273},
{"Spain", 224},
{"Japan", 431},
{"UK", 232}}};
TextField text_field_beacon_locator{
{UI_POS_X(9), UI_POS_Y(3), UI_POS_WIDTH(10), UI_POS_DEFAULT_HEIGHT},
"JN03RO"};
Button button_mangps{
{UI_POS_X_RIGHT(9), UI_POS_Y(3), UI_POS_WIDTH(9), UI_POS_HEIGHT(2)},
"Set pos."};
// Mode selection (file/manual)
OptionsField options_mode{
{UI_POS_X(7), UI_POS_Y(0)},
30,
{{"File (BEACONS.TXT)", (uint8_t)BeaconMode::FILE},
{"Manual (Editor)", (uint8_t)BeaconMode::MODE_MANUAL}}};
// Frame content
Text text_frame{
{UI_POS_X(6), UI_POS_Y(6), UI_POS_WIDTH_REMAINING(6), UI_POS_DEFAULT_HEIGHT},
""};
Text text_frame_end{
{UI_POS_X(6), UI_POS_Y(7), UI_POS_WIDTH_REMAINING(6), UI_POS_DEFAULT_HEIGHT},
""};
Text text_timeout{
{UI_POS_X(14), UI_POS_Y(10), UI_POS_WIDTH(2), UI_POS_DEFAULT_HEIGHT},
""};
// Transmission settings
Checkbox checkbox_loop{
{UI_POS_X(0), UI_POS_Y(9)},
10,
"Resend every",
true};
NumberField field_delay{
{UI_POS_X(15), UI_POS_Y(9)},
2,
{1, 99},
1,
' '};
Checkbox checkbox_am{
{UI_POS_X(0), UI_POS_Y(11)},
10,
"AM signal",
true};
FrequencyField field_am_frequency{
{UI_POS_X(13), UI_POS_Y(12)}};
Checkbox checkbox_send_on_change{
{UI_POS_X(0), UI_POS_Y(13)},
14,
"Send on change",
true};
Button button_tx{
{UI_POS_X_RIGHT(9), UI_POS_Y(9), UI_POS_WIDTH(9), UI_POS_HEIGHT(2)},
"START"};
const Style& style_tx_start = *Theme::getInstance()->fg_green;
const Style& style_tx_stop = *Theme::getInstance()->fg_red;
OptionsField options_am_channel{
{UI_POS_X(11), UI_POS_Y(14)},
20,
{{"121.375 MHz (Test)", 0},
{"121.500 MHz /!\\Real", 1},
{"Manual", 2}}};
OptionsField options_bpsk_channel{
{UI_POS_X(11), UI_POS_Y(15)},
20,
{{"433.025 MHz (Ham)", (uint8_t)BpskChannel::HAM},
{"406.025 MHz (B)", (uint8_t)BpskChannel::B},
{"406.028 MHz (C)", (uint8_t)BpskChannel::C},
{"406.037 MHz (F)", (uint8_t)BpskChannel::F},
{"406.040 MHz (G)", (uint8_t)BpskChannel::G},
{"406.049 MHz (J)", (uint8_t)BpskChannel::J},
{"406.052 MHz (K)", (uint8_t)BpskChannel::K},
{"406.061 MHz (N)", (uint8_t)BpskChannel::N},
{"406.064 MHz (O)", (uint8_t)BpskChannel::O},
{"Manual", (uint8_t)BpskChannel::MANUAL}}};
// Transmitter view
TransmitterView tx_view{
(int16_t)UI_POS_Y_BOTTOM(4),
10000,
12};
MessageHandlerRegistration message_handler_tx_progress{
Message::ID::TXProgress,
[this](const Message* const p) {
const auto message = *reinterpret_cast<const TXProgressMessage*>(p);
this->on_tx_progress(message.progress, message.done);
}};
MessageHandlerRegistration message_handler_frame_sync{
// Use frame sync for our applcation timer callback
Message::ID::DisplayFrameSync,
[this](const Message* const) {
this->on_timer();
}};
};
} // namespace ui::external_app::epirb_tx
#endif /*__EPIRB_TX_H__*/
+1 -1
View File
@@ -100,7 +100,7 @@ namespace ui::external_app::ert_app {
ERTAppView::ERTAppView(NavigationView& nav)
: nav_{nav} {
baseband::run_image(portapack::spi_flash::image_tag_ert);
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
add_children({
&field_frequency,
+1 -1
View File
@@ -77,7 +77,7 @@ __attribute__((section(".external_app.app_ert.application_information"), used))
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_none */ {'P', 'E', 'R', 'T'},
/*.m4_app_tag = portapack::spi_flash::image_tag_ert */ {'P', 'E', 'R', 'T'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
}
+72 -6
View File
@@ -103,6 +103,14 @@ set(EXTCPPSRC
external/sstvtx/main.cpp
external/sstvtx/ui_sstvtx.cpp
#same_tx
external/same_tx/main.cpp
external/same_tx/ui_same_tx.cpp
#mdc_tx
external/mdc_tx/main.cpp
external/mdc_tx/ui_mdc_tx.cpp
#sstvrx
external/sstvrx/main.cpp
external/sstvrx/ui_sstvrx.cpp
@@ -113,8 +121,8 @@ set(EXTCPPSRC
external/random_password/sha512.cpp
#acars
#external/acars_rx/main.cpp
#external/acars_rx/acars_app.cpp
external/acars_rx/main.cpp
external/acars_rx/acars_app.cpp
#wefax_rx 192 bytes
external/wefax_rx/main.cpp
@@ -255,6 +263,14 @@ set(EXTCPPSRC
#epirb_rx 168 byte flash
external/epirb_rx/main.cpp
external/epirb_rx/ui_epirb_rx.cpp
external/epirb_rx/ui_beaconlist.cpp
external/epirb_rx/beacon_db.cpp
external/epirb_rx/beacon.cpp
external/epirb_rx/location.cpp
#epirb_tx
external/epirb_tx/main.cpp
external/epirb_tx/ui_epirb_tx.cpp
#soundboard 272byte - 1236 bytes
external/soundboard/main.cpp
@@ -297,8 +313,10 @@ set(EXTCPPSRC
external/morseradiotx/main.cpp
external/morseradiotx/ui_morse_radiotx.cpp
external/keeloqtx/main.cpp
external/keeloqtx/ui_keeloqtx.cpp
#keeloqtx
external/keeloqtx/main.cpp
external/keeloqtx/ui_keeloqtx.cpp
#rtty_rx
external/rtty_rx/main.cpp
external/rtty_rx/ui_rtty_rx.cpp
@@ -308,6 +326,42 @@ set(EXTCPPSRC
external/rtty_tx/main.cpp
external/rtty_tx/ui_rtty_tx.cpp
external/rtty_tx/baudot.cpp
#pocsag_tx
external/pocsag_tx/main.cpp
external/pocsag_tx/ui_pocsag_tx.cpp
#flex_tx
external/flex_tx/main.cpp
external/flex_tx/ui_flex_tx.cpp
#time_sink
external/time_sink/main.cpp
external/time_sink/ui_time_sink.cpp
#kiss_tnc
external/kiss_tnc/main.cpp
external/kiss_tnc/ui_kiss_tnc.cpp
#fpv_detect
external/fpv_detect/main.cpp
external/fpv_detect/ui_fpv_detect.cpp
#p25_tx
external/p25_tx/main.cpp
external/p25_tx/ui_p25_tx.cpp
#two_tone_pager
external/two_tone_pager/main.cpp
external/two_tone_pager/ui_two_tone_pager.cpp
#two_tone_rx
external/two_tone_rx/main.cpp
external/two_tone_rx/ui_two_tone_rx.cpp
#hard_reset
external/hard_reset/main.cpp
external/hard_reset/ui_hard_reset.cpp
)
set(EXTAPPLIST
@@ -335,9 +389,11 @@ set(EXTAPPLIST
adsbtx
#morse_tx
sstvtx
same_tx
mdc_tx
sstvrx
random_password
# acars_rx --not working
acars_rx
wefax_rx
noaaapt_rx
shoppingcart_lock
@@ -367,11 +423,13 @@ set(EXTAPPLIST
gfxeq
waterfall_designer
detector_rx
fpv_detect
spaceinv
blackjack
battleship
ert
epirb_rx
epirb_tx
soundboard
game2048
bht_tx
@@ -382,9 +440,17 @@ set(EXTAPPLIST
siggen
morse_radio
morseradiotx
keeloqtx
keeloqtx
rtty_rx
rtty_tx
pocsag_tx
flex_tx
time_sink
kiss_tnc
p25_tx
two_tone_pager
two_tone_rx
hard_reset
)
# sdusb has type conflicts with PRALINE (HackRF Pro) - add only for non-PRALINE builds
+180 -98
View File
@@ -23,81 +23,93 @@ MEMORY
* Also need to consider processor memory map - reading 0xADxxxxxx generates a fault which may be better than unexpected behavior.
* External app address ranges below must match those in python file "external_app_info.py".
*/
ram_external_app_afsk_rx (rwx) : org = 0xADB10000, len = 32k
ram_external_app_calculator (rwx) : org = 0xADB20000, len = 32k
ram_external_app_font_viewer(rwx) : org = 0xADB30000, len = 32k
ram_external_app_blespam (rwx) : org = 0xADB40000, len = 32k
ram_external_app_analogtv (rwx) : org = 0xADB50000, len = 32k
ram_external_app_nrf_rx (rwx) : org = 0xADB60000, len = 32k
ram_external_app_coasterp (rwx) : org = 0xADB70000, len = 32k
ram_external_app_lge (rwx) : org = 0xADB80000, len = 32k
ram_external_app_lcr (rwx) : org = 0xADB90000, len = 32k
ram_external_app_jammer (rwx) : org = 0xADBA0000, len = 32k
ram_external_app_gpssim (rwx) : org = 0xADBB0000, len = 32k
ram_external_app_spainter (rwx) : org = 0xADBC0000, len = 32k
ram_external_app_keyfob (rwx) : org = 0xADBD0000, len = 32k
ram_external_app_tetris (rwx) : org = 0xADBE0000, len = 32k
ram_external_app_extsensors (rwx) : org = 0xADBF0000, len = 32k
ram_external_app_foxhunt_rx (rwx) : org = 0xADC00000, len = 32k
ram_external_app_audio_test (rwx) : org = 0xADC10000, len = 32k
ram_external_app_wardrivemap(rwx) : org = 0xADC20000, len = 32k
ram_external_app_tpmsrx (rwx) : org = 0xADC30000, len = 32k
ram_external_app_protoview (rwx) : org = 0xADC40000, len = 32k
ram_external_app_adsbtx (rwx) : org = 0xADC50000, len = 32k
ram_external_app_morse_tx (rwx) : org = 0xADC60000, len = 32k
ram_external_app_sstvtx (rwx) : org = 0xADC70000, len = 32k
ram_external_app_random_password(rwx): org = 0xADC80000, len = 32k
ram_external_app_acars_rx (rwx) : org = 0xADC90000, len = 32k
ram_external_app_shoppingcart_lock(rwx): org = 0xADCA0000, len = 32k
ram_external_app_cvs_spam (rwx) : org = 0xADCB0000, len = 32k
ram_external_app_ookbrute (rwx) : org = 0xADCC0000, len = 32k
ram_external_app_flippertx (rwx) : org = 0xADCD0000, len = 32k
ram_external_app_ook_editor (rwx) : org = 0xADCE0000, len = 32k
ram_external_app_remote (rwx) : org = 0xADCF0000, len = 32k
ram_external_app_mcu_temperature(rwx): org = 0xADD00000, len = 32k
ram_external_app_fmradio (rwx) : org = 0xADD10000, len = 32k
ram_external_app_tuner (rwx) : org = 0xADD20000, len = 32k
ram_external_app_metronome (rwx) : org = 0xADD30000, len = 32k
ram_external_app_app_manager(rwx) : org = 0xADD40000, len = 32k
ram_external_app_hopper (rwx) : org = 0xADD50000, len = 32k
ram_external_app_antenna_length(rwx): org = 0xADD60000, len = 32k
ram_external_app_view_wav (rwx) : org = 0xADD70000, len = 32k
ram_external_app_sd_wipe (rwx) : org = 0xADD80000, len = 32k
ram_external_app_playlist_editor(rwx): org = 0xADD90000, len = 32k
ram_external_app_snake (rwx) : org = 0xADDA0000, len = 32k
ram_external_app_stopwatch (rwx) : org = 0xADDB0000, len = 32k
ram_external_app_wefax_rx (rwx) : org = 0xADDC0000, len = 32k
ram_external_app_breakout (rwx) : org = 0xADDD0000, len = 32k
ram_external_app_doom (rwx) : org = 0xADDE0000, len = 32k
ram_external_app_debug_pmem (rwx) : org = 0xADDF0000, len = 32k
ram_external_app_scanner (rwx) : org = 0xADE00000, len = 32k
ram_external_app_level (rwx) : org = 0xADE10000, len = 32k
ram_external_app_gfxeq (rwx) : org = 0xADE20000, len = 32k
ram_external_app_noaaapt_rx (rwx) : org = 0xADE30000, len = 32k
ram_external_app_detector_rx (rwx) : org = 0xADE40000, len = 32k
ram_external_app_dinogame (rwx) : org = 0xADE50000, len = 32k
ram_external_app_spaceinv (rwx) : org = 0xADE60000, len = 32k
ram_external_app_blackjack (rwx) : org = 0xADE70000, len = 32k
ram_external_app_battleship (rwx) : org = 0xADE80000, len = 32k
ram_external_app_ert (rwx) : org = 0xADE90000, len = 32k
ram_external_app_epirb_rx (rwx) : org = 0xADEA0000, len = 32k
ram_external_app_soundboard (rwx) : org = 0xADEB0000, len = 32k
ram_external_app_game2048 (rwx) : org = 0xADEC0000, len = 32k
ram_external_app_bht_tx (rwx) : org = 0xADED0000, len = 32k
ram_external_app_morse_practice (rwx) : org = 0xADEE0000, len = 32k
ram_external_app_adult_toys_controller (rwx) : org = 0xADEF0000, len = 32k
ram_external_app_flex_rx (rwx) : org = 0xADF00000, len = 32k
ram_external_app_sstvrx (rwx) : org = 0xADF10000, len = 32k
ram_external_app_subcarrx (rwx) : org = 0xADF20000, len = 32k
ram_external_app_siggen (rwx) : org = 0xADF30000, len = 32k
ram_external_app_sdusb (rwx) : org = 0xADF40000, len = 32k
ram_external_app_morse_radio (rwx) : org = 0xADF50000, len = 32k
ram_external_app_waterfall_designer (rwx) : org = 0xADF60000, len = 32k
ram_external_app_morseradiotx (rwx) : org = 0xADF70000, len = 32k
ram_external_app_keeloqtx (rwx) : org = 0xADF80000, len = 32k
ram_external_app_rtty_rx (rwx) : org = 0xADF90000, len = 32k
ram_external_app_rtty_tx (rwx) : org = 0xADFA0000, len = 32k
ram_external_app_tpmstx (rwx) : org = 0xADFB0000, len = 32k
ram_external_app_afsk_rx (rwx) : org = 0xADB10000, len = 32k
ram_external_app_calculator (rwx) : org = 0xADB20000, len = 32k
ram_external_app_font_viewer (rwx) : org = 0xADB30000, len = 32k
ram_external_app_blespam (rwx) : org = 0xADB40000, len = 32k
ram_external_app_analogtv (rwx) : org = 0xADB50000, len = 32k
ram_external_app_nrf_rx (rwx) : org = 0xADB60000, len = 32k
ram_external_app_coasterp (rwx) : org = 0xADB70000, len = 32k
ram_external_app_lge (rwx) : org = 0xADB80000, len = 32k
ram_external_app_lcr (rwx) : org = 0xADB90000, len = 32k
ram_external_app_jammer (rwx) : org = 0xADBA0000, len = 32k
ram_external_app_gpssim (rwx) : org = 0xADBB0000, len = 32k
ram_external_app_spainter (rwx) : org = 0xADBC0000, len = 32k
ram_external_app_keyfob (rwx) : org = 0xADBD0000, len = 32k
ram_external_app_tetris (rwx) : org = 0xADBE0000, len = 32k
ram_external_app_extsensors (rwx) : org = 0xADBF0000, len = 32k
ram_external_app_foxhunt_rx (rwx) : org = 0xADC00000, len = 32k
ram_external_app_audio_test (rwx) : org = 0xADC10000, len = 32k
ram_external_app_wardrivemap (rwx) : org = 0xADC20000, len = 32k
ram_external_app_tpmsrx (rwx) : org = 0xADC30000, len = 32k
ram_external_app_protoview (rwx) : org = 0xADC40000, len = 32k
ram_external_app_adsbtx (rwx) : org = 0xADC50000, len = 32k
ram_external_app_morse_tx (rwx) : org = 0xADC60000, len = 32k
ram_external_app_sstvtx (rwx) : org = 0xADC70000, len = 32k
ram_external_app_random_password (rwx) : org = 0xADC80000, len = 32k
ram_external_app_acars_rx (rwx) : org = 0xADC90000, len = 32k
ram_external_app_shoppingcart_lock (rwx) : org = 0xADCA0000, len = 32k
ram_external_app_cvs_spam (rwx) : org = 0xADCB0000, len = 32k
ram_external_app_ookbrute (rwx) : org = 0xADCC0000, len = 32k
ram_external_app_flippertx (rwx) : org = 0xADCD0000, len = 32k
ram_external_app_ook_editor (rwx) : org = 0xADCE0000, len = 32k
ram_external_app_remote (rwx) : org = 0xADCF0000, len = 32k
ram_external_app_mcu_temperature (rwx) : org = 0xADD00000, len = 32k
ram_external_app_fmradio (rwx) : org = 0xADD10000, len = 32k
ram_external_app_tuner (rwx) : org = 0xADD20000, len = 32k
ram_external_app_metronome (rwx) : org = 0xADD30000, len = 32k
ram_external_app_app_manager (rwx) : org = 0xADD40000, len = 32k
ram_external_app_hopper (rwx) : org = 0xADD50000, len = 32k
ram_external_app_antenna_length (rwx) : org = 0xADD60000, len = 32k
ram_external_app_view_wav (rwx) : org = 0xADD70000, len = 32k
ram_external_app_sd_wipe (rwx) : org = 0xADD80000, len = 32k
ram_external_app_playlist_editor (rwx) : org = 0xADD90000, len = 32k
ram_external_app_snake (rwx) : org = 0xADDA0000, len = 32k
ram_external_app_stopwatch (rwx) : org = 0xADDB0000, len = 32k
ram_external_app_wefax_rx (rwx) : org = 0xADDC0000, len = 32k
ram_external_app_breakout (rwx) : org = 0xADDD0000, len = 32k
ram_external_app_doom (rwx) : org = 0xADDE0000, len = 32k
ram_external_app_debug_pmem (rwx) : org = 0xADDF0000, len = 32k
ram_external_app_scanner (rwx) : org = 0xADE00000, len = 32k
ram_external_app_level (rwx) : org = 0xADE10000, len = 32k
ram_external_app_gfxeq (rwx) : org = 0xADE20000, len = 32k
ram_external_app_noaaapt_rx (rwx) : org = 0xADE30000, len = 32k
ram_external_app_detector_rx (rwx) : org = 0xADE40000, len = 32k
ram_external_app_dinogame (rwx) : org = 0xADE50000, len = 32k
ram_external_app_spaceinv (rwx) : org = 0xADE60000, len = 32k
ram_external_app_blackjack (rwx) : org = 0xADE70000, len = 32k
ram_external_app_battleship (rwx) : org = 0xADE80000, len = 32k
ram_external_app_ert (rwx) : org = 0xADE90000, len = 32k
ram_external_app_epirb_rx (rwx) : org = 0xADEA0000, len = 32k
ram_external_app_soundboard (rwx) : org = 0xADEB0000, len = 32k
ram_external_app_game2048 (rwx) : org = 0xADEC0000, len = 32k
ram_external_app_bht_tx (rwx) : org = 0xADED0000, len = 32k
ram_external_app_morse_practice (rwx) : org = 0xADEE0000, len = 32k
ram_external_app_adult_toys_controller (rwx) : org = 0xADEF0000, len = 32k
ram_external_app_flex_rx (rwx) : org = 0xADF00000, len = 32k
ram_external_app_sstvrx (rwx) : org = 0xADF10000, len = 32k
ram_external_app_subcarrx (rwx) : org = 0xADF20000, len = 32k
ram_external_app_siggen (rwx) : org = 0xADF30000, len = 32k
ram_external_app_sdusb (rwx) : org = 0xADF40000, len = 32k
ram_external_app_morse_radio (rwx) : org = 0xADF50000, len = 32k
ram_external_app_waterfall_designer (rwx) : org = 0xADF60000, len = 32k
ram_external_app_morseradiotx (rwx) : org = 0xADF70000, len = 32k
ram_external_app_keeloqtx (rwx) : org = 0xADF80000, len = 32k
ram_external_app_rtty_rx (rwx) : org = 0xADF90000, len = 32k
ram_external_app_rtty_tx (rwx) : org = 0xADFA0000, len = 32k
ram_external_app_tpmstx (rwx) : org = 0xADFB0000, len = 32k
ram_external_app_pocsag_tx (rwx) : org = 0xADFC0000, len = 32k
ram_external_app_time_sink (rwx) : org = 0xADFD0000, len = 32k
ram_external_app_same_tx (rwx) : org = 0xADFE0000, len = 32k
ram_external_app_kiss_tnc (rwx) : org = 0xADFF0000, len = 32k
ram_external_app_mdc_tx (rwx) : org = 0xAE000000, len = 32k
ram_external_app_epirb_tx (rwx) : org = 0xAE010000, len = 32k
ram_external_app_fpv_detect (rwx) : org = 0xAE020000, len = 32k
ram_external_app_p25_tx (rwx) : org = 0xAE030000, len = 32k
ram_external_app_two_tone_pager (rwx) : org = 0xAE040000, len = 32k
ram_external_app_two_tone_rx (rwx) : org = 0xAE050000, len = 32k
ram_external_app_flex_tx (rwx) : org = 0xAE060000, len = 32k
ram_external_app_hard_reset (rwx) : org = 0xAE070000, len = 32k
}
SECTIONS
@@ -138,7 +150,7 @@ SECTIONS
*(*ui*external_app*nrf_rx*);
} > ram_external_app_nrf_rx
.external_app_coasterp : ALIGN(4) SUBALIGN(4)
.external_app_coasterp : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_coasterp.application_information));
*(*ui*external_app*coasterp*);
@@ -186,61 +198,61 @@ SECTIONS
*(*ui*external_app*tetris*);
} > ram_external_app_tetris
.external_app_extsensors : ALIGN(4) SUBALIGN(4)
.external_app_extsensors : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_extsensors.application_information));
*(*ui*external_app*extsensors*);
} > ram_external_app_extsensors
.external_app_foxhunt_rx : ALIGN(4) SUBALIGN(4)
.external_app_foxhunt_rx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_foxhunt_rx.application_information));
*(*ui*external_app*foxhunt_rx*);
} > ram_external_app_foxhunt_rx
.external_app_audio_test : ALIGN(4) SUBALIGN(4)
.external_app_audio_test : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_audio_test.application_information));
*(*ui*external_app*audio_test*);
} > ram_external_app_audio_test
.external_app_wardrivemap : ALIGN(4) SUBALIGN(4)
.external_app_wardrivemap : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_wardrivemap.application_information));
*(*ui*external_app*wardrivemap*);
} > ram_external_app_wardrivemap
.external_app_tpmsrx : ALIGN(4) SUBALIGN(4)
.external_app_tpmsrx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_tpmsrx.application_information));
*(*ui*external_app*tpmsrx*);
} > ram_external_app_tpmsrx
.external_app_tpmstx : ALIGN(4) SUBALIGN(4)
.external_app_tpmstx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_tpmstx.application_information));
*(*ui*external_app*tpmstx*);
} > ram_external_app_tpmstx
.external_app_protoview : ALIGN(4) SUBALIGN(4)
.external_app_protoview : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_protoview.application_information));
*(*ui*external_app*protoview*);
} > ram_external_app_protoview
.external_app_adsbtx : ALIGN(4) SUBALIGN(4)
.external_app_adsbtx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_adsbtx.application_information));
*(*ui*external_app*adsbtx*);
} > ram_external_app_adsbtx
.external_app_morse_tx : ALIGN(4) SUBALIGN(4)
.external_app_morse_tx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_morse_tx.application_information));
*(*ui*external_app*morse_tx*);
} > ram_external_app_morse_tx
.external_app_sstvtx : ALIGN(4) SUBALIGN(4)
.external_app_sstvtx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_sstvtx.application_information));
*(*ui*external_app*sstvtx*);
@@ -258,19 +270,19 @@ SECTIONS
*(*ui*external_app*acars_rx*);
} > ram_external_app_acars_rx
.external_app_shoppingcart_lock : ALIGN(4) SUBALIGN(4)
.external_app_shoppingcart_lock : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_shoppingcart_lock.application_information));
*(*ui*external_app*shoppingcart_lock*);
} > ram_external_app_shoppingcart_lock
.external_app_cvs_spam : ALIGN(4) SUBALIGN(4)
.external_app_cvs_spam : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_cvs_spam.application_information));
*(*ui*external_app*cvs_spam*);
} > ram_external_app_cvs_spam
.external_app_ookbrute : ALIGN(4) SUBALIGN(4)
.external_app_ookbrute : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_ookbrute.application_information));
*(*ui*external_app*ookbrute*);
@@ -282,7 +294,7 @@ SECTIONS
*(*ui*external_app*ook_editor*);
} > ram_external_app_ook_editor
.external_app_flippertx : ALIGN(4) SUBALIGN(4)
.external_app_flippertx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_flippertx.application_information));
*(*ui*external_app*flippertx*);
@@ -366,13 +378,13 @@ SECTIONS
*(*ui*external_app*stopwatch*);
} > ram_external_app_stopwatch
.external_app_wefax_rx : ALIGN(4) SUBALIGN(4)
.external_app_wefax_rx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_wefax_rx.application_information));
*(*ui*external_app*wefax_rx*);
} > ram_external_app_wefax_rx
.external_app_noaaapt_rx : ALIGN(4) SUBALIGN(4)
.external_app_noaaapt_rx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_noaaapt_rx.application_information));
*(*ui*external_app*noaaapt_rx*);
@@ -474,14 +486,12 @@ SECTIONS
*(*ui*external_app*game2048*);
} > ram_external_app_game2048
.external_app_bht_tx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_bht_tx.application_information));
*(*ui*external_app*bht_tx*);
} > ram_external_app_bht_tx
.external_app_morse_practice : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_morse_practice.application_information));
@@ -498,7 +508,7 @@ SECTIONS
{
KEEP(*(.external_app.app_flex_rx.application_information));
*(*ui*external_app*flex_rx*);
} > ram_external_app_flex_rx
} > ram_external_app_flex_rx
.external_app_sstvrx : ALIGN(4) SUBALIGN(4)
{
@@ -518,12 +528,12 @@ SECTIONS
*(*ui*external_app*siggen*);
} > ram_external_app_siggen
.external_app_sdusb : ALIGN(4) SUBALIGN(4)
.external_app_sdusb : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_sdusb.application_information));
*(*ui*external_app*sdusb*);
} > ram_external_app_sdusb
.external_app_morse_radio : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_morse_radio.application_information));
@@ -541,6 +551,7 @@ SECTIONS
KEEP(*(.external_app.app_keeloqtx.application_information));
*(*ui*external_app*keeloqtx*);
} > ram_external_app_keeloqtx
.external_app_rtty_rx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_rtty_rx.application_information));
@@ -552,5 +563,76 @@ SECTIONS
KEEP(*(.external_app.app_rtty_tx.application_information));
*(*ui*external_app*rtty_tx*);
} > ram_external_app_rtty_tx
}
.external_app_pocsag_tx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_pocsag_tx.application_information));
*(*ui*external_app*pocsag_tx*);
} > ram_external_app_pocsag_tx
.external_app_time_sink : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_time_sink.application_information));
*(*ui*external_app*time_sink*);
} > ram_external_app_time_sink
.external_app_same_tx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_same_tx.application_information));
*(*ui*external_app*same_tx*);
} > ram_external_app_same_tx
.external_app_kiss_tnc : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_kiss_tnc.application_information));
*(*ui*external_app*kiss_tnc*);
} > ram_external_app_kiss_tnc
.external_app_mdc_tx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_mdc_tx.application_information));
*(*ui*external_app*mdc_tx*);
} > ram_external_app_mdc_tx
.external_app_epirb_tx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_epirb_tx.application_information));
*(*ui*external_app*epirb_tx*);
} > ram_external_app_epirb_tx
.external_app_fpv_detect : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_fpv_detect.application_information));
*(*ui*external_app*fpv_detect*);
} > ram_external_app_fpv_detect
.external_app_p25_tx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_p25_tx.application_information));
*(*ui*external_app*p25_tx*);
} > ram_external_app_p25_tx
.external_app_two_tone_pager : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_two_tone_pager.application_information));
*(*ui*external_app*two_tone_pager*);
} > ram_external_app_two_tone_pager
.external_app_two_tone_rx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_two_tone_rx.application_information));
*(*ui*external_app*two_tone_rx*);
} > ram_external_app_two_tone_rx
.external_app_flex_tx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_flex_tx.application_information));
*(*ui*external_app*flex_tx*);
} > ram_external_app_flex_tx
.external_app_hard_reset : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_hard_reset.application_information));
*(*ui*external_app*hard_reset*);
} > ram_external_app_hard_reset
}
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_extsensors.application_information"),
0xF0,
0x0F,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::DEBUG,
/*.desired_menu_position = */ -1,
@@ -77,6 +77,10 @@ void ExtSensorsView::on_any() {
has_data = true;
}
void ExtSensorsView::on_show() {
i2cdev::I2CDevManager::set_autoscan_interval(3);
}
void ExtSensorsView::on_gps(const GPSPosDataMessage* msg) {
on_any();
std::string tmp = to_string_decimal(msg->lat, 5);
@@ -78,6 +78,8 @@ class ExtSensorsView : public View {
void on_orientation(const OrientationDataMessage* msg);
void on_environment(const EnvironmentDataMessage* msg);
void on_show() override;
MessageHandlerRegistration message_handler_gps{
Message::ID::GPSPosData,
[this](Message* const p) {
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_flex_rx.application_information"), use
0x00,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
+244 -54
View File
@@ -4,11 +4,15 @@
#include "portapack_persistent_memory.hpp"
#include "string_format.hpp"
#include "memory_map.hpp"
#include "usb_serial_asyncmsg.hpp"
using namespace portapack;
namespace ui::external_app::flex_rx {
static const int flex_tz_table[] = {0, 60, 120, 180, 240, 300, 360, 420, 480, 540, 600, 660, 720,
210, 270, 330, 0, 345, 390, 570, -210, -660, -600, -540, -480, -420, -360, -300, -240, -180, -120, -60};
FlexAppView::FlexAppView(NavigationView& nav)
: nav_{nav} {
// Load baseband image for FLEX decoding
@@ -19,6 +23,8 @@ FlexAppView::FlexAppView(NavigationView& nav)
&field_lna,
&field_vga,
&rssi,
&text_status1,
&text_status2,
&console});
// Restore saved frequency
@@ -39,6 +45,7 @@ FlexAppView::FlexAppView(NavigationView& nav)
// Initialize FLEX baseband
baseband::set_flex_config();
text_status1.set("No signal");
console.writeln("Ready");
}
@@ -51,54 +58,9 @@ void FlexAppView::focus() {
field_frequency.focus();
}
// Redraw all messages to console
void FlexAppView::redraw_console() {
console.clear(true);
bool first = true;
for (const auto& msg : messages) {
if (!first) {
console.writeln(""); // Blank line between messages
}
first = false;
console.writeln(msg);
}
}
// Add message to log with automatic line wrapping
// Add message to console
void FlexAppView::log_message(const std::string& message) {
const size_t chars_per_line = screen_width / 8;
// Console height accounts for status bar and controls row
const size_t console_lines = (screen_height - 2 * 16) / 16;
messages.push_back(message);
// Calculate total lines used (messages + blank lines between them)
size_t total_lines = 0;
for (size_t i = 0; i < messages.size(); i++) {
if (i > 0) total_lines++; // Count blank line separator
size_t msg_lines = (messages[i].length() + chars_per_line - 1) / chars_per_line;
if (msg_lines == 0) msg_lines = 1;
total_lines += msg_lines;
}
// If console would overflow, remove oldest messages and redraw
if (total_lines > console_lines) {
while (total_lines > console_lines && !messages.empty()) {
const auto& oldest = messages.front();
size_t oldest_lines = (oldest.length() + chars_per_line - 1) / chars_per_line;
if (oldest_lines == 0) oldest_lines = 1;
total_lines -= oldest_lines;
if (messages.size() > 1) total_lines--; // Remove separator line too
messages.erase(messages.begin());
}
redraw_console();
} else {
// Just append new message
if (messages.size() > 1) {
console.writeln(""); // Blank line before new message
}
console.writeln(message);
}
console.writeln(message);
}
// Update frequency and save for persistence
@@ -107,9 +69,234 @@ void FlexAppView::update_freq(rf::Frequency f) {
receiver_model.set_target_frequency(f);
}
// Type tag from numeric type code
static const char* flex_type_tag(uint32_t type) {
switch (type) {
case 0:
return "SEC";
case 1:
return "INS";
case 2:
return "TON";
case 3:
return "NUM";
case 4:
return "SNUM";
case 5:
return "ALN";
case 6:
return "HEX";
case 7:
return "NNUM";
case 8:
return "SHORT";
case 9:
return "BIW";
default:
return "UNK";
}
}
// Handle decoded FLEX packet from baseband
void FlexAppView::on_packet(const FlexPacketMessage* message) {
log_message(message->packet.message);
const auto& pkt = message->packet;
const char* type = flex_type_tag(pkt.type);
const char* pol = pkt.is_inverted ? "I" : "N";
// Update status row 1: C/F speed polarity time timezone
{
std::string s1 = "C" + to_string_dec_uint(pkt.cycle) +
"/F" + to_string_dec_uint(pkt.frame) +
" " + to_string_dec_uint(pkt.bitrate) +
" " + pol;
if (status_time_[0]) {
s1 += " ";
s1 += status_time_;
}
if (status_tz_[0]) {
s1 += " ";
s1 += status_tz_;
}
text_status1.set(s1);
}
// Update status row 2 from BIW data
if (pkt.type == 9) {
switch (pkt.biw_field) {
case 0: // SSID1
status_lid_ = pkt.biw_v1;
status_cz_ = pkt.biw_v2;
break;
case 2: { // Time
uint32_t si = (pkt.biw_v3 * 75) / 10;
auto h = to_string_dec_uint(pkt.biw_v1, 2, '0');
auto m = to_string_dec_uint(pkt.biw_v2, 2, '0');
auto sec = to_string_dec_uint(si, 2, '0');
// Store for row 1
auto ts = h + ":" + m + ":" + sec;
memcpy(status_time_, ts.c_str(), ts.size() + 1);
break;
}
case 5: { // SysInfo (timezone)
if (pkt.biw_v1 == 4 || pkt.biw_v1 == 5) {
uint16_t zone = pkt.biw_v2 & 0x1F;
int ofs = (zone < 32) ? flex_tz_table[zone] : 0;
int hrs = ofs / 60;
int mins = (ofs < 0 ? -ofs : ofs) % 60;
auto tzs = std::string("UTC") + (ofs >= 0 ? "+" : "") +
to_string_dec_int(hrs);
if (mins != 0)
tzs += ":" + to_string_dec_int(mins, 2, '0');
memcpy(status_tz_, tzs.c_str(), tzs.size() + 1);
}
break;
}
case 7: // SSID2
status_cc_ = pkt.biw_v1;
break;
}
// Rebuild row 2
std::string s2;
if (status_lid_) s2 += "LID:" + to_string_dec_uint(status_lid_);
if (status_cz_) {
s2 += " CZ:";
s2 += to_string_dec_uint(status_cz_);
}
if (status_cc_) {
s2 += " CC:";
s2 += to_string_dec_uint(status_cc_);
}
if (pkt.fiw_roaming) s2 += " R";
text_status2.set(s2);
}
// Console: skip BIW, tone-only (V=010), SHORT reserved (t=3)
bool skip_gui = (pkt.type == 9 || pkt.type == 2);
if (pkt.type == 8 && pkt.function == 3) skip_gui = true;
if (!skip_gui) {
auto cf = to_string_dec_uint(pkt.cycle) + "/" + to_string_dec_uint(pkt.frame);
std::string line = cf + " " + to_string_dec_uint(pkt.bitrate) +
" " + pol + " " + std::string(1, pkt.phase) + " ";
if (pkt.type == 1 && pkt.message[0] == 'i' && pkt.message[2] == 't') {
// INS temp group: "1234567 +GRP5@F42"
line += to_string_dec_uint(pkt.capcode);
line += " +TG";
line += to_string_dec_uint(pkt.biw_v1);
line += "@F";
line += to_string_dec_uint(pkt.biw_v2);
} else if (pkt.type == 1) {
// Other INS types
line += to_string_dec_uint(pkt.capcode);
line += " INS ";
line += pkt.message;
} else if (pkt.addr_type == 2) {
// Temp group delivery: "GRP5 ALN message"
uint32_t slot = (uint32_t)(pkt.capcode + 0x8000 - 0x1F7800) & 0x0F;
line += "TG";
line += to_string_dec_uint(slot);
line += " ";
line += type;
if (pkt.message[0]) {
line += " ";
line += pkt.message;
}
} else {
line += to_string_dec_uint(pkt.capcode);
if (pkt.is_priority) line += " P";
line += " ";
line += type;
if (pkt.message[0]) {
line += " ";
line += pkt.message;
}
}
log_message(line);
}
// Serial: pipe-delimited
if (portapack::usb_serial.serial_connected()) {
std::string s;
s = "FLEX|";
s += to_string_dec_uint(pkt.cycle);
s += '/';
s += to_string_dec_uint(pkt.frame);
s += '|';
s += to_string_dec_uint(pkt.bitrate);
s += '|';
s += pol;
s += '|';
s += pkt.phase;
if (pkt.type == 9) {
s += "|BIW|w=";
s += to_string_dec_uint(pkt.function);
s += "|t=";
s += to_string_dec_uint(pkt.biw_field);
s += '|';
s += to_string_dec_uint(pkt.biw_v1);
s += '|';
s += to_string_dec_uint(pkt.biw_v2);
s += '|';
s += to_string_dec_uint(pkt.biw_v3);
} else {
s += '|';
s += type;
s += "|cap=";
s += to_string_dec_uint(pkt.capcode);
if (pkt.is_priority) s += "|pri=1";
if (pkt.addr_type == 2) {
// Temporary address: show slot number
// capcode = aw - 0x8000, aw = capcode + 0x8000
// slot = (aw - 0x1F7800) & 0x0F = (capcode + 0x8000 - 0x1F7800) & 0x0F
uint32_t slot = (uint32_t)(pkt.capcode + 0x8000 - 0x1F7800) & 0x0F;
s += "|slot=";
s += to_string_dec_uint(slot);
}
if (pkt.has_flags) {
if (pkt.type == 7) {
s += "|seq=";
s += to_string_dec_uint(pkt.seq);
s += "|new=";
s += to_string_dec_uint(pkt.is_new);
s += "|fmt=";
s += pkt.nnum_s ? "idrom" : "std";
} else {
s += "|frag=";
s += (pkt.frag == 3) ? "first" : to_string_dec_uint(pkt.frag).c_str();
s += "|mf=";
s += to_string_dec_uint(pkt.more_frag);
s += "|seq=";
s += to_string_dec_uint(pkt.seq);
if (pkt.frag == 3) {
s += "|new=";
s += to_string_dec_uint(pkt.is_new);
s += "|md=";
s += to_string_dec_uint(pkt.maildrop);
s += "|sig=";
s += to_string_hex(pkt.sig, 2);
}
if (pkt.type == 0) {
static const char* enc[] = {"alpha", "sep", "bin", "rsvd"};
s += "|enc=";
s += enc[pkt.sec_enc & 3];
}
if (pkt.type == 6 && pkt.frag == 3) {
uint8_t b = pkt.function & 0x0F;
s += "|bb=";
s += to_string_dec_uint(b == 0 ? 16 : b);
if (pkt.function & 0x10) s += "|rtl=1";
}
}
}
if (pkt.message[0]) {
s += "|\"";
s += pkt.message;
s += '"';
}
}
UsbSerialAsyncmsg::asyncmsg(s);
}
}
// Handle stats message (currently unused)
@@ -118,12 +305,15 @@ void FlexAppView::on_stats(const FlexStatsMessage*) {
// Debug handler - uncomment to see baseband debug messages
void FlexAppView::on_debug(const FlexDebugMessage* message) {
(void)message; // Suppress unused parameter warning
// std::string text = "DBG: ";
// text += message->text;
// text += " " + to_string_hex(message->val1, 8);
// text += " " + to_string_hex(message->val2, 8);
// log_message(text);
if (portapack::usb_serial.serial_connected()) {
std::string s = "DBG|";
s += message->text;
s += "|";
s += to_string_dec_int(message->val1);
s += "|";
s += to_string_dec_int(message->val2);
UsbSerialAsyncmsg::asyncmsg(s);
}
}
} // namespace ui::external_app::flex_rx
+17 -7
View File
@@ -26,17 +26,19 @@ class FlexAppView : public View {
NavigationView& nav_;
// Saved settings
rf::Frequency frequency_value{931740000}; // Default FLEX frequency
rf::Frequency frequency_value{931740000};
RxRadioState radio_state_{};
// Message storage for console redraw
static constexpr size_t MAX_MESSAGES = 20;
std::vector<std::string> messages{};
// Status bar state (updated from BIW packets)
char status_time_[12]{}; // "HH:MM:SS"
char status_tz_[12]{}; // "UTC+N"
uint16_t status_lid_{0};
uint16_t status_cz_{0};
uint16_t status_cc_{0};
// Helper methods
void log_message(const std::string& message);
void redraw_console();
void update_freq(rf::Frequency f);
// UI Elements - Row 0, dynamically positioned
@@ -54,9 +56,17 @@ class FlexAppView : public View {
RSSI rssi{
{UI_POS_X(21), 0, UI_POS_WIDTH(9), 4}};
// Message display area (below controls, account for status bar)
// Status rows (rows 1-2)
Text text_status1{
{0, 1 * 16, screen_width, 16},
""};
Text text_status2{
{0, 2 * 16, screen_width, 16},
""};
// Message display area (below status rows)
Console console{
{0, 1 * 16, screen_width, screen_height - 2 * 16}};
{0, 3 * 16, screen_width, screen_height - 4 * 16}};
// Persistent settings manager
app_settings::SettingsManager settings_{
+62
View File
@@ -0,0 +1,62 @@
#include "ui.hpp"
#include "ui_flex_tx.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::flex_tx {
void initialize_app(ui::NavigationView& nav) {
nav.push<FlexTXView>();
}
} // namespace ui::external_app::flex_tx
extern "C" {
__attribute__((section(".external_app.app_flex_tx.application_information"), used)) application_information_t _application_information_flex_tx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::flex_tx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "FLEX TX",
/*.bitmap_data = */ {
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFC,
0x3F,
0xFE,
0x7F,
0x02,
0x40,
0xBA,
0x45,
0x02,
0x40,
0xFE,
0x7F,
0xFE,
0x7F,
0x92,
0x7C,
0x92,
0x7C,
0xFC,
0x3F,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::cyan().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_fsktx */ {'P', 'F', 'S', 'K'},
/*.m4_app_offset = */ 0x00000000,
};
}
+903
View File
@@ -0,0 +1,903 @@
#include "ui_flex_tx.hpp"
#include "baseband_api.hpp"
#include "string_format.hpp"
#include "ui_textentry.hpp"
#include "portapack_persistent_memory.hpp"
#include "portapack_shared_memory.hpp"
#include "rtc_time.hpp"
#include <cstring>
using namespace portapack;
namespace ui::external_app::flex_tx {
#define MAX_FLEX_MSG 240
#define BCH_POLY 0x769
#define DATA_MASK 0x1FFFFF
// ===== Bit reversal =====
static uint32_t reverse_bits32(uint32_t v) {
v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);
v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
v = (v >> 16) | (v << 16);
return v;
}
// ===== BCH(31,21) encoder =====
static uint32_t flex_encode_word(uint32_t dw) {
uint32_t data = dw >> 11;
uint32_t dividend = data << 10;
for (int i = 30; i >= 10; i--) {
if ((dividend >> i) & 1)
dividend ^= BCH_POLY << (i - 10);
}
uint32_t ecc = dividend & 0x3FF;
uint32_t code31 = (data << 10) | ecc;
uint32_t p = 0, tmp = code31;
while (tmp) {
p ^= (tmp & 1);
tmp >>= 1;
}
return (code31 << 1) | p;
}
static uint32_t flex_enc(uint32_t data21) {
return flex_encode_word(reverse_bits32(data21));
}
// ===== Checksum =====
static uint32_t flex_checksum(uint32_t d) {
uint32_t s = (d & 0xF) + ((d >> 4) & 0xF) + ((d >> 8) & 0xF) +
((d >> 12) & 0xF) + ((d >> 16) & 0xF) + ((d >> 20) & 0x1);
return (d & ~0xFU) | ((0xF - (s & 0xF)) & 0xF);
}
// ===== Year equivalence =====
static int flex_is_leap(int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
static int flex_jan1_dow(int y) {
static const int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
return (y + y / 4 - y / 100 + y / 400 + t[0] + 1) % 7;
}
static int flex_equiv_year(int year) {
if (year >= 1994 && year <= 2025)
return year;
int target_leap = flex_is_leap(year);
int target_dow = flex_jan1_dow(year);
for (int y = 2025; y >= 1994; y--) {
if (flex_is_leap(y) == target_leap &&
flex_jan1_dow(y) == target_dow)
return y;
}
return 1994 + ((year - 1994) & 0x1F);
}
// ===== FIW =====
static uint32_t flex_fiw(uint32_t cycle, uint32_t frame, uint32_t roaming) {
uint32_t d = 0;
d |= (cycle & 0xF) << 4;
d |= (frame & 0x7F) << 8;
d |= (roaming & 1) << 15;
// r=0, t=0 (single transmission, no low traffic flags)
return flex_enc(flex_checksum(d));
}
// ===== BIW1 =====
static uint32_t flex_biw1(uint32_t astart, uint32_t vstart, uint32_t collapse) {
uint32_t d = 0;
d |= ((astart - 1) & 0x03) << 8;
d |= (vstart & 0x3F) << 10;
d |= (collapse & 0x07) << 18;
return flex_enc(flex_checksum(d));
}
// ===== BIW Date (type 001) =====
static uint32_t flex_biw_date(uint32_t year_field, uint32_t month, uint32_t day) {
uint32_t d = 0;
d |= (1U) << 4; // type = 001
d |= (year_field & 0x1F) << 7;
d |= (day & 0x1F) << 12;
d |= (month & 0x0F) << 17;
return flex_enc(flex_checksum(d));
}
// ===== BIW Time (type 010) =====
static uint32_t flex_biw_time(uint32_t hour, uint32_t minute, uint32_t second_step) {
uint32_t d = 0;
d |= (2U) << 4; // type = 010
d |= (hour & 0x1F) << 7;
d |= (minute & 0x3F) << 12;
d |= (second_step & 0x07) << 18;
return flex_enc(flex_checksum(d));
}
// ===== BIW SysInfo (type 101) =====
static uint32_t flex_biw_sysinfo(uint32_t a_type, uint32_t info) {
uint32_t d = 0;
d |= (5U) << 4; // type = 101
d |= (a_type & 0x0F) << 7;
d |= (info & 0x03FF) << 11;
return flex_enc(flex_checksum(d));
}
// ===== BIW SSID1 (type 000) =====
static uint32_t flex_biw_ssid1(uint32_t local_id, uint32_t coverage_zone) {
uint32_t d = 0;
// type = 000 (no bits to set)
d |= (coverage_zone & 0x1F) << 7;
d |= (local_id & 0x01FF) << 12;
return flex_enc(flex_checksum(d));
}
// ===== BIW SSID2 (type 111) =====
static uint32_t flex_biw_ssid2(uint32_t country_code, uint32_t tmf) {
uint32_t d = 0;
d |= (7U) << 4; // type = 111
d |= (tmf & 0x0F) << 7;
d |= (country_code & 0x03FF) << 11;
return flex_enc(flex_checksum(d));
}
// ===== Short address =====
static uint32_t flex_short_addr(uint64_t capcode) {
return flex_enc((uint32_t)(capcode + 0x8000) & DATA_MASK);
}
// ===== Long address (2 words) =====
static int flex_long_addr(uint64_t capcode, uint32_t out[2]) {
uint64_t result;
uint32_t w1, w2;
if (capcode >= 2101249ULL && capcode <= 1075843072ULL) {
result = capcode - 2068481ULL;
w1 = (result % 32768) + 1;
w2 = 2097151U - (result / 32768);
} else if (capcode >= 1075843073ULL && capcode <= 3223326720ULL) {
result = capcode - 2068481ULL;
w1 = (result % 32768) + 1;
w2 = (result / 32768) + 1933312U;
} else if (capcode >= 3223326721ULL && capcode <= 4297068542ULL) {
result = capcode - 2068479ULL;
w1 = (result % 32768) + 2064383U;
w2 = (result / 32768) + 1867776U;
} else {
return -1;
}
out[0] = flex_enc(w1 & DATA_MASK);
out[1] = flex_enc(w2 & DATA_MASK);
return 0;
}
// ===== Vector words =====
static uint32_t flex_alpha_vector(uint32_t mw_start, uint32_t mw_count) {
uint32_t d = 0;
d |= (5U & 0x07) << 4;
d |= (mw_start & 0x7F) << 7;
d |= (mw_count & 0x7F) << 14;
return flex_enc(flex_checksum(d));
}
static uint32_t flex_numeric_vector(uint32_t type, uint32_t mw_start, uint32_t mw_count, uint32_t kbit) {
uint32_t n_field = (mw_count > 0) ? mw_count - 1 : 0;
uint32_t d = 0;
d |= (type & 0x07) << 4;
d |= (mw_start & 0x7F) << 7;
d |= (n_field & 0x07) << 14;
d |= (kbit & 0x0F) << 17;
return flex_enc(flex_checksum(d));
}
// Short vector (type 2, t=00): BCD digits in vector word
// Short addr: 3 digits in d0-d11. Long addr: 3 + 5 in 2nd word.
// Tone-only: call with empty string (all digits become space 0xC).
static uint32_t flex_short_vector(int is_long, const std::string& msg, uint32_t* vy_out) {
static const char bcd_chars[20] = "0123456789.U -][";
auto to_bcd = [&](char c) -> uint8_t {
for (int k = 0; k < 16; k++)
if (bcd_chars[k] == c) return k;
return 0xC; // space
};
int max_digits = is_long ? 8 : 3;
uint8_t digits[8];
for (int i = 0; i < 8; i++) {
digits[i] = (i < (int)msg.size() && i < max_digits) ? to_bcd(msg[i]) : 0xC;
}
uint32_t vw = 0;
vw |= (2U & 0x07) << 4; // type = 010
// t1t0 = 00 (numeric) — bits 7-8 stay 0
vw |= ((uint32_t)digits[0] & 0xF) << 9;
vw |= ((uint32_t)digits[1] & 0xF) << 13;
vw |= ((uint32_t)digits[2] & 0xF) << 17;
if (is_long && vy_out) {
uint32_t d2 = 0;
for (int i = 0; i < 5 && (i + 3) < max_digits; i++)
d2 |= ((uint32_t)digits[i + 3] & 0xF) << (i * 4);
*vy_out = flex_enc(d2);
}
return flex_enc(flex_checksum(vw));
}
// ===== Block interleave =====
static void flex_interleave_block(uint32_t blk, uint32_t* frame_words) {
uint32_t src[8];
uint8_t dst[32];
memcpy(src, frame_words + blk * 8, sizeof(src));
for (uint32_t i = 0; i < 32; i++) {
dst[i] = (uint8_t)((((src[0] >> (31 - i)) & 1) << 7) |
(((src[1] >> (31 - i)) & 1) << 6) |
(((src[2] >> (31 - i)) & 1) << 5) |
(((src[3] >> (31 - i)) & 1) << 4) |
(((src[4] >> (31 - i)) & 1) << 3) |
(((src[5] >> (31 - i)) & 1) << 2) |
(((src[6] >> (31 - i)) & 1) << 1) |
(((src[7] >> (31 - i)) & 1) << 0));
}
memcpy(frame_words + blk * 8, dst, sizeof(dst));
}
// ===== Alpha encoding =====
static int flex_encode_alpha(const std::string& msg, uint32_t* words, int max_words, uint32_t seq, uint32_t msg_r) {
int wc = 0;
uint32_t hdr = 0;
hdr |= (3U << 11);
hdr |= ((seq & 0x3F) << 13);
hdr |= ((msg_r & 1U) << 19);
words[wc++] = hdr;
size_t ci = 0;
uint32_t dw = 0;
uint8_t ch;
ch = (ci < msg.size()) ? msg[ci++] : 0x03;
dw |= ((uint32_t)(ch & 0x7F)) << 7;
ch = (ci < msg.size()) ? msg[ci++] : 0x03;
dw |= ((uint32_t)(ch & 0x7F)) << 14;
words[wc++] = dw;
while (ci < msg.size() && wc < max_words) {
dw = 0;
for (int s = 0; s < 3; s++) {
ch = (ci < msg.size()) ? msg[ci++] : 0x03;
dw |= ((uint32_t)(ch & 0x7F)) << (s * 7);
}
words[wc++] = dw;
}
// Signature
{
uint32_t sig_sum = 0;
for (int i = 1; i < wc; i++) {
uint32_t c0 = (words[i] >> 0) & 0x7F;
uint32_t c1 = (words[i] >> 7) & 0x7F;
uint32_t c2 = (words[i] >> 14) & 0x7F;
if (c0 != 0x03) sig_sum += c0;
if (c1 != 0x03) sig_sum += c1;
if (c2 != 0x03) sig_sum += c2;
}
words[1] = (words[1] & ~0x7FU) | ((~sig_sum) & 0x7F);
}
// K checksum
{
uint32_t k_sum = 0;
for (int i = 0; i < wc; i++) {
k_sum += words[i] & 0xFF;
k_sum += (words[i] >> 8) & 0xFF;
k_sum += (words[i] >> 16) & 0x1F;
}
words[0] |= ((~k_sum) & 0x3FF);
}
for (int i = 0; i < wc; i++)
words[i] = flex_enc(words[i]);
return wc;
}
// ===== Numeric BCD encoding =====
static int flex_encode_numeric(const std::string& msg, uint32_t* words, int max_words, uint32_t* k_out) {
static const char bcd[20] = "0123456789.U -][";
uint32_t mw[8] = {0};
int bit = 2;
int word_idx = 0;
for (size_t i = 0; i < msg.size(); i++) {
uint8_t nib = 0;
for (int k = 0; k < 16; k++)
if (bcd[k] == msg[i]) {
nib = k;
break;
}
for (int b = 0; b < 4; b++) {
word_idx = bit / 21;
if (word_idx >= 8) break;
if (nib & (1 << b))
mw[word_idx] |= (1U << (bit % 21));
bit++;
}
}
word_idx = (bit > 0) ? (bit - 1) / 21 : 0;
{
int end_bit = (word_idx + 1) * 21;
while (bit + 4 <= end_bit) {
for (int b = 0; b < 4; b++) {
if (0x0C & (1 << b))
mw[bit / 21] |= (1U << (bit % 21));
bit++;
}
}
}
uint32_t kb = 0;
for (int i = 0; i <= word_idx; i++) {
kb += mw[i] & 0xFF;
kb += (mw[i] >> 8) & 0xFF;
kb += (mw[i] >> 16) & 0x1F;
}
kb &= 0xFF;
kb = (kb & 0x3F) + (kb >> 6);
kb = ~kb;
mw[0] |= ((kb >> 4) & 0x03);
*k_out = kb & 0x0F;
int wc = word_idx + 1;
for (int i = 0; i < wc && i < max_words; i++)
words[i] = flex_enc(mw[i]);
return wc;
}
// ===== Sync patterns =====
static const uint8_t bs1[] = {0xAA, 0xAA, 0xAA, 0xAA};
static const uint8_t a1[] = {0x78, 0xF3, 0x59, 0x39};
static const uint8_t b_code[4] = {0x55, 0x55, 0x00, 0x00};
static const uint8_t ar[] = {0xCB, 0x20, 0x59, 0x39};
static void write_word(uint8_t*& p, uint32_t w) {
*p++ = (w >> 24) & 0xFF;
*p++ = (w >> 16) & 0xFF;
*p++ = (w >> 8) & 0xFF;
*p++ = w & 0xFF;
}
// ===== Build frame =====
static size_t build_frame(uint8_t* buf, uint64_t capcode, int msg_type, const std::string& msg, uint32_t cycle, uint32_t frame, uint32_t msg_r, const FlexBIWParams& bp) {
uint8_t* p = buf;
// S1 sync
memcpy(p, bs1, 4);
p += 4;
memcpy(p, a1, 4);
p += 4;
memcpy(p, b_code, 2);
p += 2;
for (int i = 0; i < 4; i++) *p++ = ~a1[i];
// FIW
write_word(p, flex_fiw(cycle, frame, bp.roaming));
// S2
{
uint8_t s2[5];
memset(s2, 0, 5);
uint64_t bits = 0;
bits |= (uint64_t)0xA << 36;
bits |= (uint64_t)0xED84 << 20;
bits |= (uint64_t)0x5 << 16;
bits |= (uint64_t)0x127B;
s2[0] = (bits >> 32) & 0xFF;
s2[1] = (bits >> 24) & 0xFF;
s2[2] = (bits >> 16) & 0xFF;
s2[3] = (bits >> 8) & 0xFF;
s2[4] = bits & 0xFF;
memcpy(p, s2, 5);
p += 5;
}
// Build extra BIW words (max 3 slots)
uint32_t extra_biw[4];
int extra_count = 0;
// Slot priority: SSID1 first (always when enabled), then Time, Date, TZ, SSID2
if (bp.send_ssid1 && extra_count < 3)
extra_biw[extra_count++] = flex_biw_ssid1(bp.local_id, bp.coverage_zone);
if (bp.send_time && extra_count < 3) {
uint32_t sec_step = (uint32_t)(bp.second * 2 / 15); // 7.5s steps
if (sec_step > 7) sec_step = 7;
extra_biw[extra_count++] = flex_biw_time(bp.hour, bp.minute, sec_step);
}
if (bp.send_date && extra_count < 3) {
uint32_t year_field = (uint32_t)(bp.year - 1994);
extra_biw[extra_count++] = flex_biw_date(year_field, bp.month, bp.day);
}
if (bp.send_tz && extra_count < 3) {
uint32_t tz_info = (uint32_t)bp.tz_code & 0x1F;
if (bp.send_dst)
tz_info |= (0U << 5); // L0=0 means DST active
else
tz_info |= (1U << 5); // L0=1 means standard time
extra_biw[extra_count++] = flex_biw_sysinfo(0x04, tz_info);
}
if (bp.send_ssid2 && extra_count < 3)
extra_biw[extra_count++] = flex_biw_ssid2(bp.country_code, 0);
uint32_t fw[88];
uint32_t mw[84];
int mwc = 0;
uint32_t num_k = 0;
if (msg_type == 0)
mwc = flex_encode_alpha(msg, mw, 84, bp.msg_number, msg_r);
else if (msg_type == 1)
mwc = flex_encode_numeric(msg, mw, 84, &num_k);
// Address encoding
int is_long = (capcode >= 2101249ULL);
int addr_words = is_long ? 2 : 1;
int vec_words = is_long ? 2 : 1;
int astart = 1 + extra_count;
int vstart = astart + addr_words;
int mstart = vstart + vec_words;
fw[0] = flex_biw1(astart, vstart, 0);
// Extra BIW words (words 1..extra_count)
for (int i = 0; i < extra_count; i++)
fw[1 + i] = extra_biw[i];
// Address words
if (is_long) {
uint32_t la[2];
if (flex_long_addr(capcode, la) < 0) return 0;
fw[astart] = la[0];
fw[astart + 1] = la[1];
} else {
fw[astart] = flex_short_addr(capcode);
}
// Vector + message
if (msg_type == 0) {
fw[vstart] = flex_alpha_vector(mstart, mwc);
if (is_long && mwc > 0) {
fw[vstart + 1] = mw[0];
for (int i = 0; i < mwc - 1 && (mstart + i) < 88; i++)
fw[mstart + i] = mw[i + 1];
mwc = (mwc > 0) ? mwc - 1 : 0;
} else {
for (int i = 0; i < mwc && (mstart + i) < 88; i++)
fw[mstart + i] = mw[i];
}
} else if (msg_type == 1) {
fw[vstart] = flex_numeric_vector(3, mstart, mwc, num_k);
if (is_long) {
fw[vstart + 1] = (mwc > 0) ? mw[0] : flex_enc(0);
for (int i = 1; i < mwc && (mstart + i - 1) < 88; i++)
fw[mstart + i - 1] = mw[i];
} else {
for (int i = 0; i < mwc && (mstart + i) < 88; i++)
fw[mstart + i] = mw[i];
}
} else {
// Type 2 = short/tone (empty msg), Type 3 = short numeric (msg digits)
std::string short_msg = (msg_type == 3) ? msg : "";
uint32_t short_vy = 0;
fw[vstart] = flex_short_vector(is_long, short_msg, &short_vy);
if (is_long)
fw[vstart + 1] = short_vy;
}
// Idle fill
int mf_words = mwc;
if (is_long && mwc > 0 && msg_type == 1)
mf_words = mwc - 1;
for (int i = mstart + mf_words; i < 88; i++)
fw[i] = (i & 1) ? 0x00000000 : 0xFFFFFFFF;
for (int blk = 0; blk < 11; blk++)
flex_interleave_block(blk, fw);
memcpy(p, fw, 88 * 4);
p += 88 * 4;
// Trailing idle
*p++ = 0xAA;
*p++ = 0xAA;
*p++ = 0xAA;
*p++ = 0xAA;
return (size_t)(p - buf);
}
// ===== ERS =====
static size_t build_ers(uint8_t* buf, int cycles) {
uint8_t* p = buf;
uint8_t ar_inv[4];
for (int i = 0; i < 4; i++) ar_inv[i] = ~ar[i];
for (int c = 0; c < cycles; c++) {
*p++ = 0xAA;
*p++ = 0xAA;
memcpy(p, ar, 4);
p += 4;
*p++ = 0x55;
*p++ = 0x55;
memcpy(p, ar_inv, 4);
p += 4;
}
return (size_t)(p - buf);
}
// ===== FlexParamsView =====
FlexParamsView::FlexParamsView(NavigationView& nav, FlexBIWParams& params)
: params_(params), nav_(nav) {
add_children({&labels,
&check_date, &field_year, &field_month, &field_day,
&check_time, &field_hour, &field_minute, &field_second,
&check_tz, &options_tz, &check_dst,
&check_ssid1, &field_local_id, &labels_cz, &field_coverage,
&check_ssid2, &field_country, &check_roaming,
&labels_msg, &field_msg_number,
&check_ers, &field_ers_count,
&button_save, &button_cancel});
// Populate from params
check_date.set_value(params_.send_date);
field_year.set_value(params_.year);
field_month.set_value(params_.month);
field_day.set_value(params_.day);
check_time.set_value(params_.send_time);
field_hour.set_value(params_.hour);
field_minute.set_value(params_.minute);
field_second.set_value(params_.second);
check_tz.set_value(params_.send_tz);
options_tz.set_by_value(params_.tz_code);
check_dst.set_value(params_.send_dst);
check_ssid1.set_value(params_.send_ssid1);
field_local_id.set_value(params_.local_id);
field_coverage.set_value(params_.coverage_zone);
check_ssid2.set_value(params_.send_ssid2);
field_country.set_value(params_.country_code);
check_roaming.set_value(params_.roaming);
field_msg_number.set_value(params_.msg_number);
check_ers.set_value(params_.send_ers);
field_ers_count.set_value(params_.ers_count);
// Roaming implies SSID1 + SSID2
check_roaming.on_select = [this](Checkbox&, bool v) {
on_roaming_changed(v);
};
button_save.on_select = [this, &nav](Button&) {
int32_t yr = field_year.value();
if (yr > 2025) {
int equiv = flex_equiv_year(yr);
nav.display_modal(
"Year > 2025",
"Valid: 1994-2025\nEquiv for " + to_string_dec_uint(yr) + ": " + to_string_dec_uint(equiv));
field_year.set_value(equiv);
return;
}
params_.send_date = check_date.value();
params_.year = yr;
params_.month = field_month.value();
params_.day = field_day.value();
params_.send_time = check_time.value();
params_.hour = field_hour.value();
params_.minute = field_minute.value();
params_.second = field_second.value();
params_.send_tz = check_tz.value();
params_.tz_code = options_tz.selected_index_value();
params_.send_dst = check_dst.value();
params_.send_ssid1 = check_ssid1.value();
params_.local_id = field_local_id.value();
params_.coverage_zone = field_coverage.value();
params_.send_ssid2 = check_ssid2.value();
params_.country_code = field_country.value();
params_.roaming = check_roaming.value();
params_.msg_number = field_msg_number.value();
params_.send_ers = check_ers.value();
params_.ers_count = field_ers_count.value();
nav.pop();
};
button_cancel.on_select = [&nav](Button&) {
nav.pop();
};
}
void FlexParamsView::on_roaming_changed(bool v) {
if (v) {
check_ssid1.set_value(true);
check_ssid2.set_value(true);
}
}
void FlexParamsView::focus() {
button_save.focus();
}
// ===== Serial message handler =====
void FlexTXView::on_serial_msg(const FlexTosendMessage data) {
field_capcode.set_value(data.capcode);
capcode_value = data.capcode;
options_type.set_selected_index(data.type);
message = std::string((char*)data.msg, data.msglen);
buffer = message;
text_message.set(message);
if (message.length() > 30 && message.length() <= 60)
text_message_l2.set(message.substr(29));
else if (message.length() > 60)
text_message_l2.set(message.substr(29, 27) + "...");
else
text_message_l2.set("");
field_capcode.dirty();
options_type.dirty();
text_message.dirty();
text_message_l2.dirty();
tx_view.focus();
if (start_tx()) tx_view.set_transmitting(true);
}
// ===== TX =====
void FlexTXView::on_tx_progress(const uint32_t progress, const bool done) {
if (done) {
if (tx_phase_ == 0) return; // stopped by user
int ers_n = tx_steps_total_ - 2;
if (tx_phase_ == 1 && ers_remaining_ > 0) {
tx_step_++;
text_capinfo.set("[" + to_string_dec_uint(tx_step_) + "/" + to_string_dec_uint(tx_steps_total_) +
"] ERS " + to_string_dec_uint(tx_step_) + "/" + to_string_dec_uint(ers_n));
uint8_t* data = shared_memory.bb_data.data;
size_t total = build_ers(data, 42);
ers_remaining_--;
uint32_t total_bits = total * 8;
progressbar.set_max(total_bits / 64);
baseband::set_fsk_data(total_bits, 2280000 / 1600, 4500, 64);
} else if (tx_phase_ == 1) {
tx_phase_ = 2;
tx_step_++;
text_capinfo.set("[" + to_string_dec_uint(tx_step_) + "/" + to_string_dec_uint(tx_steps_total_) +
"] Frame 1/2 (new)");
send_frame(1);
} else if (tx_phase_ == 2) {
tx_phase_ = 3;
tx_step_++;
text_capinfo.set("[" + to_string_dec_uint(tx_step_) + "/" + to_string_dec_uint(tx_steps_total_) +
"] Frame 2/2 (dup)");
send_frame(0);
} else {
biw_params_.msg_number = (biw_params_.msg_number + 1) & 63;
transmitter_model.disable();
progressbar.set_value(0);
tx_view.set_transmitting(false);
tx_phase_ = 0;
set_dirty(); // repaint capcode info
}
} else {
if (tx_phase_ != 0)
progressbar.set_value(progress);
}
}
bool FlexTXView::start_tx() {
uint64_t capcode = field_capcode.to_integer();
capcode_value = capcode;
if (capcode < 1 || capcode > 4297068542ULL) {
nav_.display_modal("Bad capcode", "Capcode: 1-4297068542");
return false;
}
int msg_type = options_type.selected_index();
if (msg_type == 1) {
if (message.find_first_not_of("0123456789.U -][") != std::string::npos) {
nav_.display_modal("Bad message", "Numeric: 0-9 . U - ] [ space");
return false;
}
}
transmitter_model.set_sampling_rate(2280000);
transmitter_model.set_baseband_bandwidth(1'750'000);
transmitter_model.enable();
int ers_n = (biw_params_.send_ers && biw_params_.ers_count > 0) ? biw_params_.ers_count : 0;
tx_steps_total_ = ers_n + 2;
tx_step_ = 0;
if (ers_n > 0) {
tx_phase_ = 1;
ers_remaining_ = ers_n;
tx_step_++;
text_capinfo.set("[" + to_string_dec_uint(tx_step_) + "/" + to_string_dec_uint(tx_steps_total_) +
"] ERS " + to_string_dec_uint(tx_step_) + "/" + to_string_dec_uint(ers_n));
uint8_t* data = shared_memory.bb_data.data;
size_t total = build_ers(data, 42);
ers_remaining_--;
uint32_t total_bits = total * 8;
progressbar.set_max(total_bits / 64);
baseband::set_fsk_data(total_bits, 2280000 / 1600, 4500, 64);
} else {
tx_phase_ = 2;
tx_step_++;
text_capinfo.set("[" + to_string_dec_uint(tx_step_) + "/" + to_string_dec_uint(tx_steps_total_) +
"] Frame 1/2 (new)");
send_frame(1);
}
return true;
}
void FlexTXView::send_frame(uint32_t msg_r) {
uint64_t capcode = field_capcode.to_integer();
int msg_type = options_type.selected_index();
uint8_t* data = shared_memory.bb_data.data;
size_t total = 0;
total += build_ers(data + total, 8);
total += build_frame(data + total, capcode, msg_type, message, 0, 0, msg_r, biw_params_);
uint32_t total_bits = total * 8;
progressbar.set_max(total_bits / 64);
baseband::set_fsk_data(total_bits, 2280000 / 1600, 4500, 64);
}
// ===== UI =====
void FlexTXView::focus() {
field_capcode.focus();
}
FlexTXView::~FlexTXView() {
transmitter_model.disable();
baseband::shutdown();
}
void FlexTXView::paint(Painter&) {
message = buffer;
text_message.set(message);
if (message.length() > 30 && message.length() <= 60)
text_message_l2.set(message.substr(29));
else if (message.length() > 60)
text_message_l2.set(message.substr(29, 27) + "...");
else
text_message_l2.set("");
// Capcode info line
uint64_t cap = field_capcode.to_integer();
std::string info;
if (cap == 0) {
info = "Invalid";
} else if (cap <= 1933312ULL) {
info = "Short addr";
} else if (cap >= 2062336ULL && cap <= 2062351ULL) {
info = "Temp grp #" + to_string_dec_uint(cap - 2062336ULL);
} else if (cap >= 2062352ULL && cap <= 2062367ULL) {
info = "Operator msg";
} else if (cap >= 2058240ULL && cap <= 2062335ULL) {
info = "Network addr";
} else if (cap >= 2041856ULL && cap <= 2058239ULL) {
info = "Info service";
} else if (cap > 1933312ULL && cap < 2101249ULL) {
info = "Reserved";
} else if (cap >= 2101249ULL && cap <= 4297068542ULL) {
info = "Long addr";
} else {
info = "Invalid";
}
// Computed frame/phase for all valid addresses
if (cap >= 1 && cap <= 4297068542ULL) {
static const char ph[] = "ABCD";
int frame = (int)((cap / 16) % 128);
int phase = (int)((cap / 4) % 4);
info += ", F" + to_string_dec_uint(frame) +
" " + std::string(1, ph[phase]);
}
text_capinfo.set(info);
}
void FlexTXView::on_set_text(NavigationView& nav) {
text_prompt(nav, buffer, MAX_FLEX_MSG, ENTER_KEYBOARD_MODE_ALPHA);
}
FlexTXView::FlexTXView(NavigationView& nav)
: nav_(nav) {
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
// Init random msg number from RTC
{
rtc::RTC datetime;
rtc_time::now(datetime);
int seed = datetime.second() + datetime.minute() * 7 + datetime.hour();
biw_params_.msg_number = seed & 63;
if (biw_params_.msg_number == 0)
biw_params_.msg_number = 1;
}
// Always populate date/time/dst from RTC
{
rtc::RTC datetime;
rtc_time::now(datetime);
int real_year = datetime.year();
biw_params_.year = flex_equiv_year(real_year);
biw_params_.month = datetime.month();
biw_params_.day = datetime.day();
biw_params_.hour = datetime.hour();
biw_params_.minute = datetime.minute();
biw_params_.second = datetime.second();
biw_params_.send_dst = portapack::persistent_memory::dst_enabled() ? 1 : 0;
}
add_children({&labels, &text_capinfo, &field_capcode, &options_speed, &options_type,
&text_message, &text_message_l2,
&button_message, &button_params, &progressbar, &tx_view});
options_speed.set_selected_index(0);
options_type.set_selected_index(0);
field_capcode.set_value(capcode_value);
field_capcode.on_change = [this](SymField&) {
set_dirty(); // trigger repaint to update capcode info text
};
button_message.on_select = [this, &nav](Button&) {
this->on_set_text(nav);
};
button_params.on_select = [this, &nav](Button&) {
nav.push<FlexParamsView>(biw_params_);
};
tx_view.on_edit_frequency = [this, &nav]() {
auto new_view =
nav.push<FrequencyKeypadView>(transmitter_model.target_frequency());
new_view->on_changed = [this](rf::Frequency f) {
transmitter_model.set_target_frequency(f);
};
};
tx_view.on_start = [this]() {
if (start_tx()) tx_view.set_transmitting(true);
};
tx_view.on_stop = [this]() {
tx_phase_ = 0;
tx_view.set_transmitting(false);
transmitter_model.disable();
progressbar.set_value(0);
set_dirty(); // repaint capcode info
};
}
} // namespace ui::external_app::flex_tx
+251
View File
@@ -0,0 +1,251 @@
#ifndef __UI_FLEX_TX_H__
#define __UI_FLEX_TX_H__
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "ui_transmitter.hpp"
#include "message.hpp"
#include "transmitter_model.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
namespace ui::external_app::flex_tx {
struct FlexBIWParams {
int32_t send_date{1};
int32_t send_time{1};
int32_t send_tz{1};
int32_t send_dst{0};
int32_t send_ssid1{0};
int32_t send_ssid2{0};
int32_t roaming{0};
int32_t year{2015};
int32_t month{1};
int32_t day{1};
int32_t hour{0};
int32_t minute{0};
int32_t second{0};
int32_t tz_code{0};
int32_t local_id{0};
int32_t coverage_zone{0};
int32_t country_code{0};
int32_t msg_number{0};
int32_t send_ers{1};
int32_t ers_count{1};
};
class FlexParamsView : public View {
public:
FlexParamsView(NavigationView& nav, FlexBIWParams& params);
std::string title() const override { return "FLEX Params"; };
void focus() override;
private:
FlexBIWParams& params_;
NavigationView& nav_;
void on_roaming_changed(bool v);
Labels labels{
{{12 * 8, 1 * 16}, "-", Theme::getInstance()->fg_light->foreground},
{{15 * 8, 1 * 16}, "-", Theme::getInstance()->fg_light->foreground},
{{10 * 8, 2 * 16}, ":", Theme::getInstance()->fg_light->foreground},
{{13 * 8, 2 * 16}, ":", Theme::getInstance()->fg_light->foreground},
};
Checkbox check_date{{0 * 8, 1 * 16}, 4, "Date", true};
NumberField field_year{{8 * 8, 1 * 16}, 4, {1994, 2099}, 1, '0', true};
NumberField field_month{{13 * 8, 1 * 16}, 2, {1, 12}, 1, '0', true};
NumberField field_day{{16 * 8, 1 * 16}, 2, {1, 31}, 1, '0', true};
Checkbox check_time{{0 * 8, 2 * 16}, 4, "Time", true};
NumberField field_hour{{8 * 8, 2 * 16}, 2, {0, 23}, 1, '0', true};
NumberField field_minute{{11 * 8, 2 * 16}, 2, {0, 59}, 1, '0', true};
NumberField field_second{{14 * 8, 2 * 16}, 2, {0, 59}, 1, '0', true};
Checkbox check_tz{{0 * 8, 3 * 16}, 2, "TZ", true};
OptionsField options_tz{
{6 * 8, 3 * 16},
9,
{{"UTC+0 ", 0},
{"UTC+1 ", 1},
{"UTC+2 ", 2},
{"UTC+3 ", 3},
{"UTC+4 ", 4},
{"UTC+5 ", 5},
{"UTC+6 ", 6},
{"UTC+7 ", 7},
{"UTC+8 ", 8},
{"UTC+9 ", 9},
{"UTC+10 ", 10},
{"UTC+11 ", 11},
{"UTC+12 ", 12},
{"UTC+3:30", 13},
{"UTC+4:30", 14},
{"UTC+5:30", 15},
{"UTC+5:45", 17},
{"UTC+6:30", 18},
{"UTC+9:30", 19},
{"UTC-3:30", 20},
{"UTC-11 ", 21},
{"UTC-10 ", 22},
{"UTC-9 ", 23},
{"UTC-8 ", 24},
{"UTC-7 ", 25},
{"UTC-6 ", 26},
{"UTC-5 ", 27},
{"UTC-4 ", 28},
{"UTC-3 ", 29},
{"UTC-2 ", 30},
{"UTC-1 ", 31}}};
Checkbox check_dst{{18 * 8, 3 * 16}, 3, "DST", true};
Checkbox check_ssid1{{0 * 8, 5 * 16}, 5, "LocID", true};
NumberField field_local_id{{9 * 8, 5 * 16}, 3, {0, 511}, 1, '0'};
Labels labels_cz{
{{12 * 8, 5 * 16}, "CovZone", Theme::getInstance()->fg_light->foreground},
};
NumberField field_coverage{{20 * 8, 5 * 16}, 2, {0, 31}, 1, '0'};
Checkbox check_ssid2{{0 * 8, 6 * 16}, 11, "CountryCode", true};
NumberField field_country{{15 * 8, 6 * 16}, 4, {0, 1023}, 1, '0'};
Checkbox check_roaming{{0 * 8, 7 * 16}, 4, "Roam", true};
Labels labels_msg{
{{0 * 8, 9 * 16}, "Msg#:", Theme::getInstance()->fg_light->foreground},
};
NumberField field_msg_number{{5 * 8, 9 * 16}, 2, {0, 63}, 1, '0'};
Checkbox check_ers{{0 * 8, 10 * 16}, 3, "ERS", true};
NumberField field_ers_count{{8 * 8, 10 * 16}, 2, {1, 10}, 1, ' '};
Button button_save{{1 * 8, 12 * 16, 12 * 8, 32}, "Save"};
Button button_cancel{{16 * 8, 12 * 16, 12 * 8, 32}, "Cancel"};
};
class FlexTXView : public View {
public:
FlexTXView(NavigationView& nav);
~FlexTXView();
FlexTXView(const FlexTXView&) = delete;
FlexTXView& operator=(const FlexTXView&) = delete;
void focus() override;
void paint(Painter&) override;
std::string title() const override { return "FLEX TX"; };
FlexBIWParams biw_params_{};
private:
std::string buffer{"FLEX TEST"};
std::string message{};
NavigationView& nav_;
int tx_phase_{0};
int ers_remaining_{0};
int tx_step_{0};
int tx_steps_total_{0};
int64_t capcode_value{1000};
TxRadioState radio_state_{
931740000 /* frequency */,
1750000 /* bandwidth */,
2280000 /* sampling rate */
};
app_settings::SettingsManager settings_{
"tx_flex",
app_settings::Mode::TX,
{{"capcode", &capcode_value},
{"biw_date", &biw_params_.send_date},
{"biw_time", &biw_params_.send_time},
{"biw_tz", &biw_params_.send_tz},
{"biw_ssid1", &biw_params_.send_ssid1},
{"biw_ssid2", &biw_params_.send_ssid2},
{"biw_roam", &biw_params_.roaming},
{"biw_tzc", &biw_params_.tz_code},
{"biw_lid", &biw_params_.local_id},
{"biw_cz", &biw_params_.coverage_zone},
{"biw_cc", &biw_params_.country_code},
{"biw_ers", &biw_params_.send_ers},
{"biw_ersc", &biw_params_.ers_count}}};
void on_set_text(NavigationView& nav);
void on_tx_progress(const uint32_t progress, const bool done);
void on_serial_msg(const FlexTosendMessage data);
bool start_tx();
void send_frame(uint32_t msg_r);
Labels labels{
{{1 * 8, 4 * 8}, "Capcode:", Theme::getInstance()->fg_light->foreground},
{{3 * 8, 6 * 8}, "Speed:", Theme::getInstance()->fg_light->foreground},
{{4 * 8, 8 * 8}, "Type:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), 12 * 8}, "Message:", Theme::getInstance()->fg_light->foreground}};
Text text_capinfo{
{UI_POS_X(0), 2 * 8, screen_width, 16},
""};
SymField field_capcode{
{10 * 8, 4 * 8},
10};
OptionsField options_speed{
{10 * 8, 6 * 8},
10,
{{"1600/2FSK ", 0}}};
OptionsField options_type{
{10 * 8, 8 * 8},
14,
{{"Alphanumeric ", 0},
{"Numeric ", 1},
{"Short/tone ", 2},
{"Short numeric", 3}}};
Text text_message{
{UI_POS_X(0), 14 * 8, screen_width, 16},
""};
Text text_message_l2{
{UI_POS_X(0), 16 * 8, screen_width, 16},
""};
Button button_message{
{UI_POS_X(0), 18 * 8, 13 * 8, 32},
"Set message"};
Button button_params{
{14 * 8, 18 * 8, 13 * 8, 32},
"Set params"};
ProgressBar progressbar{
{16, 210, UI_POS_WIDTH_REMAINING(4), 16}};
TransmitterView tx_view{
(int16_t)UI_POS_Y_BOTTOM(4),
10000,
9};
MessageHandlerRegistration message_handler_tx_progress{
Message::ID::TXProgress,
[this](const Message* const p) {
const auto message =
*reinterpret_cast<const TXProgressMessage*>(p);
this->on_tx_progress(message.progress, message.done);
}};
MessageHandlerRegistration message_handler_flex_tosend{
Message::ID::FlexTosend,
[this](const Message* const p) {
const auto message =
*reinterpret_cast<const FlexTosendMessage*>(p);
this->on_serial_msg(message);
}};
};
} // namespace ui::external_app::flex_tx
#endif
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_flippertx.application_information"), u
0xE0,
0x07,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
+5 -5
View File
@@ -165,7 +165,7 @@ FmRadioView::FmRadioView(NavigationView& nav)
&gr});
txt_save_help.set_focusable(false);
txt_save_help.visible(false);
txt_save_help.hidden(true);
for (uint8_t i = 0; i < 12; ++i) {
if (freq_fav_list[i].frequency == 0) {
freq_fav_list[i].frequency = 87000000;
@@ -195,7 +195,7 @@ FmRadioView::FmRadioView(NavigationView& nav)
btn_fav_save.on_select = [this](Button&) {
save_fav = !save_fav;
txt_save_help.set_text(save_fav ? "Select slot" : "");
txt_save_help.visible(save_fav);
txt_save_help.hidden(!save_fav);
txt_save_help.set_dirty();
};
@@ -229,9 +229,9 @@ void FmRadioView::on_btn_clicked(uint8_t i) {
freq_fav_list[i].modulation = field_modulation.selected_index_value();
freq_fav_list[i].bandwidth = radio_bw;
update_fav_btn_texts();
txt_save_help.visible(save_fav);
txt_save_help.hidden(true);
txt_save_help.set_text("");
txt_save_help.set_dirty();
set_dirty();
return;
}
field_frequency.set_value(freq_fav_list[i].frequency);
@@ -266,7 +266,7 @@ FmRadioView::~FmRadioView() {
}
void FmRadioView::on_audio_spectrum() {
if (gr.visible() && audio_spectrum_data) gr.update_audio_spectrum(*audio_spectrum_data);
if (gr.drawn() && audio_spectrum_data) gr.update_audio_spectrum(*audio_spectrum_data);
if (audio_spectrum_data && audio_spectrum_data->db.size() <= 128) {
for (size_t i = 0; i < audio_spectrum_data->db.size(); ++i) {
audio_spectrum[i] = ((int16_t)audio_spectrum_data->db[i] - 127) * 256;
+65
View File
@@ -0,0 +1,65 @@
// Author: berkeozkir (Berke Özkır)
#include "ui.hpp"
#include "ui_fpv_detect.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::fpv_detect {
void initialize_app(ui::NavigationView& nav) {
nav.push<FpvDetectView>();
}
} // namespace ui::external_app::fpv_detect
extern "C" {
__attribute__((section(".external_app.app_fpv_detect.application_information"), used)) application_information_t _application_information_fpv_detect = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::fpv_detect::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "FPV DETECT",
/*.bitmap_data = */
{
0x00,
0x00,
0xC0,
0x03,
0x20,
0x04,
0x10,
0x08,
0x48,
0x12,
0xA4,
0x25,
0x54,
0x2A,
0xA8,
0x15,
0x54,
0x2A,
0xA4,
0x25,
0x48,
0x12,
0x10,
0x08,
0x20,
0x04,
0xC0,
0x03,
0x00,
0x00,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_wfm_audio */ {'P', 'W', 'F', 'M'},
/*.m4_app_offset = */ 0x00000000,
};
}
@@ -0,0 +1,664 @@
// Author: berkeozkir (Berke Özkır)
/*
* FPV RX how frequency search and lock work
*
* 1. Power metric: We use channelized power that portapack RSSI algo included.
*
* 2. Scanning: We step through FPV bands/channels (A/B/E/F/R, 8 ch each). When
* power on the current channel exceeds the detect threshold, we enter
* "Candidate" and run verification - with some edge detecting algo.
*
* 3. Verification (making sure the drone is on that freq):
* - Multiple samples: verify_hits / verify_misses over several updates.
* - Confidence score: combines average above threshold, peak margin,
* hit count, and crucially neighbor_margin = center power max(adjacent ch).
* - Neighbor check: we only lock if the center channel is at least
* MIN_NEIGHBOR_MARGIN_FOR_LOCK_DB above both adjacent channels. That
* avoids locking on wide/noise that looks strong on many channels.
* During Candidate we re-sample left/right adjacent channels so the
* margin is based on current measurements, not stale scan data.
* - Lock requires: enough hits, confidence LOCK_CONFIDENCE_MIN, and
* center stronger than neighbors (strong lock path has same requirement).
*
* 4. Lock hold: Once locked, we only unlock when power stays below
* unlock_threshold_db() long enough to drain lock_hold_ (down from
* LOCK_HOLD_MAX), so brief fades don't drop lock.
*/
#include "ui_fpv_detect.hpp"
#include <cstdio>
#include "baseband_api.hpp"
#include "oversample.hpp"
using namespace portapack;
namespace ui::external_app::fpv_detect {
static constexpr uint8_t SCAN_DWELL_FRAMES = 1;
static constexpr uint8_t VERIFY_SAMPLE_TARGET = 5;
static constexpr uint8_t VERIFY_MIN_HITS = 4;
static constexpr uint8_t STRONG_LOCK_PEAK_MARGIN_DB = 8;
static constexpr uint8_t LOCK_HOLD_MAX = 12;
static constexpr uint8_t LOCK_CONFIDENCE_MIN = 72;
/** Center channel must be at least this many dB above adjacent channels to lock.
* Ensures we lock on a real FPV carrier (narrow peak) rather than wide/noise. */
static constexpr int32_t MIN_NEIGHBOR_MARGIN_FOR_LOCK_DB = 3;
static constexpr uint8_t BEEP_GUARD_FRAMES = 8;
int32_t FpvDetectView::clamp_value(int32_t value, int32_t low, int32_t high) {
if (value < low) return low;
if (value > high) return high;
return value;
}
int32_t FpvDetectView::map_value(int32_t value, int32_t from_low, int32_t from_high, int32_t to_low, int32_t to_high) {
const auto clamped = clamp_value(value, from_low, from_high);
return to_low + (clamped - from_low) * (to_high - to_low) / (from_high - from_low);
}
void FpvDetectView::focus() {
field_lna.focus();
}
FpvDetectView::~FpvDetectView() {
shared_memory.request_m4_performance_counter = 0;
receiver_model.disable();
audio::output::stop();
baseband::shutdown();
}
uint8_t FpvDetectView::channel_index(uint8_t band, uint8_t ch) const {
return static_cast<uint8_t>(band * FPV_CHANNELS_PER_BAND + ch);
}
uint8_t FpvDetectView::current_channel_index() const {
return channel_index(scan_band, scan_ch);
}
int16_t FpvDetectView::detect_threshold_db() const {
return static_cast<int16_t>(detect_threshold_db_);
}
int16_t FpvDetectView::unlock_threshold_db() const {
return static_cast<int16_t>(detect_threshold_db() - 6);
}
int16_t FpvDetectView::candidate_average_db() const {
if (!verify_samples_) {
return -120;
}
return static_cast<int16_t>(verify_sum_db_ / verify_samples_);
}
int16_t FpvDetectView::neighbor_best_db() const {
int16_t best = -120;
if (candidate_ch_ > 0) {
const auto& left = channel_memory_[channel_index(candidate_band_, static_cast<uint8_t>(candidate_ch_ - 1))];
if (left.last_db > best) {
best = left.last_db;
}
}
if ((candidate_ch_ + 1) < FPV_CHANNELS_PER_BAND) {
const auto& right = channel_memory_[channel_index(candidate_band_, static_cast<uint8_t>(candidate_ch_ + 1))];
if (right.last_db > best) {
best = right.last_db;
}
}
return best;
}
void FpvDetectView::request_event_beep(uint32_t hz, uint32_t duration_ms) {
if ((frame_counter_ - last_beep_frame_) < BEEP_GUARD_FRAMES) {
return;
}
last_beep_frame_ = frame_counter_;
baseband::request_audio_beep(hz, 24000, duration_ms);
}
void FpvDetectView::retune_to(uint8_t band, uint8_t ch) {
scan_band = band;
scan_ch = ch;
freq_ = fpv_frequencies[band][ch];
receiver_model.set_target_frequency(freq_);
update_freq_display();
}
void FpvDetectView::step_scan() {
if (band_mode < FPV_NUM_BANDS) {
scan_band = band_mode;
scan_ch = static_cast<uint8_t>((scan_ch + 1) % FPV_CHANNELS_PER_BAND);
} else {
scan_ch = static_cast<uint8_t>(scan_ch + 1);
if (scan_ch >= FPV_CHANNELS_PER_BAND) {
scan_ch = 0;
scan_band = static_cast<uint8_t>(scan_band + 1);
if (scan_band >= FPV_NUM_BANDS) {
scan_band = 0;
}
}
}
retune_to(scan_band, scan_ch);
scan_dwell_frames_ = SCAN_DWELL_FRAMES;
}
void FpvDetectView::reset_detector(bool retune_current) {
detect_state_ = DetectState::Scanning;
candidate_band_ = scan_band;
candidate_ch_ = scan_ch;
verify_samples_ = 0;
verify_hits_ = 0;
verify_misses_ = 0;
verify_sum_db_ = 0;
verify_peak_db_ = -120;
candidate_confidence_ = 0;
lock_hold_ = 0;
neighbor_phase_ = 0;
neighbors_fresh_ = false;
scan_dwell_frames_ = 0;
update_state_badge();
update_confidence_text();
update_status_text();
update_detail_text();
update_visual_state();
if (retune_current) {
retune_to(scan_band, scan_ch);
scan_dwell_frames_ = SCAN_DWELL_FRAMES;
}
}
bool FpvDetectView::is_possible_freq_spike(const ChannelStatistics& statistics) const {
return statistics.max_db >= detect_threshold_db();
}
uint8_t FpvDetectView::compute_candidate_confidence() const {
if (!verify_samples_) {
return 0;
}
const int32_t avg_db = candidate_average_db();
const int32_t center_margin = avg_db - detect_threshold_db();
const int32_t peak_margin = verify_peak_db_ - detect_threshold_db();
const int32_t neighbor_margin = avg_db - neighbor_best_db();
int32_t score = 18;
score += center_margin * 7;
score += peak_margin * 4;
score += static_cast<int32_t>(verify_hits_) * 5;
score -= static_cast<int32_t>(verify_misses_) * 10;
if (neighbor_margin >= 6) {
score += 12;
} else if (neighbor_margin >= 3) {
score += 6;
} else if (neighbor_margin <= 0) {
score -= 8;
}
const auto& mem = channel_memory_[channel_index(candidate_band_, candidate_ch_)];
if (mem.hits >= 2) {
score += 4;
}
return static_cast<uint8_t>(clamp_value(score, 0, 99));
}
void FpvDetectView::enter_candidate(const ChannelStatistics& statistics) {
detect_state_ = DetectState::Candidate;
candidate_band_ = scan_band;
candidate_ch_ = scan_ch;
verify_samples_ = 1;
verify_hits_ = 1;
verify_misses_ = 0;
verify_sum_db_ = statistics.max_db;
verify_peak_db_ = statistics.max_db;
candidate_confidence_ = compute_candidate_confidence();
neighbor_phase_ = 0;
neighbors_fresh_ = false;
retune_to(candidate_band_, candidate_ch_);
update_state_badge();
update_confidence_text();
update_status_text();
update_detail_text();
update_visual_state();
request_event_beep(1150, 60);
}
void FpvDetectView::evaluate_candidate_sample(const ChannelStatistics& statistics) {
if (detect_state_ != DetectState::Candidate) {
return;
}
++verify_samples_;
verify_sum_db_ += statistics.max_db;
if (statistics.max_db > verify_peak_db_) {
verify_peak_db_ = statistics.max_db;
}
if (statistics.max_db >= detect_threshold_db()) {
++verify_hits_;
} else {
++verify_misses_;
}
candidate_confidence_ = compute_candidate_confidence();
update_confidence_text();
update_detail_text();
/* Refresh adjacent channel power so neighbor_best_db() uses current
* measurements instead of stale scan data. Do this before any lock decision. */
if (verify_samples_ >= 2 && !neighbors_fresh_) {
if (candidate_ch_ > 0) {
neighbor_phase_ = 1;
retune_to(candidate_band_, static_cast<uint8_t>(candidate_ch_ - 1));
} else {
neighbor_phase_ = 2;
retune_to(candidate_band_, static_cast<uint8_t>(candidate_ch_ + 1));
}
return;
}
/* Lock decisions use neighbor margin; only run when we have fresh neighbor data. */
if (!neighbors_fresh_) {
return;
}
const bool strong_lock =
verify_samples_ >= 3 &&
verify_hits_ >= 3 &&
verify_peak_db_ >= (detect_threshold_db() + STRONG_LOCK_PEAK_MARGIN_DB) &&
candidate_confidence_ >= 80 &&
(candidate_average_db() - neighbor_best_db()) >= MIN_NEIGHBOR_MARGIN_FOR_LOCK_DB;
if (strong_lock) {
enter_lock();
return;
}
if (verify_samples_ < VERIFY_SAMPLE_TARGET) {
return;
}
const bool center_stronger_than_neighbors =
(candidate_average_db() - neighbor_best_db()) >= MIN_NEIGHBOR_MARGIN_FOR_LOCK_DB;
if (verify_hits_ >= VERIFY_MIN_HITS && candidate_confidence_ >= LOCK_CONFIDENCE_MIN &&
center_stronger_than_neighbors) {
enter_lock();
return;
}
detect_state_ = DetectState::Scanning;
candidate_confidence_ = static_cast<uint8_t>(candidate_confidence_ / 2);
verify_samples_ = 0;
verify_hits_ = 0;
verify_misses_ = 0;
verify_sum_db_ = 0;
verify_peak_db_ = -120;
scan_dwell_frames_ = 0;
update_state_badge();
update_confidence_text();
update_status_text();
update_detail_text();
update_visual_state();
}
void FpvDetectView::enter_lock() {
detect_state_ = DetectState::Locked;
lock_hold_ = LOCK_HOLD_MAX;
candidate_confidence_ = static_cast<uint8_t>(clamp_value(candidate_confidence_, LOCK_CONFIDENCE_MIN, 99));
retune_to(candidate_band_, candidate_ch_);
update_state_badge();
update_confidence_text();
update_status_text();
update_detail_text();
update_visual_state();
request_event_beep(1850, 180);
}
void FpvDetectView::update_lock(const ChannelStatistics& statistics) {
if (detect_state_ != DetectState::Locked) {
return;
}
if (statistics.max_db >= unlock_threshold_db()) {
if (lock_hold_ < LOCK_HOLD_MAX) {
++lock_hold_;
}
if (candidate_confidence_ < 99) {
++candidate_confidence_;
}
} else {
if (lock_hold_ > 0) {
--lock_hold_;
}
if (candidate_confidence_ > 0) {
--candidate_confidence_;
}
}
update_confidence_text();
update_detail_text();
if (lock_hold_ > 0) {
return;
}
detect_state_ = DetectState::Scanning;
candidate_confidence_ = 0;
verify_samples_ = 0;
verify_hits_ = 0;
verify_misses_ = 0;
verify_sum_db_ = 0;
verify_peak_db_ = -120;
scan_dwell_frames_ = 0;
update_state_badge();
update_confidence_text();
update_status_text();
update_detail_text();
update_visual_state();
request_event_beep(650, 90);
}
void FpvDetectView::update_freq_display() {
char buf[28];
std::snprintf(buf, sizeof(buf), "%c%d %ld MHz",
band_labels[scan_band],
static_cast<int>(scan_ch + 1),
static_cast<long>(freq_ / 1000000LL));
text_freq.set(buf);
}
void FpvDetectView::update_state_badge() {
switch (detect_state_) {
case DetectState::Scanning:
text_state.set("SCANNING");
break;
case DetectState::Candidate:
text_state.set("CHECKING");
break;
case DetectState::Locked:
text_state.set("FREQ FOUND");
break;
}
}
void FpvDetectView::update_confidence_text() {
char buf[16];
std::snprintf(buf, sizeof(buf), "Posi %u%%", static_cast<unsigned>(candidate_confidence_));
text_confidence.set(buf);
}
void FpvDetectView::update_status_text() {
char buf[40];
switch (detect_state_) {
case DetectState::Scanning:
if (band_mode < FPV_NUM_BANDS) {
std::snprintf(buf, sizeof(buf), "Scanning band %c", band_labels[band_mode]);
} else {
std::snprintf(buf, sizeof(buf), "Scanning all from list");
}
break;
case DetectState::Candidate:
std::snprintf(buf, sizeof(buf), "CHKING %c%d %ld MHz",
band_labels[candidate_band_],
static_cast<int>(candidate_ch_ + 1),
static_cast<long>(fpv_frequencies[candidate_band_][candidate_ch_] / 1000000LL));
break;
case DetectState::Locked:
std::snprintf(buf, sizeof(buf), "FREQ FOUND %c%d %ld",
band_labels[candidate_band_],
static_cast<int>(candidate_ch_ + 1),
static_cast<long>(fpv_frequencies[candidate_band_][candidate_ch_] / 1000000LL));
break;
}
text_status.set(buf);
}
void FpvDetectView::update_detail_text() {
char buf[40];
switch (detect_state_) {
case DetectState::Scanning:
std::snprintf(buf, sizeof(buf), "Need >= %d dB, stable dwell", static_cast<int>(detect_threshold_db()));
break;
case DetectState::Candidate:
std::snprintf(buf, sizeof(buf), "avg %d peak %d hits %u/%u",
static_cast<int>(candidate_average_db()),
static_cast<int>(verify_peak_db_),
static_cast<unsigned>(verify_hits_),
static_cast<unsigned>(verify_samples_));
break;
case DetectState::Locked:
std::snprintf(buf, sizeof(buf), "LOCKED %c%d posi %u%% hold %u",
band_labels[candidate_band_],
static_cast<int>(candidate_ch_ + 1),
static_cast<unsigned>(candidate_confidence_),
static_cast<unsigned>(lock_hold_));
break;
}
text_detail.set(buf);
}
void FpvDetectView::update_visual_state() {
auto* theme = Theme::getInstance();
/*
* Conservative styling for cross-branch compatibility.
* If your branch has explicit blue/red banner theme styles,
* swap the styles in this function only.
*/
auto normal_style = theme->bg_darkest;
auto attention_style = theme->fg_red;
switch (detect_state_) {
case DetectState::Scanning:
text_state.set_style(normal_style);
text_status.set_style(normal_style);
break;
case DetectState::Candidate:
text_state.set_style(normal_style);
text_status.set_style(normal_style);
break;
case DetectState::Locked:
text_state.set_style(attention_style);
text_status.set_style(attention_style);
break;
}
freq_stats_rssi.set_style(normal_style);
freq_stats_db.set_style(normal_style);
text_detail.set_style(normal_style);
text_confidence.set_style(normal_style);
}
void FpvDetectView::update_stats_text(const ChannelStatistics& statistics) {
rssi_graph.add_values(rssi.get_min(), rssi.get_avg(), rssi.get_max(), statistics.max_db);
auto& mem = channel_memory_[current_channel_index()];
mem.last_db = statistics.max_db;
if (statistics.max_db > mem.peak_db) {
mem.peak_db = statistics.max_db;
}
if (statistics.max_db >= detect_threshold_db()) {
if (mem.hits < 255) {
++mem.hits;
}
}
mem.confidence = candidate_confidence_;
if (last_max_db_ != statistics.max_db) {
last_max_db_ = statistics.max_db;
char power_buf[20];
std::snprintf(power_buf, sizeof(power_buf), "PWR %d dB", static_cast<int>(statistics.max_db));
freq_stats_db.set(power_buf);
rssi.set_db(statistics.max_db);
}
const uint8_t graph_min = rssi_graph.get_graph_min();
const uint8_t graph_avg = rssi_graph.get_graph_avg();
const uint8_t graph_max = rssi_graph.get_graph_max();
if (last_min_rssi_ != graph_min || last_avg_rssi_ != graph_avg || last_max_rssi_ != graph_max) {
last_min_rssi_ = graph_min;
last_avg_rssi_ = graph_avg;
last_max_rssi_ = graph_max;
char rssi_buf[22];
std::snprintf(rssi_buf, sizeof(rssi_buf), "RSSI %u/%u/%u",
static_cast<unsigned>(graph_min),
static_cast<unsigned>(graph_avg),
static_cast<unsigned>(graph_max));
freq_stats_rssi.set(rssi_buf);
}
}
void FpvDetectView::on_timer() {
++frame_counter_;
if (detect_state_ != DetectState::Scanning) {
return;
}
if (scan_dwell_frames_ > 0) {
--scan_dwell_frames_;
return;
}
step_scan();
}
FpvDetectView::FpvDetectView(NavigationView& nav)
: nav_{nav} {
add_children({
&labels,
&field_lna,
&field_vga,
&field_rf_amp,
&field_volume,
&field_band,
&text_freq,
&text_state,
&text_confidence,
&text_detect_label,
&field_detect_threshold,
&freq_stats_rssi,
&freq_stats_db,
&text_status,
&text_detail,
&rssi,
&rssi_graph,
});
rssi.set_vertical_rssi(true);
rssi.set_peak(true, 3000);
rssi_graph.set_nb_columns(256);
field_detect_threshold.set_value(detect_threshold_db_);
field_detect_threshold.on_change = [this](int32_t v) {
detect_threshold_db_ = v;
update_detail_text();
};
field_band.on_change = [this](size_t, int32_t value) {
band_mode = static_cast<uint8_t>(value);
scan_band = (band_mode < FPV_NUM_BANDS) ? band_mode : 0;
scan_ch = 0;
reset_detector(true);
};
change_mode();
field_band.set_selected_index(FPV_AUTO_SCAN_MODE);
reset_detector(true);
}
void FpvDetectView::on_statistics_update(const ChannelStatistics& statistics) {
const bool is_sampling_neighbor =
(detect_state_ == DetectState::Candidate && (neighbor_phase_ == 1 || neighbor_phase_ == 2));
if (!is_sampling_neighbor) {
update_stats_text(statistics);
}
switch (detect_state_) {
case DetectState::Scanning:
if (is_possible_freq_spike(statistics)) {
enter_candidate(statistics);
}
break;
case DetectState::Candidate:
if (neighbor_phase_ == 1) {
const auto idx = channel_index(candidate_band_, static_cast<uint8_t>(candidate_ch_ - 1));
channel_memory_[idx].last_db = statistics.max_db;
if (candidate_ch_ + 1 < FPV_CHANNELS_PER_BAND) {
neighbor_phase_ = 2;
retune_to(candidate_band_, static_cast<uint8_t>(candidate_ch_ + 1));
} else {
neighbor_phase_ = 0;
neighbors_fresh_ = true;
retune_to(candidate_band_, candidate_ch_);
}
break;
}
if (neighbor_phase_ == 2) {
const auto idx = channel_index(candidate_band_, static_cast<uint8_t>(candidate_ch_ + 1));
channel_memory_[idx].last_db = statistics.max_db;
neighbor_phase_ = 0;
neighbors_fresh_ = true;
retune_to(candidate_band_, candidate_ch_);
break;
}
evaluate_candidate_sample(statistics);
break;
case DetectState::Locked:
update_lock(statistics);
break;
}
}
size_t FpvDetectView::change_mode() {
audio::output::stop();
receiver_model.disable();
baseband::shutdown();
audio_sampling_rate = audio::Rate::Hz_24000;
baseband::run_image(portapack::spi_flash::image_tag_capture);
receiver_model.set_modulation(ReceiverModel::Mode::Capture);
baseband::set_sample_rate(FPV_RX_BW, get_oversample_rate(FPV_RX_BW));
auto actual_sampling_rate = get_actual_sample_rate(FPV_RX_BW);
receiver_model.set_sampling_rate(actual_sampling_rate);
receiver_model.set_baseband_bandwidth(filter_bandwidth_for_sampling_rate(actual_sampling_rate));
audio::set_rate(audio_sampling_rate);
audio::output::start();
receiver_model.set_headphone_volume(receiver_model.headphone_volume());
receiver_model.enable();
return 0;
}
} // namespace ui::external_app::fpv_detect
@@ -0,0 +1,200 @@
// Author: berkeozkir (Berke Özkır)
#ifndef _UI_FPV_DETECT
#define _UI_FPV_DETECT
#include <array>
#include <cstdint>
#include "analog_audio_app.hpp"
#include "app_settings.hpp"
#include "audio.hpp"
#include "baseband_api.hpp"
#include "radio_state.hpp"
#include "receiver_model.hpp"
#include "string_format.hpp"
#include "ui.hpp"
#include "ui_receiver.hpp"
#include "ui_spectrum.hpp"
namespace ui::external_app::fpv_detect {
static constexpr uint8_t FPV_NUM_BANDS = 5;
static constexpr uint8_t FPV_CHANNELS_PER_BAND = 8;
static constexpr uint8_t FPV_TOTAL_CHANNELS = FPV_NUM_BANDS * FPV_CHANNELS_PER_BAND;
static constexpr uint8_t FPV_AUTO_SCAN_MODE = FPV_NUM_BANDS;
static constexpr int64_t fpv_frequencies[FPV_NUM_BANDS][FPV_CHANNELS_PER_BAND] = {
/* Band A */ {5865000000LL, 5845000000LL, 5825000000LL, 5805000000LL, 5785000000LL, 5765000000LL, 5745000000LL, 5725000000LL},
/* Band B */ {5733000000LL, 5752000000LL, 5771000000LL, 5790000000LL, 5809000000LL, 5828000000LL, 5847000000LL, 5866000000LL},
/* Band E */ {5705000000LL, 5685000000LL, 5665000000LL, 5645000000LL, 5885000000LL, 5905000000LL, 5925000000LL, 5945000000LL},
/* Band F */ {5740000000LL, 5760000000LL, 5780000000LL, 5800000000LL, 5820000000LL, 5840000000LL, 5860000000LL, 5880000000LL},
/* Band R */ {5658000000LL, 5695000000LL, 5732000000LL, 5769000000LL, 5806000000LL, 5843000000LL, 5880000000LL, 5917000000LL},
};
static constexpr char band_labels[] = {'A', 'B', 'E', 'F', 'R'};
#define FPV_RX_BW 750000
class FpvDetectView : public View {
public:
explicit FpvDetectView(NavigationView& nav);
~FpvDetectView();
void focus() override;
std::string title() const override { return "FPV DETECT"; };
private:
enum class DetectState : uint8_t {
Scanning,
Candidate,
Locked,
};
struct ChannelMemory {
int16_t last_db = -120;
int16_t peak_db = -120;
uint8_t hits = 0;
uint8_t confidence = 0;
};
NavigationView& nav_;
RxRadioState radio_state_{};
static int32_t clamp_value(int32_t value, int32_t low, int32_t high);
static int32_t map_value(int32_t value, int32_t from_low, int32_t from_high, int32_t to_low, int32_t to_high);
size_t change_mode();
void on_statistics_update(const ChannelStatistics& statistics);
void on_timer();
void retune_to(uint8_t band, uint8_t ch);
void step_scan();
void reset_detector(bool retune_current);
bool is_possible_freq_spike(const ChannelStatistics& statistics) const;
void enter_candidate(const ChannelStatistics& statistics);
void evaluate_candidate_sample(const ChannelStatistics& statistics);
void enter_lock();
void update_lock(const ChannelStatistics& statistics);
uint8_t current_channel_index() const;
uint8_t channel_index(uint8_t band, uint8_t ch) const;
uint8_t compute_candidate_confidence() const;
int16_t detect_threshold_db() const;
int16_t unlock_threshold_db() const;
int16_t candidate_average_db() const;
int16_t neighbor_best_db() const;
void request_event_beep(uint32_t hz, uint32_t duration_ms);
void update_freq_display();
void update_state_badge();
void update_confidence_text();
void update_status_text();
void update_detail_text();
void update_stats_text(const ChannelStatistics& statistics);
void update_visual_state();
DetectState detect_state_ = DetectState::Scanning;
uint8_t scan_band = 0;
uint8_t scan_ch = 0;
uint8_t band_mode = FPV_AUTO_SCAN_MODE;
uint8_t candidate_band_ = 0;
uint8_t candidate_ch_ = 0;
uint8_t verify_samples_ = 0;
uint8_t verify_hits_ = 0;
uint8_t verify_misses_ = 0;
int32_t verify_sum_db_ = 0;
int16_t verify_peak_db_ = -120;
uint8_t candidate_confidence_ = 0;
uint8_t lock_hold_ = 0;
/** During Candidate: 0=center, 1=left neighbor, 2=right neighbor. Used to
* re-sample adjacent channels so neighbor_margin uses current measurements. */
uint8_t neighbor_phase_ = 0;
bool neighbors_fresh_ = false;
uint8_t scan_dwell_frames_ = 0;
uint32_t frame_counter_ = 0;
uint32_t last_beep_frame_ = 0;
int16_t last_max_db_ = -127;
uint8_t last_min_rssi_ = 0;
uint8_t last_avg_rssi_ = 0;
uint8_t last_max_rssi_ = 0;
std::array<ChannelMemory, FPV_TOTAL_CHANNELS> channel_memory_{};
rf::Frequency freq_ = {fpv_frequencies[0][0]};
int32_t detect_threshold_db_ = -38;
audio::Rate audio_sampling_rate = audio::Rate::Hz_48000;
app_settings::SettingsManager settings_{
"rx_fpv",
app_settings::Mode::RX,
{
{"detect_threshold"sv, &detect_threshold_db_},
}};
Labels labels{
{{UI_POS_X(0), UI_POS_Y(0)}, "LNA: VGA: AMP: ", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X_RIGHT(6), UI_POS_Y(0)}, "VOL: ", Theme::getInstance()->fg_light->foreground},
};
LNAGainField field_lna{{UI_POS_X(4), UI_POS_Y(0)}};
VGAGainField field_vga{{UI_POS_X(11), UI_POS_Y(0)}};
RFAmpField field_rf_amp{{UI_POS_X(18), UI_POS_Y(0)}};
AudioVolumeField field_volume{{UI_POS_X_RIGHT(2), UI_POS_Y(0)}};
OptionsField field_band{
{UI_POS_X(0), UI_POS_Y(1)},
9,
{
{"Band A ", 0},
{"Band B ", 1},
{"Band E ", 2},
{"Band F ", 3},
{"Band R ", 4},
{"AutoScan", FPV_AUTO_SCAN_MODE},
}};
Text text_freq{{UI_POS_X_RIGHT(20), UI_POS_Y(1), UI_POS_WIDTH(20), UI_POS_DEFAULT_HEIGHT}, ""};
Text text_state{{UI_POS_X(0), UI_POS_Y(2), UI_POS_WIDTH(12), UI_POS_DEFAULT_HEIGHT}, "SCANNING"};
Text text_confidence{{UI_POS_X(12), UI_POS_Y(2), UI_POS_WIDTH(8), UI_POS_DEFAULT_HEIGHT}, "Posi 0%"};
Text text_detect_label{{UI_POS_X_RIGHT(10), UI_POS_Y(2), UI_POS_WIDTH(5), UI_POS_DEFAULT_HEIGHT}, "Thr>"};
NumberField field_detect_threshold{
{UI_POS_X_RIGHT(5), UI_POS_Y(2)},
4,
{-100, 20},
1,
' ',
};
Text freq_stats_rssi{{UI_POS_X(0), UI_POS_Y(3), UI_POS_WIDTH(15), UI_POS_DEFAULT_HEIGHT}, "RSSI 0/0/0"};
Text freq_stats_db{{UI_POS_X_RIGHT(14), UI_POS_Y(3), UI_POS_WIDTH(14), UI_POS_DEFAULT_HEIGHT}, "PWR -120 dB"};
Text text_status{{UI_POS_X(0), UI_POS_Y(4), UI_POS_WIDTH(30), UI_POS_DEFAULT_HEIGHT}, "SCANNING FOR FREQS"};
Text text_detail{{UI_POS_X(0), UI_POS_Y(5), UI_POS_WIDTH(30), UI_POS_DEFAULT_HEIGHT}, "Waiting for FPV FREQ"};
RSSIGraph rssi_graph{{UI_POS_X(0), UI_POS_Y(6), UI_POS_WIDTH_REMAINING(5), UI_POS_HEIGHT_REMAINING(7)}};
RSSI rssi{{UI_POS_X_RIGHT(5), UI_POS_Y(6), UI_POS_WIDTH(5), UI_POS_HEIGHT_REMAINING(7)}};
MessageHandlerRegistration message_handler_stats{
Message::ID::ChannelStatistics,
[this](const Message* const p) {
this->on_statistics_update(static_cast<const ChannelStatisticsMessage*>(p)->statistics);
}};
MessageHandlerRegistration message_handler_frame_sync{
Message::ID::DisplayFrameSync,
[this](const Message* const) {
this->on_timer();
}};
};
} // namespace ui::external_app::fpv_detect
#endif
+87
View File
@@ -0,0 +1,87 @@
/*
* Copyright (C) 2026 Pezsma
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui.hpp"
#include "ui_hard_reset.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::hard_reset {
void initialize_app(NavigationView& nav) {
nav.push<HardResetView>();
}
} // namespace ui::external_app::hard_reset
extern "C" {
__attribute__((section(".external_app.app_hard_reset.application_information"), used))
application_information_t _application_information_hard_reset = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::hard_reset::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "Hard Reset",
/*.bitmap_data = */ {
0x00,
0x00,
0x00,
0x00,
0xC0,
0x01,
0xFF,
0x7F,
0xFF,
0x7F,
0x56,
0x35,
0x56,
0x35,
0x56,
0x35,
0x56,
0x35,
0x56,
0x35,
0x56,
0x35,
0x56,
0x35,
0x56,
0x35,
0xFE,
0x3F,
0xFE,
0x3F,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::red().v,
/*.menu_location = */ app_location_t::SETTINGS,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_none */ {0, 0, 0, 0},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
} // extern "C"
@@ -0,0 +1,239 @@
/*
* Copyright (C) 2026 Pezsma
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui_hard_reset.hpp"
#include "portapack.hpp"
#include "file.hpp"
#include "file_path.hpp"
#include "ui_touch_calibration.hpp"
#include "ui_external_items_menu_loader.hpp"
#include "app_settings.hpp"
using namespace portapack;
namespace pmem = portapack::persistent_memory;
namespace ui::external_app::hard_reset {
HardResetView::HardResetView(ui::NavigationView& nav)
: nav_(nav) {
add_children({&chk_settings_file,
&chk_bad_apps,
&chk_pmem,
&txt_settings_file_count,
&txt_bad_apps_count,
&btn_yes,
&btn_no,
&text,
&txt_wait});
txt_wait.set_style(Theme::getInstance()->warning_dark);
btn_yes.on_select = [this](Button&) {
{ // to free painter after draw
Painter painter;
txt_wait.hidden(false);
text.hidden(true);
painter.fill_rectangle(text.screen_rect(), this->style().background);
txt_wait.paint(painter);
}
if (chk_settings_file.value()) {
clear_settings_folder();
}
if (chk_bad_apps.value()) {
delete_bad_apps(apps_dir);
}
if (chk_pmem.value()) {
pmem::cache::defaults();
StatusRefreshMessage message{};
EventDispatcher::send_message(message);
nav_.replace<TouchCalibrationView>();
} else {
nav_.pop();
}
};
btn_no.on_select = [this](Button&) {
nav_.pop();
};
txt_settings_file_count.set_style(Theme::getInstance()->fg_magenta);
txt_bad_apps_count.set_style(Theme::getInstance()->fg_magenta);
signal_token_tick_second = rtc_time::signal_tick_second += [this]() {
this->calculate();
rtc_time::signal_tick_second -= signal_token_tick_second;
};
}
HardResetView::~HardResetView() {
rtc_time::signal_tick_second -= signal_token_tick_second;
}
void HardResetView::calculate() {
settings_file_count = count_ini_files_in_directory(settings_dir);
txt_settings_file_count.set(to_string_dec_uint(settings_file_count));
bad_apps_count = count_bad_apps(apps_dir);
txt_bad_apps_count.set(to_string_dec_uint(bad_apps_count));
if (settings_file_count > 0) {
chk_settings_file.set_value(true);
}
if (bad_apps_count > 0) {
chk_bad_apps.set_value(true);
}
chk_pmem.set_value(true);
txt_wait.hidden(true);
text.set("Warning! Checked items will beerased (bad apps, P.Mem, settings). Uncheck to keep. Touch calibration is required only if P.Mem is reset.");
}
void HardResetView::focus() {
btn_no.focus();
}
uint16_t HardResetView::count_ini_files_in_directory(const std::filesystem::path& dir_path) {
int count = 0;
for (const auto& entry : std::filesystem::directory_iterator(dir_path, u"*.ini")) {
if (std::filesystem::is_regular_file(entry.status())) {
count++;
}
}
return count;
}
void HardResetView::delete_ini_files_in_directory(const std::filesystem::path& dir_path) {
bool found_and_deleted;
do {
found_and_deleted = false;
for (const auto& entry : std::filesystem::directory_iterator(dir_path, u"*.ini")) {
if (std::filesystem::is_regular_file(entry.status())) {
auto full_path = dir_path / entry.path().filename();
delete_file(full_path);
found_and_deleted = true;
break; // iterator can become invalid if the dir is modified, so break and restart the loop after deletion
}
}
} while (found_and_deleted);
}
void HardResetView::clear_settings_folder() {
delete_ini_files_in_directory(settings_dir);
}
bool HardResetView::is_bad_app(const std::filesystem::path& file_path, bool is_ppma) {
File app;
if (app.open(file_path)) {
return true;
}
bool is_bad = false;
if (is_ppma) {
application_information_t app_info = {};
auto readResult = app.read(&app_info, sizeof(application_information_t));
if (!readResult || readResult.value() != sizeof(application_information_t)) {
is_bad = true;
} else if (app_info.header_version != CURRENT_HEADER_VERSION) {
is_bad = true;
} else if (VERSION_MD5 != app_info.app_version) {
is_bad = true;
} else {
// --- CHECKSUM VALIDATION ---
// Similar to run_external_app: read through the file and calculate the checksum
app.seek(0);
uint32_t checksum = 0;
uint8_t buffer[512]; // 512-byte buffer to conserve RAM
while (true) {
auto res = app.read(buffer, sizeof(buffer));
if (!res) break;
checksum += simple_checksum((uint32_t)buffer, res.value());
if (res.value() < sizeof(buffer)) break; // End of file
}
if (checksum != EXT_APP_EXPECTED_CHECKSUM) {
is_bad = true; // The file body is corrupted / truncated!
}
}
} else {
// PPMP validation
standalone_application_information_t app_info = {};
auto readResult = app.read(&app_info, sizeof(standalone_application_information_t));
if (!readResult || readResult.value() != sizeof(standalone_application_information_t)) {
is_bad = true;
} else if (app_info.header_version > CURRENT_STANDALONE_APPLICATION_API_VERSION) {
is_bad = true;
}
}
app.close();
return is_bad;
}
uint16_t HardResetView::count_bad_apps(const std::filesystem::path& apps_dir) {
int bad_count = 0;
// Check .ppma files
for (const auto& entry : std::filesystem::directory_iterator(apps_dir, u"*.ppma")) {
auto file_path = apps_dir / entry.path();
if (is_bad_app(file_path, true)) {
bad_count++;
}
}
// Check .ppmp files
for (const auto& entry : std::filesystem::directory_iterator(apps_dir, u"*.ppmp")) {
auto file_path = apps_dir / entry.path();
if (is_bad_app(file_path, false)) {
bad_count++;
}
}
return bad_count;
}
void HardResetView::delete_bad_apps(const std::filesystem::path& apps_dir) {
// Delete bad .ppma files
bool deleted_something;
do {
deleted_something = false;
for (const auto& entry : std::filesystem::directory_iterator(apps_dir, u"*.ppma")) {
auto file_path = apps_dir / entry.path();
if (is_bad_app(file_path, true)) {
delete_file(file_path);
deleted_something = true;
break;
}
}
} while (deleted_something);
// Delete bad .ppmp files
do {
deleted_something = false;
for (const auto& entry : std::filesystem::directory_iterator(apps_dir, u"*.ppmp")) {
auto file_path = apps_dir / entry.path();
if (is_bad_app(file_path, false)) {
delete_file(file_path);
deleted_something = true;
break;
}
}
} while (deleted_something);
}
} // namespace ui::external_app::hard_reset
@@ -0,0 +1,69 @@
/*
* Copyright (C) 2026 Pezsma
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __UI_HARD_RESET_H__
#define __UI_HARD_RESET_H__
#include "ui_navigation.hpp"
#include "signal.hpp"
using namespace ui;
namespace ui::external_app::hard_reset {
class HardResetView : public ui::View {
public:
HardResetView(ui::NavigationView& nav);
~HardResetView();
std::string title() const override { return "Hard Reset"; }
void focus() override;
private:
ui::NavigationView& nav_;
SignalToken signal_token_tick_second{};
ui::Button btn_yes{{UI_POS_X(1), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(11), UI_POS_HEIGHT(2)}, "Erase sel."};
ui::Button btn_no{{UI_POS_X_RIGHT(11), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(10), UI_POS_HEIGHT(2)}, "No"};
ui::Text text{{UI_POS_X(0), UI_POS_Y(6), UI_POS_MAXWIDTH, UI_POS_HEIGHT(5)}, ""};
Checkbox chk_settings_file{{UI_POS_X(1), UI_POS_Y(1)}, 14, "Settings file:", true};
Checkbox chk_bad_apps{{UI_POS_X(1), UI_POS_Y(2.5)}, 9, "Bad apps:", true};
Checkbox chk_pmem{{UI_POS_X(1), UI_POS_Y(4)}, 11, "P.mem reset", true};
Text txt_settings_file_count{{UI_POS_X(19), UI_POS_Y(1), UI_POS_WIDTH(5), UI_POS_HEIGHT(1)}, "?"};
Text txt_bad_apps_count{{UI_POS_X(14), UI_POS_Y(2.5), UI_POS_WIDTH(5), UI_POS_HEIGHT(1)}, "?"};
Text txt_wait{{UI_POS_X_CENTER(14), UI_POS_Y(8), UI_POS_WIDTH(14), UI_POS_HEIGHT(1)}, "Please wait..."};
uint16_t count_ini_files_in_directory(const std::filesystem::path& dir_path);
void delete_ini_files_in_directory(const std::filesystem::path& dir_path);
void clear_settings_folder();
void calculate();
bool is_bad_app(const std::filesystem::path& file_path, bool is_ppma);
uint16_t count_bad_apps(const std::filesystem::path& apps_dir);
void delete_bad_apps(const std::filesystem::path& apps_dir);
uint16_t settings_file_count = 0;
uint16_t bad_apps_count = 0;
};
} // namespace ui::external_app::hard_reset
#endif // __UI_HARD_RESET_H__
+84
View File
@@ -0,0 +1,84 @@
/*
* Copyright (C) 2024 Sarah Rose
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui.hpp"
#include "ui_kiss_tnc.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::kiss_tnc {
void initialize_app(ui::NavigationView& nav) {
nav.push<KissTncView>();
}
} // namespace ui::external_app::kiss_tnc
extern "C" {
__attribute__((section(".external_app.app_kiss_tnc.application_information"), used)) application_information_t _application_information_kiss_tnc = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::kiss_tnc::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "KISS TNC",
/*.bitmap_data = */ {
// 16x16 icon - radio tower / TNC
0x00,
0x00,
0x08,
0x00,
0x14,
0x00,
0x22,
0x00,
0x08,
0x00,
0x08,
0x00,
0x08,
0x00,
0x3E,
0x00,
0x22,
0x00,
0x22,
0x00,
0x22,
0x00,
0x22,
0x00,
0x3E,
0x00,
0x1C,
0x00,
0x08,
0x00,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::green().v,
/*.menu_location = */ app_location_t::TRX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_aprs_rx */ {'P', 'A', 'P', 'R'},
/*.m4_app_offset = */ 0x00000000,
};
}
+222
View File
@@ -0,0 +1,222 @@
/*
* Copyright (C) 2024 Sarah Rose
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui_kiss_tnc.hpp"
#include "baseband_api.hpp"
#include "portapack.hpp"
#include "receiver_model.hpp"
#include "transmitter_model.hpp"
#include "string_format.hpp"
#include "memory_map.hpp"
#include "ax25.hpp"
#include "spi_image.hpp"
extern "C" {
#include "usb_serial_device_to_host.h"
}
using namespace portapack;
namespace ui::external_app::kiss_tnc {
namespace {
KissTncView* g_kiss_tnc_instance = nullptr;
}
void KissTncView::kiss_input_trampoline(const uint8_t* data, size_t len) {
if (g_kiss_tnc_instance) g_kiss_tnc_instance->on_kiss_bytes(data, len);
}
KissTncView::KissTncView(NavigationView& nav)
: nav_{nav} {
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
add_children({&field_frequency,
&field_rf_amp,
&field_lna,
&field_vga,
&rssi,
&channel,
&text_status,
&text_usb_status,
&text_rx_count,
&text_tx_count,
&labels,
&console});
receiver_model.enable();
baseband::set_aprs(1200);
g_kiss_tnc_instance = this;
usb_input_handler_.emplace(kiss_input_trampoline);
update_stats();
}
KissTncView::~KissTncView() {
g_kiss_tnc_instance = nullptr;
usb_input_handler_.reset();
if (tx_active_) {
transmitter_model.disable();
} else {
receiver_model.disable();
}
baseband::shutdown();
}
void KissTncView::focus() {
field_frequency.focus();
}
void KissTncView::update_stats() {
text_rx_count.set(to_string_dec_uint(rx_count_));
text_tx_count.set(to_string_dec_uint(tx_count_));
text_usb_status.set(portapack::usb_serial.serial_connected() ? "Connected" : "Disconnected");
}
void KissTncView::send_kiss_frame(const uint8_t* data, size_t len) {
// Stack-allocate output buffer: max KISS overhead is 2x data + 2 FENDs + 1 cmd byte
uint8_t buf[512];
size_t i = 0;
buf[i++] = 0xC0; // FEND
buf[i++] = 0x00; // data command
for (size_t j = 0; j < len; j++) {
if (data[j] == 0xC0) {
if (i + 3 > sizeof(buf)) break; // need 2 for escape + 1 for final FEND
buf[i++] = 0xDB;
buf[i++] = 0xDC;
} else if (data[j] == 0xDB) {
if (i + 3 > sizeof(buf)) break; // need 2 for escape + 1 for final FEND
buf[i++] = 0xDB;
buf[i++] = 0xDD;
} else {
if (i + 2 > sizeof(buf)) break; // need 1 for data + 1 for final FEND
buf[i++] = data[j];
}
}
buf[i++] = 0xC0; // FEND
if (usb_input_handler_)
usb_input_handler_->write(buf, i);
}
void KissTncView::on_packet(const APRSPacketMessage* message) {
aprs::APRSPacket pkt = message->packet;
uint8_t payload_size = pkt.size();
if (payload_size > 2) {
uint8_t raw[256];
size_t raw_len = payload_size - 2;
for (size_t i = 0; i < raw_len; i++)
raw[i] = static_cast<uint8_t>(pkt[i]);
send_kiss_frame(raw, raw_len);
}
console.writeln(pkt.get_source_formatted() + ">" + pkt.get_destination_formatted());
rx_count_++;
update_stats();
}
void KissTncView::on_kiss_bytes(const uint8_t* data, size_t len) {
for (size_t i = 0; i < len; i++) {
uint8_t b = data[i];
switch (kiss_state_) {
case KissState::IDLE:
if (b == 0xC0) kiss_state_ = KissState::CMD;
break;
case KissState::CMD:
if (b == 0xC0) break;
if (b == 0x00) {
kiss_idx_ = 0;
kiss_state_ = KissState::DATA;
} else {
kiss_state_ = KissState::IDLE;
}
break;
case KissState::DATA:
if (b == 0xC0) {
if (kiss_idx_ > 0) process_kiss_frame();
kiss_idx_ = 0;
kiss_state_ = KissState::CMD;
} else if (b == 0xDB) {
kiss_state_ = KissState::ESC;
} else if (kiss_idx_ < sizeof(kiss_buf_)) {
kiss_buf_[kiss_idx_++] = b;
}
break;
case KissState::ESC:
if (b == 0xDC) {
if (kiss_idx_ < sizeof(kiss_buf_)) kiss_buf_[kiss_idx_++] = 0xC0;
} else if (b == 0xDD) {
if (kiss_idx_ < sizeof(kiss_buf_)) kiss_buf_[kiss_idx_++] = 0xDB;
}
kiss_state_ = KissState::DATA;
break;
}
}
}
void KissTncView::process_kiss_frame() {
if (tx_active_ || kiss_idx_ == 0) return;
// AFSK shared buffer is 512 bytes (256 uint16_t words). Each raw byte
// produces ~10 encoded bits after bit-stuffing + flags, so cap at 200 bytes
// to ensure the bitstream plus required 0-word terminator always fits.
if (kiss_idx_ > 200) return;
start_tx();
}
void KissTncView::start_tx() {
tx_active_ = true;
ax25::AX25Frame frame;
frame.make_frame_from_raw(kiss_buf_, kiss_idx_);
rx_frequency_ = receiver_model.target_frequency();
receiver_model.disable();
baseband::shutdown();
baseband::run_image(portapack::spi_flash::image_tag_afsk);
transmitter_model.set_target_frequency(rx_frequency_);
transmitter_model.set_sampling_rate(AFSK_SAMPLE_RATE);
transmitter_model.set_baseband_bandwidth(AFSK_BASEBAND_BW);
transmitter_model.enable();
baseband::set_afsk_data(AFSK_SAMPLE_RATE / 1200, 1200, 2200, 1, 10000, 8);
text_status.set("Transmitting");
tx_count_++;
update_stats();
}
void KissTncView::finish_tx() {
transmitter_model.disable();
baseband::shutdown();
// Must reload from SPI flash — run_image(afsk) overwrote m4_code.base()
baseband::run_image(portapack::spi_flash::image_tag_aprs_rx);
receiver_model.set_target_frequency(rx_frequency_);
receiver_model.set_sampling_rate(APRS_RX_SAMPLE_RATE);
receiver_model.set_baseband_bandwidth(APRS_RX_BASEBAND_BW);
receiver_model.enable();
baseband::set_aprs(1200);
tx_active_ = false;
text_status.set("Listening");
update_stats();
}
} // namespace ui::external_app::kiss_tnc
+138
View File
@@ -0,0 +1,138 @@
/*
* Copyright (C) 2024 Sarah Rose
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#pragma once
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_freq_field.hpp"
#include "ui_rssi.hpp"
#include "radio_state.hpp"
#include "app_settings.hpp"
#include "message.hpp"
#include "baseband_api.hpp"
#include "portapack.hpp"
#include "receiver_model.hpp"
#include "aprs_packet.hpp"
#include "usb_serial_host_to_device.hpp"
#include <optional>
namespace ui::external_app::kiss_tnc {
class KissTncView : public View {
public:
KissTncView(NavigationView& nav);
~KissTncView();
void focus() override;
std::string title() const override { return "KISS TNC"; }
private:
static constexpr rf::Frequency APRS_FREQ_DEFAULT = 144390000;
static constexpr uint32_t APRS_RX_SAMPLE_RATE = 3072000U;
static constexpr uint32_t APRS_RX_BASEBAND_BW = 1750000U;
static constexpr uint32_t AFSK_SAMPLE_RATE = 1536000U;
static constexpr uint32_t AFSK_BASEBAND_BW = 1750000U;
NavigationView& nav_;
// CRITICAL: RxRadioState must be declared before SettingsManager
RxRadioState radio_state_{
APRS_FREQ_DEFAULT,
APRS_RX_BASEBAND_BW,
APRS_RX_SAMPLE_RATE};
app_settings::SettingsManager settings_{"kiss_tnc", app_settings::Mode::RX};
RxFrequencyField field_frequency{
{0, 0},
nav_};
RFAmpField field_rf_amp{{13 * 8, 0}};
LNAGainField field_lna{{15 * 8, 0}};
VGAGainField field_vga{{18 * 8, 0}};
RSSI rssi{{21 * 8, 0, 6 * 8, 4}};
Channel channel{{21 * 8, 5, 6 * 8, 4}};
Text text_status{{0, 16, 240, 16}, "Listening"};
Text text_usb_status{{4 * 8, 2 * 16, 14 * 8, 16}, "Disconnected"};
Text text_rx_count{{3 * 8, 3 * 16, 5 * 8, 16}, "0"};
Text text_tx_count{{11 * 8, 3 * 16, 5 * 8, 16}, "0"};
Labels labels{{
{{0, 2 * 16}, "USB:", Color::light_grey()},
{{0, 3 * 16}, "RX:", Color::light_grey()},
{{8 * 8, 3 * 16}, "TX:", Color::light_grey()},
}};
Console console{{0, 4 * 16, 240, 180}};
enum class KissState : uint8_t { IDLE,
CMD,
DATA,
ESC };
KissState kiss_state_{KissState::IDLE};
uint8_t kiss_buf_[350]{};
size_t kiss_idx_{0};
bool tx_active_{false};
rf::Frequency rx_frequency_{APRS_FREQ_DEFAULT};
uint32_t rx_count_{0};
uint32_t tx_count_{0};
void on_packet(const APRSPacketMessage* message);
void on_kiss_bytes(const uint8_t* data, size_t len);
void process_kiss_frame();
void send_kiss_frame(const uint8_t* data, size_t len);
void start_tx();
void finish_tx();
void update_stats();
uint32_t frame_counter_{0};
static void kiss_input_trampoline(const uint8_t* data, size_t len);
std::optional<UsbSerialInputHandler> usb_input_handler_{};
MessageHandlerRegistration message_handler_packet{
Message::ID::APRSPacket,
[this](Message* const p) {
on_packet(reinterpret_cast<const APRSPacketMessage*>(p));
}};
MessageHandlerRegistration message_handler_tx_progress{
Message::ID::TXProgress,
[this](Message* const p) {
auto* msg = reinterpret_cast<const TXProgressMessage*>(p);
if (msg->done) finish_tx();
}};
MessageHandlerRegistration message_handler_frame_sync{
Message::ID::DisplayFrameSync,
[this](const Message* const) {
if (++frame_counter_ == 60) {
frame_counter_ = 0;
text_usb_status.set(portapack::usb_serial.serial_connected() ? "Connected" : "Disconnected");
}
}};
};
} // namespace ui::external_app::kiss_tnc
+1
View File
@@ -137,6 +137,7 @@ LevelView::LevelView(NavigationView& nav)
else
v = SPEC_MODULATION;
field_mode.set_selected_index(v);
return; // Important ! Guru will occur if you don't return when modifying field from within on_change !
}
last_mode = v;
change_mode(v);
+83
View File
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2025 Sarah Rose
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui.hpp"
#include "ui_mdc_tx.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::mdc_tx {
void initialize_app(ui::NavigationView& nav) {
nav.push<MdcTxView>();
}
} // namespace ui::external_app::mdc_tx
extern "C" {
__attribute__((section(".external_app.app_mdc_tx.application_information"), used))
application_information_t _application_information_mdc_tx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::mdc_tx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "MDC-1200 TX",
/*.bitmap_data = */ {
0x00,
0x00,
0xFE,
0x7F,
0xFF,
0xFF,
0xBB,
0xD0,
0xFF,
0xFF,
0xFF,
0xFF,
0x0B,
0xE1,
0xFF,
0xFF,
0xFF,
0xFF,
0xEB,
0xD0,
0xFF,
0xFF,
0xFE,
0x7F,
0x70,
0x00,
0x30,
0x00,
0x10,
0x00,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = */ {'P', 'A', 'F', 'T'},
/*.m4_app_offset = */ 0x00000000,
};
}
+289
View File
@@ -0,0 +1,289 @@
/*
* Copyright (C) 2025 Sarah Rose
*
* This file is part of PortaPack.
*
* 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 2, 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; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui_mdc_tx.hpp"
#include "baseband_api.hpp"
#include "portapack.hpp"
#include "portapack_shared_memory.hpp"
#include "transmitter_model.hpp"
#include "ui/ui_receiver.hpp"
using namespace portapack;
namespace ui::external_app::mdc_tx {
static constexpr uint32_t MDC_SAMPLES_PER_BIT = AFSK_TX_SAMPLERATE / 1200U;
static constexpr uint32_t MDC_MARK_FREQ = 1800U;
static constexpr uint32_t MDC_SPACE_FREQ = 1200U;
static constexpr uint32_t MDC_FM_DEVIATION = 2500U;
static constexpr uint8_t MDC_PREAMBLE[7] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA};
static constexpr uint8_t MDC_SYNC[5] = {0x07, 0x09, 0x2A, 0x44, 0x6F};
static constexpr int MDC_NUM_PREAMBLES = 3;
static constexpr uint8_t MDC_DP_OP = 0x35;
static constexpr uint8_t MDC_DP_ARG = 0x89;
static constexpr uint8_t MDC_DP_CALL_ARG = 0x0D;
static uint8_t mdc_flip8(uint8_t in) {
uint8_t out = 0;
for (int i = 0; i < 8; i++) {
out = static_cast<uint8_t>((out << 1) | (in & 1));
in >>= 1;
}
return out;
}
static uint16_t mdc_flip16(uint16_t in) {
uint16_t out = 0;
for (int i = 0; i < 16; i++) {
out = static_cast<uint16_t>((out << 1) | (in & 1));
in >>= 1;
}
return out;
}
static uint16_t mdc_crc(const uint8_t* data, int length) {
uint16_t crc = 0;
for (int i = 0; i < length; i++) {
uint16_t c = mdc_flip8(data[i]);
for (int j = 0x80; j != 0; j >>= 1) {
uint16_t bit = crc & 0x8000;
crc = static_cast<uint16_t>(crc << 1);
if (c & static_cast<uint16_t>(j)) bit ^= 0x8000;
if (bit) crc ^= 0x1021;
}
}
crc = mdc_flip16(crc);
crc ^= 0xFFFF;
return crc;
}
// CRC + convolutional encoding + bit interleaving for a 14-byte codeword.
// Uses lbits_ (class member) so no large allocation hits the stack.
void MdcTxView::pack_codeword(uint8_t cw[14]) {
uint16_t crc = mdc_crc(cw, 4);
cw[4] = static_cast<uint8_t>(crc & 0xFF);
cw[5] = static_cast<uint8_t>((crc >> 8) & 0xFF);
cw[6] = 0x00;
// Convolutional encoding — csr[7] is only 7 bytes, fine on stack
uint8_t csr[7] = {};
for (int i = 0; i < 7; i++) {
cw[i + 7] = 0;
for (int j = 0; j <= 7; j++) {
for (int k = 6; k > 0; k--) csr[k] = csr[k - 1];
csr[0] = (cw[i] >> j) & 1;
int b = csr[0] + csr[2] + csr[5] + csr[6];
cw[i + 7] |= static_cast<uint8_t>((b & 1) << j);
}
}
// Bit interleaving — uses lbits_ class member (112 bytes off the stack)
for (int i = 0; i < 112; i++) lbits_[i] = 0;
int l = 0, m = 0;
for (int i = 0; i < 14; i++) {
for (int j = 0; j <= 7; j++) {
lbits_[l] = (cw[i] >> j) & 1;
l += 16;
if (l > 111) {
m++;
l = m;
}
}
}
l = 0;
for (int i = 0; i < 14; i++) {
cw[i] = 0;
for (int j = 7; j >= 0; j--) {
if (lbits_[l]) cw[i] |= static_cast<uint8_t>(1 << j);
l++;
}
}
}
// Writes preamble + sync + one packed codeword into tx_stream_, returns length.
int MdcTxView::build_single(uint8_t op, uint8_t arg, uint8_t id_hi, uint8_t id_lo) {
int idx = 0;
for (int i = 0; i < MDC_NUM_PREAMBLES; i++)
for (int j = 0; j < 7; j++) tx_stream_[idx++] = MDC_PREAMBLE[j];
for (int j = 0; j < 5; j++) tx_stream_[idx++] = MDC_SYNC[j];
uint8_t cw[14] = {};
cw[0] = op;
cw[1] = arg;
cw[2] = id_hi;
cw[3] = id_lo;
pack_codeword(cw);
for (int j = 0; j < 14; j++) tx_stream_[idx++] = cw[j];
return idx;
}
// Writes preamble + sync + two packed codewords into tx_stream_, returns length.
int MdcTxView::build_double(uint8_t op1, uint8_t arg1, uint8_t id1_hi, uint8_t id1_lo, uint8_t op2, uint8_t arg2, uint8_t id2_hi, uint8_t id2_lo) {
int idx = 0;
for (int i = 0; i < MDC_NUM_PREAMBLES; i++)
for (int j = 0; j < 7; j++) tx_stream_[idx++] = MDC_PREAMBLE[j];
for (int j = 0; j < 5; j++) tx_stream_[idx++] = MDC_SYNC[j];
uint8_t cw1[14] = {};
cw1[0] = op1;
cw1[1] = arg1;
cw1[2] = id1_hi;
cw1[3] = id1_lo;
pack_codeword(cw1);
for (int j = 0; j < 14; j++) tx_stream_[idx++] = cw1[j];
uint8_t cw2[14] = {};
cw2[0] = op2;
cw2[1] = arg2;
cw2[2] = id2_hi;
cw2[3] = id2_lo;
pack_codeword(cw2);
for (int j = 0; j < 14; j++) tx_stream_[idx++] = cw2[j];
return idx;
}
MdcTxView::MdcTxView(NavigationView& nav)
: nav_{nav} {
baseband::run_image(portapack::spi_flash::image_tag_afsk);
add_children({
&labels_,
&field_op,
&field_id_hi,
&field_id_lo,
&field_arg,
&field_src_hi,
&field_src_lo,
&text_status,
&tx_view,
});
tx_view.on_start = [this]() {
if (!tx_active_) {
start_tx();
tx_view.set_transmitting(true);
}
};
tx_view.on_stop = [this]() { stop_tx(); };
transmitter_model.set_tx_gain(30);
tx_view.on_edit_frequency = [this, &nav]() {
auto new_view = nav.push<FrequencyKeypadView>(transmitter_model.target_frequency());
new_view->on_changed = [this](rf::Frequency f) {
transmitter_model.set_target_frequency(f);
};
};
field_op.on_change = [this](size_t, int32_t op) {
switch (op) {
case 0xFE:
field_arg.set_value(0x0C);
break; // Unstun
case 0x2B:
field_arg.set_value(0x00);
break; // Stun
case 0x63:
field_arg.set_value(0x85);
break; // Radio Check
case 0x11:
field_arg.set_value(0x8A);
break; // Remote Monitor
default:
field_arg.set_value(0x00);
break;
}
};
}
MdcTxView::~MdcTxView() {
transmitter_model.disable();
baseband::shutdown();
}
void MdcTxView::focus() {
field_op.focus();
}
void MdcTxView::start_tx() {
int32_t raw_op = field_op.selected_index_value();
uint8_t op = (raw_op == 0xFE) ? 0x2B : static_cast<uint8_t>(raw_op);
uint8_t arg = static_cast<uint8_t>(field_arg.value());
uint8_t id_hi = static_cast<uint8_t>(field_id_hi.value());
uint8_t id_lo = static_cast<uint8_t>(field_id_lo.value());
uint8_t src_hi = static_cast<uint8_t>(field_src_hi.value());
uint8_t src_lo = static_cast<uint8_t>(field_src_lo.value());
int stream_len;
bool is_double = (op == 0x80 || op == 0x81 || op == 0x82);
if (is_double) {
stream_len = build_double(MDC_DP_OP, MDC_DP_ARG, id_hi, id_lo,
op, MDC_DP_CALL_ARG, src_hi, src_lo);
} else {
stream_len = build_single(op, arg, id_hi, id_lo);
}
// NRZI encode tx_stream_ into shared memory words
auto* words = reinterpret_cast<uint16_t*>(shared_memory.bb_data.data);
uint8_t prev_bit = 0;
for (int i = 0; i < stream_len; i++) {
uint8_t raw = tx_stream_[i];
uint8_t nrzi = 0;
for (int bit = 7; bit >= 0; bit--) {
uint8_t rb = (raw >> bit) & 1;
uint8_t nb = rb ^ prev_bit;
prev_bit = rb;
nrzi = static_cast<uint8_t>((nrzi << 1) | nb);
}
words[i] = nrzi;
}
words[stream_len] = 0;
tx_active_ = true;
text_status.set("TX...");
transmitter_model.enable();
baseband::set_afsk_data(
MDC_SAMPLES_PER_BIT,
MDC_MARK_FREQ,
MDC_SPACE_FREQ,
1,
MDC_FM_DEVIATION,
8);
}
void MdcTxView::stop_tx() {
baseband::kill_afsk();
transmitter_model.disable();
tx_active_ = false;
text_status.set("Ready");
tx_view.set_transmitting(false);
}
void MdcTxView::on_tx_progress(uint32_t, bool done) {
if (done) {
stop_tx();
text_status.set("Done!");
}
}
} // namespace ui::external_app::mdc_tx

Some files were not shown because too many files have changed in this diff Show More