Compare commits

..

36 Commits

Author SHA1 Message Date
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
122 changed files with 9381 additions and 1509 deletions
+67
View File
@@ -0,0 +1,67 @@
<!--
👋 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)
- [ ] Reviewed the [Contributing Guidelines](https://github.com/portapack-mayhem/mayhem-firmware/wiki/Contributing-Guidelines)
+1 -1
View File
@@ -60,7 +60,7 @@ jobs:
- name: Make build folder
run: mkdir ${{ github.workspace }}/build
- name: Run the Docker image
run: docker run -e VERSION_STRING=${{ steps.version_date.outputs.date }} -i -v ${{ github.workspace }}:/havoc portapack-dev ninja ${{ matrix.cmake_args }}
run: docker run -e VERSION_STRING=${{ steps.version_date.outputs.date }} -i -v ${{ github.workspace }}:/havoc portapack-dev ${{ matrix.cmake_args }}
- name: Create Small SD Card ZIP - No World Map
run: |
mkdir -p sdcard/FIRMWARE && cp build/firmware/portapack-mayhem-firmware.bin sdcard/FIRMWARE/portapack-mayhem_${{ steps.version_date.outputs.date }}.bin && cp build/firmware/portapack-mayhem_OCI.ppfw.tar sdcard/FIRMWARE/mayhem_nightly_${{ steps.version_date.outputs.date }}${{ matrix.artifact_suffix }}_OCI.ppfw.tar && mkdir -p sdcard/APPS && cp build/firmware/application/*.ppma sdcard/APPS && cp build/firmware/standalone/*/*.ppmp sdcard/APPS && cd sdcard && zip -r ../sdcard-no-map.zip . && cd ..
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- name: Make build folder
run: mkdir ${{ github.workspace }}/build
- name: Run the Docker image
run: docker run -e VERSION_STRING=${{ steps.version.outputs.version }} -i -v ${{ github.workspace }}:/havoc portapack-dev ninja ${{ matrix.cmake_args }}
run: docker run -e VERSION_STRING=${{ steps.version.outputs.version }} -i -v ${{ github.workspace }}:/havoc portapack-dev ${{ matrix.cmake_args }}
- name: Create Small SD Card ZIP - No World Map
run: |
mkdir -p sdcard/FIRMWARE && cp build/firmware/portapack-mayhem-firmware.bin sdcard/FIRMWARE/portapack-mayhem_${{ steps.version.outputs.version }}.bin && cp build/firmware/portapack-mayhem_OCI.ppfw.tar sdcard/FIRMWARE/mayhem_${{ steps.version.outputs.version }}${{ matrix.artifact_suffix }}_OCI.ppfw.tar && mkdir -p sdcard/APPS && cp build/firmware/application/*.ppma sdcard/APPS && cp build/firmware/standalone/*/*.ppmp sdcard/APPS && cd sdcard && zip -r ../sdcard-no-map.zip . && cd ..
+1 -1
View File
@@ -1 +1 @@
v2.3.1
v2.3.2
+1 -1
View File
@@ -1 +1 @@
v2.3.2
v2.4.0
+4 -1
View File
@@ -51,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.
+2 -2
View File
@@ -29,5 +29,5 @@ RUN mkdir /opt/build \
ADD firmware/tools/docker-entrypoint.sh /usr/local/bin/entrypoint.sh
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
# replace ninja with make if you prefer to use that by default
CMD ["ninja"]
# replace make with ninja temporarily while building your image if you prefer to use that by default
CMD ["make"]
@@ -419,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() {
+1 -1
View File
@@ -446,7 +446,7 @@ class BLERxView : public View {
};
// Variable to store the current limit
size_t max_recent_entries = 32;
size_t max_recent_entries = 25;
}; /* BLERxView */
} /* namespace ui */
+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__*/
+26 -1
View File
@@ -1160,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});
@@ -1169,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();
};
+22 -7
View File
@@ -1045,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"};
+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 */
+15
View File
@@ -21,6 +21,7 @@
*/
#include "baseband_api.hpp"
#include <cstring>
#include "audio.hpp"
#include "tonesets.hpp"
@@ -392,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);
@@ -426,6 +432,15 @@ void set_epirb_tx_config(EPIRBTXDataMessage& 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;
void run_image(const spi_flash::image_tag_t image_tag) {
+2
View File
@@ -108,6 +108,7 @@ void set_siggen_config(const uint32_t bw, const uint32_t shape, const uint32_t d
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);
@@ -117,6 +118,7 @@ void set_bitstream_config(uint32_t deviation, uint8_t mode);
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_p25tx_data(const uint8_t* dibits, uint16_t frame_length);
void request_roger_beep();
void request_rssi_beep();
+51 -5
View File
@@ -319,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},
@@ -335,6 +344,7 @@ 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{{
#ifdef PRALINE
@@ -451,7 +461,7 @@ void ClockManager::init_clock_generator() {
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};
reference = Reference{ReferenceSource::Xtal, 0}; // PLLA
/* Clock control will be set AFTER multisynth configuration - see below */
#else
@@ -640,12 +650,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() {
@@ -668,6 +682,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;
@@ -686,6 +711,7 @@ ClockManager::Reference ClockManager::choose_reference() {
if (hackrf_r9) {
gpio_r9_clkin_en.write(0);
}
#endif
portapack_tcxo_disable();
return {ReferenceSource::Xtal, 25000000};
@@ -881,10 +907,6 @@ 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.
*/
if (hackrf_r9 && reference.source != ReferenceSource::Xtal) {
return;
}
#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)
@@ -893,6 +915,10 @@ void ClockManager::set_reference_ppb(const int32_t ppb) {
}
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
@@ -1105,6 +1131,25 @@ void ClockManager::stop_audio_pll() {
}
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);
@@ -1133,4 +1178,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
}
+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,
+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},
+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::orange().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
+175 -22
View File
@@ -98,6 +98,39 @@ void EPIRBTXAppView::on_timer() {
}
}
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
@@ -136,17 +169,17 @@ void EPIRBTXAppView::update_frame(bool updateConfig) {
}
void EPIRBTXAppView::update_config() {
if (epirb_tx_message.mode_bpsk) {
// Already in BPSK mode => backup bpsk frequency
bpsk_frequency = transmitter_model.target_frequency();
} else {
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 = (150 * TONES_SAMPLERATE) / 1000; // 150 ms
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);
@@ -178,15 +211,12 @@ void EPIRBTXAppView::stop_tx() {
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;
// Backup bpsk frequency for next run
bpsk_frequency = transmitter_model.target_frequency();
// Restore am frequency
transmitter_model.set_target_frequency(am_frequency);
// Send config to baseband
baseband::set_epirb_tx_config(epirb_tx_message);
// Start am transmission
update_am_transmission();
} else {
// End of BPSK frame
transmitter_model.disable();
@@ -262,6 +292,8 @@ EPIRBTXAppView::EPIRBTXAppView(
&checkbox_am,
&field_am_frequency,
&checkbox_send_on_change,
&options_am_channel,
&options_bpsk_channel,
&tx_view});
text_beacon.set_style(Theme::getInstance()->fg_light);
@@ -279,6 +311,11 @@ EPIRBTXAppView::EPIRBTXAppView(
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);
@@ -292,23 +329,23 @@ EPIRBTXAppView::EPIRBTXAppView(
update_mode();
update_location();
options_mode.on_change = [this](size_t index, OptionsField::value_t) {
mode_file = (index == 0);
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 index, OptionsField::value_t) {
beacon_params.type = (BeaconType)index;
beacon_type = index;
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 index, OptionsField::value_t) {
beacon_params.protocol = (BeaconProtocol)index;
beacon_protocol = index;
options_beacon_protocol.on_change = [this](size_t, OptionsField::value_t value) {
beacon_params.protocol = (BeaconProtocol)value;
beacon_protocol = value;
update_frame();
set_dirty();
};
@@ -320,6 +357,71 @@ EPIRBTXAppView::EPIRBTXAppView(
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;
@@ -358,7 +460,7 @@ EPIRBTXAppView::EPIRBTXAppView(
field_am_frequency.on_change = [this](rf::Frequency freq) {
am_frequency = freq;
if (transmitting && !epirb_tx_message.mode_bpsk && am_enabled)
if (transmitting && !transmitting_bpsk && am_enabled)
// Update transmitter frequency
transmitter_model.set_target_frequency(am_frequency);
};
@@ -397,6 +499,8 @@ EPIRBTXAppView::EPIRBTXAppView(
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);
};
@@ -404,7 +508,21 @@ EPIRBTXAppView::EPIRBTXAppView(
field_am_frequency.on_edit = [this, &nav]() {
auto new_view = nav.push<FrequencyKeypadView>(field_am_frequency.value());
new_view->on_changed = [this](rf::Frequency f) {
field_am_frequency.set_value(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();
};
};
@@ -415,8 +533,43 @@ EPIRBTXAppView::EPIRBTXAppView(
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);
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();
};
};
+87 -15
View File
@@ -37,8 +37,26 @@
#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,
@@ -51,6 +69,25 @@ enum class BeaconProtocol {
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;
@@ -95,6 +132,8 @@ class EPIRBTXAppView : public View {
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);
@@ -114,25 +153,33 @@ class EPIRBTXAppView : public View {
// 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{121500000};
rf::Frequency am_frequency{AM_TEST_FREQUENCY};
// Frequency of the 406 MHz BPSK signal
rf::Frequency bpsk_frequency{406025000};
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{true};
bool mode_file{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{false};
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{0};
uint8_t beacon_type{(uint8_t)BeaconType::EPIRB};
// Currently selected beacon protocol
uint8_t beacon_protocol{0};
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)
@@ -150,6 +197,8 @@ class EPIRBTXAppView : public View {
{"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},
@@ -166,6 +215,8 @@ class EPIRBTXAppView : public View {
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};
@@ -179,7 +230,9 @@ class EPIRBTXAppView : public View {
{{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(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
@@ -231,15 +284,15 @@ class EPIRBTXAppView : public View {
OptionsField options_beacon_type{
{UI_POS_X(9), UI_POS_Y(1)},
7,
{{"EPIRB", 0},
{"ELT", 1},
{"PLB", 2}}};
{{"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", 0},
{"Standard", 1},
{"National", 2}}};
{{"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,
@@ -261,8 +314,8 @@ class EPIRBTXAppView : public View {
OptionsField options_mode{
{UI_POS_X(7), UI_POS_Y(0)},
30,
{{"File (BEACONS.TXT)", 0},
{"Manual (Editor)", 1}}};
{{"File (BEACONS.TXT)", (uint8_t)BeaconMode::FILE},
{"Manual (Editor)", (uint8_t)BeaconMode::MODE_MANUAL}}};
// Frame content
Text text_frame{
@@ -305,6 +358,25 @@ class EPIRBTXAppView : public View {
"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{
+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
};
}
+34 -2
View File
@@ -107,6 +107,10 @@ set(EXTCPPSRC
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
@@ -305,8 +309,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
@@ -321,6 +327,10 @@ set(EXTCPPSRC
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
@@ -328,6 +338,22 @@ set(EXTCPPSRC
#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
)
set(EXTAPPLIST
@@ -356,6 +382,7 @@ set(EXTAPPLIST
#morse_tx
sstvtx
same_tx
mdc_tx
sstvrx
random_password
acars_rx
@@ -388,6 +415,7 @@ set(EXTAPPLIST
gfxeq
waterfall_designer
detector_rx
fpv_detect
spaceinv
blackjack
battleship
@@ -408,8 +436,12 @@ set(EXTAPPLIST
rtty_rx
rtty_tx
pocsag_tx
flex_tx
time_sink
kiss_tnc
p25_tx
two_tone_pager
two_tone_rx
)
# sdusb has type conflicts with PRALINE (HackRF Pro) - add only for non-PRALINE builds
+143 -104
View File
@@ -23,87 +23,92 @@ 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_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_epirb_tx (rwx) : org = 0xAE000000, 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
}
SECTIONS
@@ -144,7 +149,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*);
@@ -192,61 +197,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*);
@@ -264,19 +269,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*);
@@ -288,7 +293,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*);
@@ -372,13 +377,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*);
@@ -480,14 +485,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));
@@ -504,7 +507,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)
{
@@ -524,12 +527,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));
@@ -547,6 +550,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));
@@ -583,10 +587,45 @@ SECTIONS
*(*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
}
+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,
+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,
+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
+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
+124
View File
@@ -0,0 +1,124 @@
/*
* 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.
*/
#ifndef __UI_MDC_TX_H__
#define __UI_MDC_TX_H__
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_transmitter.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "message.hpp"
#include "modems.hpp"
namespace ui::external_app::mdc_tx {
class MdcTxView : public View {
public:
MdcTxView(NavigationView& nav);
~MdcTxView();
MdcTxView(const MdcTxView&) = delete;
MdcTxView& operator=(const MdcTxView&) = delete;
void focus() override;
std::string title() const override { return "MDC-1200 TX"; }
private:
NavigationView& nav_;
// TxRadioState MUST be declared before SettingsManager
TxRadioState radio_state_{
462562500,
1750000,
AFSK_TX_SAMPLERATE};
app_settings::SettingsManager settings_{
"tx_mdc_tx",
app_settings::Mode::TX};
Labels labels_{{
{{UI_POS_X(0), UI_POS_Y(0)}, "Op:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(1)}, "ID:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(13), UI_POS_Y(1)}, "Arg:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(2)}, "Src:", ui::Theme::getInstance()->fg_light->foreground},
}};
// Only one OptionsField allowed per external app
// Stun=Op 0x2B Arg 0x00, Unstun=Op 0x2B Arg 0x0C (auto-set via on_change)
OptionsField field_op{
{UI_POS_X(4), UI_POS_Y(0)},
14,
{{"PTT ID", 0x01},
{"Emergency", 0x00},
{"Radio Check", 0x63},
{"Stun", 0x2B},
{"Unstun", 0xFE}, // sentinel: op=0x2B, arg=0x0C
{"Call Alert", 0x81},
{"Sel Call 1", 0x80},
{"Sel Call 2", 0x82},
{"Status Req", 0x22},
{"Status Resp", 0x06},
{"Rem Monitor", 0x11},
{"Message", 0x07}}};
// Unit ID: two decimal bytes (0-255) combined into a 16-bit ID
NumberField field_id_hi{{UI_POS_X(4), UI_POS_Y(1)}, 3, {0, 255}, 1, '0'};
NumberField field_id_lo{{UI_POS_X(7), UI_POS_Y(1)}, 3, {0, 255}, 1, '0'};
// Argument byte (decimal 0-255, auto-set by op selection)
NumberField field_arg{{UI_POS_X(17), UI_POS_Y(1)}, 3, {0, 255}, 1, '0'};
// Source ID: two decimal bytes (0-255) combined into a 16-bit ID
NumberField field_src_hi{{UI_POS_X(4), UI_POS_Y(2)}, 3, {0, 255}, 1, '0'};
NumberField field_src_lo{{UI_POS_X(7), UI_POS_Y(2)}, 3, {0, 255}, 1, '0'};
Text text_status{{0, UI_POS_Y(3), UI_POS_MAXWIDTH, UI_POS_DEFAULT_HEIGHT}, "Ready"};
TransmitterView tx_view{
(int16_t)UI_POS_Y_BOTTOM(4),
12500,
0};
bool tx_active_{false};
// Class-owned scratch buffers — keep large allocations off the stack
uint8_t tx_stream_[128]{};
uint8_t lbits_[112]{};
void pack_codeword(uint8_t cw[14]);
int build_single(uint8_t op, uint8_t arg, uint8_t id_hi, uint8_t id_lo);
int 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);
void start_tx();
void stop_tx();
void on_tx_progress(uint32_t progress, bool done);
MessageHandlerRegistration message_handler_tx_progress{
Message::ID::TXProgress,
[this](const Message* const p) {
const auto msg = *reinterpret_cast<const TXProgressMessage*>(p);
this->on_tx_progress(msg.progress, msg.done);
}};
};
} // namespace ui::external_app::mdc_tx
#endif
@@ -27,6 +27,9 @@ MorseRadiotxView::MorseRadiotxView(ui::NavigationView& nav)
&chk_trans,
&bandwidth,
&chk_callsgn,
&chk_loop,
&wait_time,
&progressbar,
&txt_last,
&console_text,
&btn_clear,
@@ -69,6 +72,7 @@ MorseRadiotxView::MorseRadiotxView(ui::NavigationView& nav)
options_mode.set_selected_index(current_mode, true);
tone_.set_value(tone, true);
wpm_.set_value(wpm, true);
wait_time.set_value(1, true);
bandwidth.set_value(band, true);
btn_ptt.on_select = [this](Button&) {
@@ -156,6 +160,14 @@ MorseRadiotxView::MorseRadiotxView(ui::NavigationView& nav)
transmitter_model.set_target_frequency(f);
};
};
chk_trans.on_select = [this](Checkbox&, bool v) {
if (v) chk_loop.set_value(false);
};
chk_loop.on_select = [this](Checkbox&, bool v) {
if (v) chk_trans.set_value(false);
};
}
MorseRadiotxView::~MorseRadiotxView() {
@@ -197,19 +209,15 @@ MorseRadiotxView::MorseTimings MorseRadiotxView::calculate_morse_timings(uint32_
void MorseRadiotxView::transmit_morse_message() {
std::string full_message = "";
// cal sign
if (chk_callsgn.value() && !call_sign.empty()) {
full_message = call_sign;
if (!chk_trans.value() && !msg_buffer.empty()) {
full_message += " " + msg_buffer;
}
} else {
if (!chk_trans.value()) full_message = msg_buffer;
}
if (full_message.empty() && !chk_trans.value()) {
if (chk_trans.value()) {
ptt_button_visibility(false);
return;
} else {
full_message = msg_buffer;
if (chk_callsgn.value() && !call_sign.empty()) { // call sign
full_message += " " + call_sign;
}
}
// enable transmit
@@ -219,46 +227,63 @@ void MorseRadiotxView::transmit_morse_message() {
ui_toggle();
}
for (size_t i = 0; i < full_message.length(); i++) {
if (chThdShouldTerminate()) break;
uint8_t loop_seconds = static_cast<uint8_t>(wait_time.value());
progressbar.set_max(loop_seconds * 2);
char c = full_message[i];
do {
for (size_t i = 0; i < full_message.length(); i++) {
if (chThdShouldTerminate()) break;
std::string s_char(1, c);
// space
if (c == ' ') {
console_text.write(" ");
chThdSleepMilliseconds(current_timings.word_gap);
continue;
}
char c = full_message[i];
const char* pattern = morse_decoder_.get_morse_pattern(c);
std::string s_char(1, c);
// space
if (c == ' ') {
console_text.write(" ");
chThdSleepMilliseconds(current_timings.word_gap);
continue;
}
if (pattern != nullptr) {
txt_last.set(pattern);
const char* pattern = morse_decoder_.get_morse_pattern(c);
// write blue char to console
console_text.write(STR_COLOR_BLUE + s_char);
if (pattern != nullptr) {
txt_last.set(pattern);
// Morze (dih/dah) send
for (int j = 0; pattern[j] != '\0'; j++) {
baseband::set_morsetx_key(true);
if (pattern[j] == '.') {
chThdSleepMilliseconds(current_timings.dot_ms);
} else if (pattern[j] == '-') {
chThdSleepMilliseconds(current_timings.dash_ms);
// write blue char to console
console_text.write(STR_COLOR_BLUE + s_char);
// Morze (dih/dah) send
for (int j = 0; pattern[j] != '\0'; j++) {
baseband::set_morsetx_key(true);
if (pattern[j] == '.') {
chThdSleepMilliseconds(current_timings.dot_ms);
} else if (pattern[j] == '-') {
chThdSleepMilliseconds(current_timings.dash_ms);
}
if (chThdShouldTerminate()) break;
// pause between signs
baseband::set_morsetx_key(false);
chThdSleepMilliseconds(current_timings.symbol_gap);
}
if (chThdShouldTerminate()) break;
// pause between signs
baseband::set_morsetx_key(false);
chThdSleepMilliseconds(current_timings.symbol_gap);
}
if (chThdShouldTerminate()) break;
if (current_timings.char_gap > current_timings.symbol_gap) {
chThdSleepMilliseconds(current_timings.char_gap - current_timings.symbol_gap);
if (current_timings.char_gap > current_timings.symbol_gap) {
chThdSleepMilliseconds(current_timings.char_gap - current_timings.symbol_gap);
}
}
}
}
if (chThdShouldTerminate()) break;
if (chk_loop.value()) {
console_text.write(" ");
for (uint8_t s = 0; s < (loop_seconds * 2); s++) {
if (chThdShouldTerminate()) break;
progressbar.set_value(s + 1);
if (!chk_loop.value()) break;
chThdSleepMilliseconds(500);
}
progressbar.set_value(0);
}
if (!chk_loop.value()) break;
} while (chk_loop.value() && !chThdShouldTerminate());
if (chk_trans.value()) ptt_button_visibility(false);
baseband::set_morsetx_key(false);
@@ -356,13 +381,17 @@ void MorseRadiotxView::ui_toggle() {
wpm_.set_style(Theme::getInstance()->fg_dark);
wpm_.set_focusable(false);
btn_message.set_style(Theme::getInstance()->fg_dark);
btn_message.set_focusable(false);
btn_calls.set_style(Theme::getInstance()->fg_dark);
btn_calls.set_focusable(false);
chk_trans.set_style(Theme::getInstance()->fg_dark);
chk_trans.set_focusable(false);
bandwidth.set_style(Theme::getInstance()->fg_dark);
bandwidth.set_focusable(false);
chk_callsgn.set_style(Theme::getInstance()->fg_dark);
chk_callsgn.set_focusable(false);
wait_time.set_style(Theme::getInstance()->fg_dark);
wait_time.set_focusable(false);
bandwidth.set_style(Theme::getInstance()->fg_dark);
bandwidth.set_focusable(false);
} else {
options_mode.set_style(Theme::getInstance()->bg_darker);
@@ -370,11 +399,15 @@ void MorseRadiotxView::ui_toggle() {
wpm_.set_style(Theme::getInstance()->bg_darker);
wpm_.set_focusable(true);
btn_message.set_style(Theme::getInstance()->bg_darker);
btn_message.set_focusable(true);
btn_calls.set_style(Theme::getInstance()->bg_darker);
btn_calls.set_focusable(true);
chk_trans.set_style(Theme::getInstance()->bg_darker);
chk_trans.set_focusable(true);
chk_callsgn.set_style(Theme::getInstance()->bg_darker);
chk_callsgn.set_focusable(true);
wait_time.set_style(Theme::getInstance()->bg_darker);
wait_time.set_focusable(true);
ptt_button_visibility(true);
tone_.set_style(Theme::getInstance()->bg_darker);
tone_.set_focusable(true);
@@ -118,15 +118,20 @@ class MorseRadiotxView : public ui::View {
{{"AM", 0}, {"FM", 1}, {"DSB", 2}, {"USB", 3}, {"LSB", 4}}};
NumberField tone_{{UI_POS_X(14), UI_POS_Y(0)}, 4, {400, 1400}, 10, ' ', true};
NumberField wpm_{{UI_POS_X(25), UI_POS_Y(0)}, 2, {10, 45}, 1, ' ', true};
FloatField bandwidth{{UI_POS_X(20), UI_POS_Y(3)}, 4, {1.0, 16.0}, 0.1, ' ', true, 1};
NumberField wait_time{{UI_POS_X(10), UI_POS_Y(4)}, 3, {1, 99}, 1, ' ', true}; // wait between tx-es in loop mode (sec)
FloatField bandwidth{{UI_POS_X(6), UI_POS_Y(5)}, 4, {1.0, 16.0}, 0.1, ' ', true, 1};
ProgressBar progressbar{
{UI_POS_X(0), UI_POS_Y(6), screen_width, 16}};
ui::Text txt_msg{{UI_POS_X(0), UI_POS_Y(1), UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "[" + msg_buffer + "] "};
ui::Button btn_message{{UI_POS_X(0), UI_POS_Y(2), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)}, "Message"};
ui::Button btn_calls{{UI_POS_X(0), UI_POS_Y(4), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)}, (call_sign.empty()) ? "call sign?" : call_sign};
ui::Button btn_calls{{UI_POS_X(0), UI_POS_Y(3), UI_POS_WIDTH(11), UI_POS_HEIGHT(1)}, (call_sign.empty()) ? "call sign?" : call_sign};
Checkbox chk_trans{{UI_POS_X(14), UI_POS_Y(2)}, 13, "Manual trans.", true};
Checkbox chk_callsgn{{UI_POS_X(14), UI_POS_Y(4)}, 13, "Call sign", true};
ui::Text txt_last{{UI_POS_X(10), UI_POS_Y(5), UI_POS_WIDTH_REMAINING(10), UI_POS_HEIGHT(1)}, ""};
ui::Console console_text{{UI_POS_X(0), UI_POS_Y(7), UI_POS_MAXWIDTH, UI_POS_HEIGHT_REMAINING(14)}};
Checkbox chk_callsgn{{UI_POS_X(14), UI_POS_Y(3)}, 9, "Call sign", true};
Checkbox chk_loop{{UI_POS_X(14), UI_POS_Y(4)}, 4, "loop", true};
ui::Text txt_last{{UI_POS_X(10), UI_POS_Y(7), UI_POS_WIDTH_REMAINING(10), UI_POS_HEIGHT(1)}, ""};
ui::Console console_text{{UI_POS_X(0), UI_POS_Y(9), UI_POS_MAXWIDTH, UI_POS_HEIGHT_REMAINING(14)}};
ui::Button btn_clear{{UI_POS_X(0), UI_POS_Y_BOTTOM(5), UI_POS_WIDTH(5), UI_POS_HEIGHT(1)}, "CLR"};
ui::Button btn_ptt{{UI_POS_X_CENTER(12), UI_POS_Y_BOTTOM(7), UI_POS_WIDTH(12), UI_POS_HEIGHT(3)}, "PTT"};
@@ -135,10 +140,11 @@ class MorseRadiotxView : public ui::View {
{{UI_POS_X(9), UI_POS_Y(0)}, "Tone:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(18), UI_POS_Y(0)}, "Hz", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(21), UI_POS_Y(0)}, "WPM:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(14), UI_POS_Y(3)}, "BandW:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(24), UI_POS_Y(3)}, "kHz", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(5)}, "Last seq:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(6)}, "Sent Message:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(5)}, "BandW:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(10), UI_POS_Y(5)}, "kHz", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(4)}, "Wait time: ", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(7)}, "Last seq:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(8)}, "Sent Message:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X_RIGHT(7), UI_POS_Y_BOTTOM(5)}, "Vol.:", Theme::getInstance()->fg_light->foreground},
};
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_noaaapt_rx.application_information"),
0x78,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_ook_editor.application_information"),
0xE0,
0x07,
},
/*.icon_color = */ ui::Color::orange().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_ookbrute.application_information"), us
0xE0,
0x07,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
+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_p25_tx.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::p25_tx {
void initialize_app(ui::NavigationView& nav) {
nav.push<P25TxView>();
}
} // namespace ui::external_app::p25_tx
extern "C" {
__attribute__((section(".external_app.app_p25_tx.application_information"), used))
application_information_t _application_information_p25_tx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::p25_tx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "P25 TX",
/*.bitmap_data = */ {
0x00,
0x00,
0xFE,
0x7F,
0x02,
0x40,
0xFA,
0x5F,
0x0A,
0x50,
0x0A,
0x50,
0xFA,
0x5F,
0x02,
0x40,
0x02,
0x40,
0xE2,
0x47,
0x22,
0x44,
0xE2,
0x47,
0x02,
0x40,
0x02,
0x40,
0xFE,
0x7F,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = */ {'P', '2', '5', 'T'},
/*.m4_app_offset = */ 0x00000000,
};
}
+282
View File
@@ -0,0 +1,282 @@
/*
* 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_p25_tx.hpp"
#include "portapack.hpp"
#include "transmitter_model.hpp"
#include "baseband_api.hpp"
#include "ui_freq_field.hpp"
#include <cstring>
using namespace portapack;
namespace ui::external_app::p25_tx {
static constexpr uint8_t DUID_TSBK = 0x07;
static constexpr uint8_t SS_TSCC = 0x02;
// BCH(63,16) generator matrix from TIA-102.BAAA-A (ccemu/p25/bch.go)
static const uint64_t bch_matrix[16] = {
0x8000cd930bdd3b2aULL,
0x4000ab5a8e33a6beULL,
0x2000983e4cc4e874ULL,
0x10004c1f2662743aULL,
0x0800eb9c98ec0136ULL,
0x0400b85d47ab3bb0ULL,
0x02005c2ea3d59dd8ULL,
0x01002e1751eaceecULL,
0x0080170ba8f56776ULL,
0x0040c616dfa78890ULL,
0x0020630b6fd3c448ULL,
0x00103185b7e9e224ULL,
0x000818c2dbf4f112ULL,
0x0004c1f2662743a2ULL,
0x0002ad6a38ce9afbULL,
0x00019b2617ba7657ULL,
};
static uint64_t bch_encode(uint16_t data) {
uint64_t cw = 0;
for (int i = 0; i < 16; i++)
if (data & (0x8000u >> i))
cw ^= bch_matrix[i];
return cw;
}
// CRC-CCITT bit-by-bit, init=0, final XOR=0xFFFF (ccemu/p25/crc.go)
static uint16_t crc_ccitt_80(uint16_t high, uint64_t low) {
uint32_t crc = 0;
for (int i = 15; i >= 0; i--) {
crc <<= 1;
if (((crc >> 16) ^ ((high >> i) & 1)) & 1) crc ^= 0x1021;
}
for (int i = 63; i >= 0; i--) {
crc <<= 1;
if (((crc >> 16) ^ ((uint32_t)((low >> i) & 1))) & 1) crc ^= 0x1021;
}
return (uint16_t)((crc & 0xFFFF) ^ 0xFFFF);
}
// 1/2-rate trellis: [state][inputDibit]={outDibit0,outDibit1} (ccemu/p25/trellis.go)
static const uint8_t trellis_table[4][4][2] = {
{{0, 2}, {3, 0}, {0, 1}, {3, 3}},
{{3, 2}, {0, 0}, {3, 1}, {0, 3}},
{{2, 1}, {1, 3}, {2, 2}, {1, 0}},
{{1, 1}, {2, 3}, {1, 2}, {2, 0}},
};
static void trellis_encode(const uint8_t* in48, uint8_t* out98) {
uint8_t state = 0;
for (int i = 0; i < 49; i++) {
uint8_t d = (i < 48) ? in48[i] : 0;
out98[i * 2 + 0] = trellis_table[state][d][0];
out98[i * 2 + 1] = trellis_table[state][d][1];
state = d;
}
}
static void data_interleave(const uint8_t* in98, uint8_t* out98) {
int idx = 0;
for (int j = 0; j < 97; j += 8) {
out98[idx++] = in98[j];
out98[idx++] = in98[j + 1];
}
for (int i = 2; i < 7; i += 2)
for (int j = 0; j < 89; j += 8) {
out98[idx++] = in98[i + j];
out98[idx++] = in98[i + j + 1];
}
}
static int insert_status(const uint8_t* data, int dlen, uint8_t* out, uint8_t ss) {
int num_ss = (dlen + 34) / 35, remaining = num_ss, oi = 0, i = 1;
for (int d = 0; d < dlen; d++) {
out[oi++] = data[d];
if ((i % 35 == 0) && remaining > 0) {
out[oi++] = ss;
remaining--;
}
i++;
}
while (remaining > 0) {
out[oi++] = 0;
if (i % 35 == 0) {
out[oi++] = ss;
remaining--;
}
i++;
}
return oi;
}
static void build_tsbk(uint8_t* out12, uint8_t opcode, uint64_t args) {
uint16_t high = (1u << 15) | ((uint16_t)opcode << 8);
uint16_t crc = crc_ccitt_80(high, args);
out12[0] = (uint8_t)(high >> 8);
out12[1] = (uint8_t)high;
for (int i = 0; i < 8; i++) out12[2 + i] = (uint8_t)(args >> (56 - 8 * i));
out12[10] = (uint8_t)(crc >> 8);
out12[11] = (uint8_t)crc;
}
static void tsbk_iden_up(uint8_t* out12, uint64_t freq_hz) {
uint64_t args = ((uint64_t)100 << 51) | ((uint64_t)100 << 32) | ((freq_hz / 5) & 0xFFFFFFFF);
build_tsbk(out12, 0x3D, args);
}
static void tsbk_net_status(uint8_t* out12, uint32_t wacn, uint16_t sysid) {
build_tsbk(out12, 0x3B, ((uint64_t)(wacn & 0xFFFFF) << 36) | ((uint64_t)(sysid & 0xFFF) << 24));
}
static void tsbk_grp_v_grant(uint8_t* out12, uint8_t chan_id, uint16_t chan_num, uint16_t tg) {
uint64_t ch = ((uint64_t)(chan_id & 0xF) << 12) | (chan_num & 0xFFF);
// opts: bit1=group
uint64_t args = ((uint64_t)0x02 << 56) | (ch << 40) | ((uint64_t)tg << 24);
build_tsbk(out12, 0x00, args);
}
static void tsbk_rfss_status(uint8_t* out12, uint16_t sysid, uint8_t rfssid, uint8_t siteid) {
build_tsbk(out12, 0x3A, ((uint64_t)(sysid & 0xFFF) << 40) | ((uint64_t)rfssid << 32) | ((uint64_t)siteid << 24));
}
static int build_frame(uint8_t* out, uint16_t nac, const uint8_t* tsbk12) {
uint8_t pre[160];
int idx = 0;
static const uint64_t FSW = 0x5575F5FF77FFULL;
for (int i = 0; i < 24; i++) pre[idx++] = (uint8_t)((FSW >> (46 - i * 2)) & 3);
uint64_t nid = bch_encode((uint16_t)((nac << 4) | DUID_TSBK));
for (int i = 0; i < 32; i++) pre[idx++] = (uint8_t)((nid >> (62 - i * 2)) & 3);
uint8_t in_d[48];
for (int i = 0; i < 12; i++) {
in_d[i * 4 + 0] = (tsbk12[i] >> 6) & 3;
in_d[i * 4 + 1] = (tsbk12[i] >> 4) & 3;
in_d[i * 4 + 2] = (tsbk12[i] >> 2) & 3;
in_d[i * 4 + 3] = (tsbk12[i] >> 0) & 3;
}
uint8_t enc[98], ilv[98];
trellis_encode(in_d, enc);
data_interleave(enc, ilv);
memcpy(&pre[idx], ilv, 98);
idx += 98;
return insert_status(pre, idx, out, SS_TSCC);
}
static constexpr int TX_BUF_SIZE = 512;
static int fill_tx_buffer(uint8_t* buf, uint16_t nac, uint32_t wacn, uint16_t sysid, uint8_t rfssid, uint8_t siteid, uint64_t freq_hz, uint16_t tg, uint16_t vch, int& tsbk_idx) {
memset(buf, 0, TX_BUF_SIZE);
int total = 0;
uint8_t tsbk[12];
while (true) {
switch (tsbk_idx % 5) {
case 0:
tsbk_iden_up(tsbk, freq_hz);
break;
case 1:
tsbk_net_status(tsbk, wacn, sysid);
break;
case 2:
tsbk_rfss_status(tsbk, sysid, rfssid, siteid);
break;
case 3:
tsbk_grp_v_grant(tsbk, 0, vch, tg);
break;
default:
tsbk_net_status(tsbk, wacn, sysid);
break;
}
tsbk_idx++;
uint8_t probe[200];
int flen = build_frame(probe, nac, tsbk);
if (total + flen > TX_BUF_SIZE) break;
memcpy(&buf[total], probe, flen);
total += flen;
}
return total;
}
void P25TxView::start_tx() {
uint8_t dibits[TX_BUF_SIZE];
int len = fill_tx_buffer(dibits,
(uint16_t)field_nac.to_integer(), (uint32_t)field_wacn.to_integer(),
(uint16_t)field_sysid.to_integer(), (uint8_t)field_rfssid.to_integer(),
(uint8_t)field_siteid.to_integer(), (uint64_t)transmitter_model.target_frequency(),
(uint16_t)field_tg.to_integer(), (uint16_t)field_vch.to_integer(),
tsbk_idx_);
transmitter_model.enable();
tx_view.set_transmitting(true);
text_status.set("TX TSCC");
transmitting = true;
baseband::set_p25tx_data(dibits, (uint16_t)len);
}
void P25TxView::stop_tx() {
transmitting = false;
transmitter_model.disable();
tx_view.set_transmitting(false);
text_status.set("Ready");
tsbk_idx_ = 0;
}
void P25TxView::on_tx_progress(const uint32_t, const bool done) {
if (done && transmitting) {
uint8_t dibits[TX_BUF_SIZE];
int len = fill_tx_buffer(dibits,
(uint16_t)field_nac.to_integer(), (uint32_t)field_wacn.to_integer(),
(uint16_t)field_sysid.to_integer(), (uint8_t)field_rfssid.to_integer(),
(uint8_t)field_siteid.to_integer(), (uint64_t)transmitter_model.target_frequency(),
(uint16_t)field_tg.to_integer(), (uint16_t)field_vch.to_integer(),
tsbk_idx_);
baseband::set_p25tx_data(dibits, (uint16_t)len);
}
}
P25TxView::P25TxView(NavigationView& nav)
: nav_{nav} {
add_children({&labels_, &field_nac, &field_sysid, &field_wacn,
&field_rfssid, &field_siteid, &field_tg, &field_vch,
&text_status, &tx_view});
field_nac.set_value(0x293);
field_wacn.set_value(0xBEEF0);
field_sysid.set_value(0x001);
field_rfssid.set_value(1);
field_siteid.set_value(1);
field_tg.set_value(1);
field_vch.set_value(1);
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
tx_view.on_start = [this]() { start_tx(); };
tx_view.on_stop = [this]() { stop_tx(); };
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); };
};
}
P25TxView::~P25TxView() {
if (transmitting)
stop_tx();
transmitter_model.disable();
baseband::shutdown();
}
void P25TxView::focus() {
field_nac.focus();
}
} // namespace ui::external_app::p25_tx
+96
View File
@@ -0,0 +1,96 @@
/*
* 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.
*/
#ifndef __UI_P25_TX
#define __UI_P25_TX
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_transmitter.hpp"
#include "ui_freq_field.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "message.hpp"
namespace ui::external_app::p25_tx {
class P25TxView : public View {
public:
explicit P25TxView(NavigationView& nav);
~P25TxView();
void focus() override;
std::string title() const override { return "P25 TX"; }
private:
void start_tx();
void stop_tx();
void on_tx_progress(const uint32_t progress, const bool done);
NavigationView& nav_;
TxRadioState radio_state_{
155'000'000,
12500,
2'400'000};
app_settings::SettingsManager settings_{
"tx_p25_tx",
app_settings::Mode::TX};
Labels labels_{{
{{UI_POS_X(0), UI_POS_Y(0)}, "NAC:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(9), UI_POS_Y(0)}, "SYS:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(1)}, "WACN:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(2)}, "RFSS:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(9), UI_POS_Y(2)}, "SITE:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(3)}, "TG:", ui::Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(9), UI_POS_Y(3)}, "VCH:", ui::Theme::getInstance()->fg_light->foreground},
}};
SymField field_nac{{UI_POS_X(4), UI_POS_Y(0)}, 3, SymField::Type::Hex};
SymField field_sysid{{UI_POS_X(13), UI_POS_Y(0)}, 3, SymField::Type::Hex};
SymField field_wacn{{UI_POS_X(5), UI_POS_Y(1)}, 5, SymField::Type::Hex};
SymField field_rfssid{{UI_POS_X(5), UI_POS_Y(2)}, 2, SymField::Type::Hex};
SymField field_siteid{{UI_POS_X(14), UI_POS_Y(2)}, 2, SymField::Type::Hex};
SymField field_tg{{UI_POS_X(3), UI_POS_Y(3)}, 4, SymField::Type::Hex};
SymField field_vch{{UI_POS_X(13), UI_POS_Y(3)}, 3, SymField::Type::Hex};
Text text_status{{0, UI_POS_Y(4), UI_POS_MAXWIDTH, UI_POS_DEFAULT_HEIGHT}, "Ready"};
TransmitterView tx_view{
(int16_t)UI_POS_Y_BOTTOM(5),
12500,
0};
bool transmitting{false};
int tsbk_idx_{0};
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);
}};
};
} // namespace ui::external_app::p25_tx
#endif /* __UI_P25_TX */
+34 -12
View File
@@ -44,7 +44,7 @@ POCSAGTXView::~POCSAGTXView() {
baseband::shutdown();
}
void POCSAGTXView::on_remote(const PocsagTosendMessage data) {
void POCSAGTXView::on_remete(const PocsagTosendMessage data) {
// check if still sending or not
size_t tmp = 0;
if (data.baud == 1200) tmp = 1;
@@ -56,7 +56,8 @@ void POCSAGTXView::on_remote(const PocsagTosendMessage data) {
if (data.function == 'C') tmp = 2;
if (data.function == 'D') tmp = 3;
options_function.set_selected_index(tmp);
options_phase.set_selected_index(data.phase == 'P' ? 0 : 1);
/* 'S' = Standard (CCIR Rec. 584 polarity), 'I' = Inverted */
options_polarity.set_selected_index(data.polarity == 'S' ? 0 : 1);
field_address.set_value(data.addr);
message = (char*)data.msg;
buffer = message;
@@ -64,7 +65,7 @@ void POCSAGTXView::on_remote(const PocsagTosendMessage data) {
options_bitrate.dirty();
options_type.dirty();
options_function.dirty();
options_phase.dirty();
options_polarity.dirty();
field_address.dirty();
text_message.dirty();
tx_view.focus();
@@ -95,12 +96,34 @@ bool POCSAGTXView::start_tx() {
if (type == MessageType::NUMERIC_ONLY) {
// Check for invalid characters
if (message.find_first_not_of("0123456789SU -][") != std::string::npos) {
const char* p = message.c_str();
bool is_valid = true;
while (*p != '\0') {
const char c = *p;
// Check if char is NOT in the allowed set
if (!((c >= '0' && c <= '9') || c == 'S' || c == 'U' ||
c == ' ' || c == '-' || c == '[' || c == ']')) {
is_valid = false;
break;
}
p++;
}
if (!is_valid) {
nav_.display_modal("Bad message", "A numeric only message must\nonly contain:\n0123456789SU][- or space.");
return false;
}
}
MessageType phase = (MessageType)options_phase.selected_index_value();
/*
* TX polarity inversion (CCIR Rec. 584):
*
* The FSK modulator (proc_fsk.cpp) maps bit 1 to positive deviation.
* Standard POCSAG requires bit 1 to negative deviation.
*
* "Standard" (value 0): invert codewords so that original bit 1 becomes
* bit 0 in the modulator, producing negative deviation. This is the standard.
* "Inverted" (value 1): send codewords as-is. Bit 1 produces positive deviation.
*/
bool invert_polarity = (options_polarity.selected_index_value() == 0);
pocsag_encode(type, BCH_code, options_function.selected_index_value(), message, address, codewords);
@@ -118,10 +141,7 @@ bool POCSAGTXView::start_tx() {
bi = 0;
for (i = 0; i < codewords.size(); i++) {
if (phase == 0)
codeword = ~(codewords[i]);
else
codeword = codewords[i];
codeword = invert_polarity ? ~(codewords[i]) : codewords[i];
data_ptr[bi++] = (codeword >> 24) & 0xFF;
data_ptr[bi++] = (codeword >> 16) & 0xFF;
@@ -166,15 +186,17 @@ POCSAGTXView::POCSAGTXView(
&field_address,
&options_type,
&options_function,
&options_phase,
&options_polarity,
&text_message,
&text_message_l2,
&button_message,
&progressbar,
&tx_view});
options_bitrate.set_selected_index(1); // 1200bps
options_type.set_selected_index(0); // Address only
options_bitrate.set_selected_index(1); // 1200 bps
options_type.set_selected_index(2); // Alphanumeric
options_function.set_selected_index(0); // Function A
options_polarity.set_selected_index(0); // Standard (CCIR Rec. 584)
field_address.set_value(persistent_memory::pocsag_last_address());
+21 -13
View File
@@ -76,7 +76,7 @@ class POCSAGTXView : public View {
void on_set_text(NavigationView& nav);
void on_tx_progress(const uint32_t progress, const bool done);
void on_remote(const PocsagTosendMessage data);
void on_remete(const PocsagTosendMessage data);
bool start_tx();
Labels labels{
@@ -84,7 +84,7 @@ class POCSAGTXView : public View {
{{3 * 8, 6 * 8}, "Address:", Theme::getInstance()->fg_light->foreground},
{{6 * 8, 8 * 8}, "Type:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 10 * 8}, "Function:", Theme::getInstance()->fg_light->foreground},
{{5 * 8, 12 * 8}, "Phase:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 12 * 8}, "Polarity:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), 14 * 8}, "Message:", Theme::getInstance()->fg_light->foreground}};
OptionsField options_bitrate{
@@ -113,12 +113,20 @@ class POCSAGTXView : public View {
{"C", 2},
{"D", 3}}};
OptionsField options_phase{
/*
* TX polarity (CCIR Rec. 584):
* "Standard" (value 0): bit 1 = negative deviation (CCIR Rec. 584 standard).
* Codewords are bitwise-inverted before the FSK modulator
* because the modulator maps bit 1 to positive deviation.
* "Inverted" (value 1): bit 1 = positive deviation (non-standard).
* Codewords are sent as-is to the modulator.
*/
OptionsField options_polarity{
{11 * 8, 12 * 8},
1,
8,
{
{"P", 0},
{"N", 1},
{"Standard", 0},
{"Inverted", 1},
}};
Text text_message{
@@ -140,19 +148,19 @@ class POCSAGTXView : public View {
10000,
9};
MessageHandlerRegistration message_handler_tx_remete{
Message::ID::PocsagTosend,
[this](const Message* const p) {
const auto message = *reinterpret_cast<const PocsagTosendMessage*>(p);
this->on_remete(message);
}};
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_tx_remote{
Message::ID::PocsagTosend,
[this](const Message* const p) {
const auto message = *reinterpret_cast<const PocsagTosendMessage*>(p);
this->on_remote(message);
}};
};
} /* namespace ui::external_app::pocsag_tx */
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_rtty_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,
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_rtty_tx.application_information"), use
0x00,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
+1 -1
View File
@@ -69,7 +69,7 @@ __attribute__((section(".external_app.app_same_tx.application_information"), use
0x00,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
+1 -1
View File
@@ -58,7 +58,7 @@ __attribute__((section(".external_app.app_shoppingcart_lock.application_informat
0x7E,
0x00,
},
/*.icon_color = */ ui::Color::red().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::UTILITIES,
/*.desired_menu_position = */ -1,
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_soundboard.application_information"),
0xF0,
0xFF,
},
/*.icon_color = */ ui::Color::orange().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_spainter.application_information"), us
0xC0,
0x01,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
+1 -1
View File
@@ -72,7 +72,7 @@ __attribute__((section(".external_app.app_time_sink.application_information"), u
0x00,
0x00,
},
/*.icon_color = */ ui::Color::cyan().v,
/*.icon_color = */ ui::Color::green().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
+86
View File
@@ -0,0 +1,86 @@
/*
* Copyright (C) 2024 PortaPack Mayhem
*
* 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_two_tone_pager.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::two_tone_pager {
void initialize_app(ui::NavigationView& nav) {
nav.push<TwoTonePagerView>();
}
} // namespace ui::external_app::two_tone_pager
extern "C" {
__attribute__((section(".external_app.app_two_tone_pager.application_information"), used)) application_information_t _application_information_two_tone_pager = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::two_tone_pager::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "2-Tone TX",
/*.bitmap_data = */ {
// 16×16 pager icon — two-tone radio / pager device
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::orange().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
// Uses the proc_tones baseband processor (same as Morse TX)
/*.m4_app_tag = portapack::spi_flash::image_tag_tones */ {'P', 'T', 'O', 'N'},
/*.m4_app_offset = */ 0x00000000, // filled at compile time
};
} // extern "C"
@@ -0,0 +1,616 @@
/*
* Copyright (C) 2024 PortaPack Mayhem
*
* 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_two_tone_pager.hpp"
#include "portapack.hpp"
#include "baseband_api.hpp"
#include "portapack_shared_memory.hpp"
#include "string_format.hpp"
#include "theme.hpp"
#include <algorithm>
#include <cstring>
using namespace portapack;
namespace ui::external_app::two_tone_pager {
// ---------------------------------------------------------------------------
// Tone tables — store only freq×10 values; names are generated at runtime
// to keep static data small and avoid const-char-pointer patching issues.
// ---------------------------------------------------------------------------
static const uint32_t MOTO_FREQS[45] = {
2885,
3047,
3217,
3396,
3586,
3786,
3998,
4221,
4457,
4705,
4968,
5246,
5539,
5848,
6174,
6519,
6883,
7268,
7674,
8102,
8555,
9032,
9537,
10073,
10642,
11225,
11247,
11534,
11852,
11885,
12178,
12514,
12555,
12858,
13258,
13576,
13950,
13996,
14768,
15579,
16430,
17325,
18262,
19245,
20275,
};
// Index 0 = None (0), indices 1-50 = standard CTCSS tones
static const uint32_t CTCSS_FREQS[51] = {
0,
670,
719,
744,
770,
797,
825,
854,
885,
915,
948,
974,
1000,
1035,
1072,
1109,
1148,
1188,
1230,
1273,
1318,
1365,
1413,
1462,
1500,
1514,
1567,
1598,
1622,
1655,
1679,
1713,
1738,
1773,
1799,
1835,
1862,
1899,
1928,
1966,
1995,
2035,
2065,
2107,
2181,
2257,
2291,
2336,
2418,
2503,
2541,
};
// Generate a display name from a freq×10 value ("288.5Hz", "None" for 0)
static std::string freq_name(uint32_t freq_x10) {
if (freq_x10 == 0) return "None";
return to_string_dec_uint(freq_x10 / 10) + "." +
to_string_dec_uint(freq_x10 % 10) + "Hz";
}
// Common timing profiles used in the field
struct TimingPreset {
uint32_t dur_a; // ms
uint32_t dur_b; // ms
uint32_t gap; // ms
};
static const TimingPreset TIMING_PRESETS[4] = {
{1000, 3000, 0}, // Moto Std
{700, 1000, 0}, // Short Alert
{2000, 1000, 0}, // Fire Std
{3000, 3000, 0}, // Long Alert
};
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// Parse one unsigned decimal integer from *p, advancing p past the digits and
// an optional trailing comma.
static uint32_t parse_uint_field(const char*& p) {
uint32_t v = 0;
while (*p >= '0' && *p <= '9')
v = v * 10 + (*p++ - '0');
if (*p == ',')
++p;
return v;
}
// Phase-delta for the 32-bit sine-table accumulator used by proc_tones.
// delta = freq_hz * 2^32 / sample_rate
// Using freq_x10 to avoid floating-point: delta = (freq_x10 * 2^32) / (sample_rate * 10)
uint32_t TwoTonePagerView::tone_delta(uint32_t freq_x10) const {
if (freq_x10 == 0) return 0;
return static_cast<uint32_t>(
(static_cast<uint64_t>(freq_x10) << 32) /
(static_cast<uint64_t>(SAMPLE_RATE) * 10ULL));
}
uint32_t TwoTonePagerView::ms_to_samples(uint32_t ms) const {
return static_cast<uint32_t>(
(static_cast<uint64_t>(ms) * SAMPLE_RATE) / 1000ULL);
}
// ---------------------------------------------------------------------------
// Preset encode / decode
// ---------------------------------------------------------------------------
std::string TwoTonePagerView::encode_preset() const {
return to_string_dec_uint(ctcss_idx) + "," +
to_string_dec_uint(tone_a_idx) + "," +
to_string_dec_uint(tone_b_idx) + "," +
to_string_dec_uint(dur_a) + "," +
to_string_dec_uint(dur_b) + "," +
to_string_dec_uint(gap_ms) + "," +
to_string_dec_uint(custom_freq_a_hz) + "," +
to_string_dec_uint(custom_freq_b_hz);
}
void TwoTonePagerView::decode_preset(const std::string& s) {
const char* p = s.c_str();
uint32_t ci = parse_uint_field(p);
uint32_t ai = parse_uint_field(p);
uint32_t bi = parse_uint_field(p);
uint32_t da = parse_uint_field(p);
uint32_t db = parse_uint_field(p);
uint32_t gp = parse_uint_field(p);
uint32_t cfa = (*p != '\0') ? parse_uint_field(p) : 405;
uint32_t cfb = (*p != '\0') ? parse_uint_field(p) : 814;
ctcss_idx = std::min(ci, static_cast<uint32_t>(CTCSS_COUNT - 1));
tone_a_idx = std::min(ai, CUSTOM_TONE_IDX);
tone_b_idx = std::min(bi, CUSTOM_TONE_IDX);
dur_a = std::max(uint32_t{100}, std::min(da, uint32_t{9900}));
dur_b = std::max(uint32_t{100}, std::min(db, uint32_t{9900}));
gap_ms = std::min(gp, uint32_t{9900});
custom_freq_a_hz = std::max(uint32_t{100}, std::min(cfa, uint32_t{9999}));
custom_freq_b_hz = std::max(uint32_t{100}, std::min(cfb, uint32_t{9999}));
}
std::string& TwoTonePagerView::slot_ref(uint32_t slot) {
switch (slot) {
case 2:
return preset_2;
case 3:
return preset_3;
case 4:
return preset_4;
case 5:
return preset_5;
default:
return preset_1;
}
}
std::string& TwoTonePagerView::slot_name_ref(uint32_t slot) {
switch (slot) {
case 2:
return preset_name_2;
case 3:
return preset_name_3;
case 4:
return preset_name_4;
case 5:
return preset_name_5;
default:
return preset_name_1;
}
}
void TwoTonePagerView::update_slot_name_display() {
const auto& name = slot_name_ref(preset_slot);
std::string display = name.empty() ? "(none)" : name;
if (display.size() > 8) display = display.substr(0, 8);
text_slot_name.set(display);
}
void TwoTonePagerView::save_preset(uint32_t slot) {
slot_ref(slot) = encode_preset();
text_status.set("Saved to slot " + to_string_dec_uint(slot));
}
void TwoTonePagerView::load_preset(uint32_t slot) {
decode_preset(slot_ref(slot));
// Update all UI fields without firing their on_change callbacks
options_ctcss.set_selected_index(ctcss_idx, false);
options_tone_a.set_selected_index(tone_a_idx, false);
options_tone_b.set_selected_index(tone_b_idx, false);
field_dur_a.set_value(static_cast<int32_t>(dur_a), false);
field_dur_b.set_value(static_cast<int32_t>(dur_b), false);
field_gap.set_value(static_cast<int32_t>(gap_ms), false);
symfield_custom_a.set_value(custom_freq_a_hz);
symfield_custom_b.set_value(custom_freq_b_hz);
options_timing.set_selected_index(detect_timing_preset(), false);
update_tx_time();
update_slot_name_display();
text_status.set("Loaded slot " + to_string_dec_uint(slot));
}
// ---------------------------------------------------------------------------
// Timing presets
// ---------------------------------------------------------------------------
size_t TwoTonePagerView::detect_timing_preset() const {
for (size_t i = 0; i < 4; i++) {
if (TIMING_PRESETS[i].dur_a == dur_a &&
TIMING_PRESETS[i].dur_b == dur_b &&
TIMING_PRESETS[i].gap == gap_ms)
return i;
}
return 4; // "Custom"
}
void TwoTonePagerView::apply_timing_preset(size_t idx) {
if (idx >= 4) return; // "Custom" — do not override current values
dur_a = TIMING_PRESETS[idx].dur_a;
dur_b = TIMING_PRESETS[idx].dur_b;
gap_ms = TIMING_PRESETS[idx].gap;
field_dur_a.set_value(static_cast<int32_t>(dur_a), false);
field_dur_b.set_value(static_cast<int32_t>(dur_b), false);
field_gap.set_value(static_cast<int32_t>(gap_ms), false);
update_tx_time();
}
// ---------------------------------------------------------------------------
// UI helpers
// ---------------------------------------------------------------------------
void TwoTonePagerView::update_tx_time() {
uint32_t total_ms = dur_a + gap_ms + dur_b;
std::string name_a = (tone_a_idx == CUSTOM_TONE_IDX)
? to_string_dec_uint(custom_freq_a_hz) + "Hz"
: freq_name(MOTO_FREQS[tone_a_idx]);
std::string name_b = (tone_b_idx == CUSTOM_TONE_IDX)
? to_string_dec_uint(custom_freq_b_hz) + "Hz"
: freq_name(MOTO_FREQS[tone_b_idx]);
text_time.set("TX time: " +
to_string_dec_uint(total_ms / 1000) + "." +
to_string_dec_uint((total_ms / 100) % 10) + "s" +
" A:" + name_a + " B:" + name_b);
}
// ---------------------------------------------------------------------------
// Transmission
// ---------------------------------------------------------------------------
bool TwoTonePagerView::start_tx() {
auto& td = shared_memory.bb_data.tones_data;
const uint32_t freq_a_x10 = (tone_a_idx == CUSTOM_TONE_IDX)
? custom_freq_a_hz * 10
: MOTO_FREQS[tone_a_idx];
const uint32_t freq_b_x10 = (tone_b_idx == CUSTOM_TONE_IDX)
? custom_freq_b_hz * 10
: MOTO_FREQS[tone_b_idx];
const uint32_t delta_a = tone_delta(freq_a_x10);
const uint32_t delta_b = tone_delta(freq_b_x10);
const uint32_t delta_c = tone_delta(CTCSS_FREQS[ctcss_idx]);
const uint32_t samp_a = ms_to_samples(dur_a);
const uint32_t samp_b = ms_to_samples(dur_b);
const uint32_t samp_g = ms_to_samples(gap_ms);
const bool with_ctcss = (ctcss_idx > 0);
// Clear tone defs we'll use
memset(&td, 0, sizeof(td));
uint8_t tone_count;
if (!with_ctcss) {
// Single-tone sequential mode
// tone_defs[0] = Tone A, tone_defs[1] = Tone B
td.tone_defs[0].delta = delta_a;
td.tone_defs[0].duration = samp_a;
td.tone_defs[1].delta = delta_b;
td.tone_defs[1].duration = samp_b;
if (gap_ms > 0) {
td.silence = samp_g;
td.message[0] = 0; // Tone A
td.message[1] = 255; // Silence (any index ≥ 32 triggers silence)
td.message[2] = 1; // Tone B
tone_count = 3;
} else {
td.message[0] = 0; // Tone A
td.message[1] = 1; // Tone B
tone_count = 2;
}
} else {
// Dual-tone mode: CTCSS mixed simultaneously with pager tones.
//
// proc_tones dual-tone indexing for digit n:
// main delta = tone_deltas[n * 2] = tone_defs[n*2].delta
// sub delta = tone_deltas[n*2 + 1] = tone_defs[n*2+1].delta
// duration = tone_durations[n] = tone_defs[n].duration
//
// digit 0 → Tone A (main) + CTCSS (sub), duration from tone_defs[0]
// digit 1 → Tone B (main) + CTCSS (sub), duration from tone_defs[1]
td.tone_defs[0].delta = delta_a; // digit 0 main
td.tone_defs[0].duration = samp_a;
td.tone_defs[1].delta = delta_c; // digit 0 sub (CTCSS); also digit 1 duration source
td.tone_defs[1].duration = samp_b;
td.tone_defs[2].delta = delta_b; // digit 1 main (Tone B)
td.tone_defs[2].duration = 0; // duration for digit 1 comes from tone_defs[1]
td.tone_defs[3].delta = delta_c; // digit 1 sub (CTCSS)
td.tone_defs[3].duration = 0;
if (gap_ms > 0) {
td.silence = samp_g;
td.message[0] = 0;
td.message[1] = 255;
td.message[2] = 1;
tone_count = 3;
} else {
td.message[0] = 0;
td.message[1] = 1;
tone_count = 2;
}
}
progressbar.set_max(tone_count);
progressbar.set_value(0);
transmitter_model.set_baseband_bandwidth(1'750'000);
transmitter_model.enable();
baseband::set_tones_config(
transmitter_model.channel_bandwidth(),
0, // no pre-silence
tone_count,
with_ctcss, // dual_tone flag
false); // no audio monitor output
return true;
}
void TwoTonePagerView::stop_tx() {
transmitter_model.disable();
baseband::kill_tone();
tx_view.set_transmitting(false);
text_status.set("Stopped.");
}
void TwoTonePagerView::on_tx_progress(uint32_t progress, bool done) {
if (done) {
transmitter_model.disable();
progressbar.set_value(0);
tx_view.set_transmitting(false);
text_status.set("Done.");
} else {
progressbar.set_value(progress);
}
}
// ---------------------------------------------------------------------------
// View lifecycle
// ---------------------------------------------------------------------------
void TwoTonePagerView::focus() {
options_tone_a.focus();
}
TwoTonePagerView::~TwoTonePagerView() {
transmitter_model.disable();
baseband::shutdown();
}
TwoTonePagerView::TwoTonePagerView(NavigationView& nav)
: nav_(nav) {
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
// Clamp restored settings to valid ranges before touching UI
ctcss_idx = std::min(ctcss_idx, static_cast<uint32_t>(CTCSS_COUNT - 1));
tone_a_idx = std::min(tone_a_idx, CUSTOM_TONE_IDX);
tone_b_idx = std::min(tone_b_idx, CUSTOM_TONE_IDX);
dur_a = std::max(uint32_t{100}, std::min(dur_a, uint32_t{9900}));
dur_b = std::max(uint32_t{100}, std::min(dur_b, uint32_t{9900}));
gap_ms = std::min(gap_ms, uint32_t{9900});
preset_slot = std::max(uint32_t{1}, std::min(preset_slot, uint32_t{5}));
custom_freq_a_hz = std::max(uint32_t{100}, std::min(custom_freq_a_hz, uint32_t{9999}));
custom_freq_b_hz = std::max(uint32_t{100}, std::min(custom_freq_b_hz, uint32_t{9999}));
// Build CTCSS options list
{
std::vector<std::pair<std::string, int32_t>> opts;
opts.reserve(CTCSS_COUNT);
for (size_t i = 0; i < CTCSS_COUNT; i++)
opts.push_back({freq_name(CTCSS_FREQS[i]), static_cast<int32_t>(i)});
options_ctcss.set_options(std::move(opts));
}
// Build Motorola tone options (same pool for both A and B); "Custom" appended
{
std::vector<std::pair<std::string, int32_t>> opts;
opts.reserve(MOTO_TONE_COUNT + 1);
for (size_t i = 0; i < MOTO_TONE_COUNT; i++)
opts.push_back({freq_name(MOTO_FREQS[i]), static_cast<int32_t>(i)});
opts.push_back({"Custom", static_cast<int32_t>(CUSTOM_TONE_IDX)});
options_tone_a.set_options(opts);
options_tone_b.set_options(std::move(opts));
}
add_children({&labels,
&options_ctcss,
&options_tone_a,
&options_tone_b,
&symfield_custom_a,
&symfield_custom_b,
&field_dur_a,
&field_dur_b,
&field_gap,
&options_timing,
&field_slot,
&button_save,
&button_load,
&text_slot_name,
&text_time,
&text_status,
&progressbar,
&tx_view});
// Restore saved indices into the options / number fields (no callbacks)
options_ctcss.set_selected_index(ctcss_idx, false);
options_tone_a.set_selected_index(tone_a_idx, false);
options_tone_b.set_selected_index(tone_b_idx, false);
symfield_custom_a.set_value(custom_freq_a_hz);
symfield_custom_b.set_value(custom_freq_b_hz);
field_dur_a.set_value(static_cast<int32_t>(dur_a), false);
field_dur_b.set_value(static_cast<int32_t>(dur_b), false);
field_gap.set_value(static_cast<int32_t>(gap_ms), false);
options_timing.set_selected_index(detect_timing_preset(), false);
field_slot.set_value(static_cast<int32_t>(preset_slot), false);
update_tx_time();
update_slot_name_display();
// --- Callbacks ---
options_ctcss.on_change = [this](size_t i, int32_t) {
ctcss_idx = static_cast<uint32_t>(i);
};
options_tone_a.on_change = [this](size_t i, int32_t) {
tone_a_idx = static_cast<uint32_t>(i);
update_tx_time();
};
options_tone_b.on_change = [this](size_t i, int32_t) {
tone_b_idx = static_cast<uint32_t>(i);
update_tx_time();
};
symfield_custom_a.on_change = [this](SymField&) {
uint32_t v = static_cast<uint32_t>(symfield_custom_a.to_integer());
custom_freq_a_hz = std::max(uint32_t{100}, std::min(v, uint32_t{9999}));
update_tx_time();
};
symfield_custom_b.on_change = [this](SymField&) {
uint32_t v = static_cast<uint32_t>(symfield_custom_b.to_integer());
custom_freq_b_hz = std::max(uint32_t{100}, std::min(v, uint32_t{9999}));
update_tx_time();
};
field_dur_a.on_change = [this](int32_t v) {
dur_a = static_cast<uint32_t>(v);
options_timing.set_selected_index(detect_timing_preset(), false);
update_tx_time();
};
field_dur_b.on_change = [this](int32_t v) {
dur_b = static_cast<uint32_t>(v);
options_timing.set_selected_index(detect_timing_preset(), false);
update_tx_time();
};
field_gap.on_change = [this](int32_t v) {
gap_ms = static_cast<uint32_t>(v);
options_timing.set_selected_index(detect_timing_preset(), false);
update_tx_time();
};
options_timing.on_change = [this](size_t i, int32_t) {
apply_timing_preset(i);
};
field_slot.on_change = [this](int32_t v) {
preset_slot = static_cast<uint32_t>(v);
update_slot_name_display();
};
button_save.on_select = [this](Button&) {
text_prompt(nav_, slot_name_ref(preset_slot), 12, ENTER_KEYBOARD_MODE_ALPHA,
[this](std::string&) {
save_preset(preset_slot);
update_slot_name_display();
});
};
button_load.on_select = [this](Button&) {
load_preset(preset_slot);
};
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);
text_status.set("Transmitting...");
}
};
tx_view.on_stop = [this]() {
stop_tx();
};
}
} // namespace ui::external_app::two_tone_pager
@@ -0,0 +1,250 @@
/*
* Copyright (C) 2024 PortaPack Mayhem
*
* 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_TWO_TONE_PAGER_H__
#define __UI_TWO_TONE_PAGER_H__
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_transmitter.hpp"
#include "ui_textentry.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "portapack.hpp"
#include "message.hpp"
#include "string_format.hpp"
namespace ui::external_app::two_tone_pager {
class TwoTonePagerView : public View {
public:
TwoTonePagerView(NavigationView& nav);
~TwoTonePagerView();
TwoTonePagerView(const TwoTonePagerView&) = delete;
TwoTonePagerView(TwoTonePagerView&&) = delete;
TwoTonePagerView& operator=(const TwoTonePagerView&) = delete;
TwoTonePagerView& operator=(TwoTonePagerView&&) = delete;
void focus() override;
std::string title() const override { return "2-Tone TX"; };
private:
NavigationView& nav_;
static constexpr uint32_t SAMPLE_RATE = 1536000;
static constexpr size_t MOTO_TONE_COUNT = 45;
static constexpr size_t CTCSS_COUNT = 51;
static constexpr uint32_t CUSTOM_TONE_IDX = MOTO_TONE_COUNT; // sentinel: one past the table, use custom Hz field
TxRadioState radio_state_{
154280000ULL, // 154.280 MHz — common VHF paging frequency
1750000,
SAMPLE_RATE};
// Persisted settings
uint32_t ctcss_idx{0};
uint32_t tone_a_idx{8}; // 405.3 Hz
uint32_t tone_b_idx{24}; // 813.9 Hz
uint32_t dur_a{1000};
uint32_t dur_b{3000};
uint32_t gap_ms{0};
uint32_t preset_slot{1};
uint32_t custom_freq_a_hz{405}; // used when tone_a_idx == CUSTOM_TONE_IDX
uint32_t custom_freq_b_hz{814};
// Five preset slots — encoded tone/timing data and a user-chosen display name
std::string preset_1{"0,8,24,1000,3000,0"};
std::string preset_2{"0,8,24,1000,3000,0"};
std::string preset_3{"0,8,24,1000,3000,0"};
std::string preset_4{"0,8,24,1000,3000,0"};
std::string preset_5{"0,8,24,1000,3000,0"};
std::string preset_name_1{""};
std::string preset_name_2{""};
std::string preset_name_3{""};
std::string preset_name_4{""};
std::string preset_name_5{""};
app_settings::SettingsManager settings_{
"tx_twotone",
app_settings::Mode::TX,
{
{"ctcss"sv, &ctcss_idx},
{"tone_a"sv, &tone_a_idx},
{"tone_b"sv, &tone_b_idx},
{"dur_a"sv, &dur_a},
{"dur_b"sv, &dur_b},
{"gap"sv, &gap_ms},
{"slot"sv, &preset_slot},
{"custom_a"sv, &custom_freq_a_hz},
{"custom_b"sv, &custom_freq_b_hz},
{"preset1"sv, &preset_1},
{"preset2"sv, &preset_2},
{"preset3"sv, &preset_3},
{"preset4"sv, &preset_4},
{"preset5"sv, &preset_5},
{"pname1"sv, &preset_name_1},
{"pname2"sv, &preset_name_2},
{"pname3"sv, &preset_name_3},
{"pname4"sv, &preset_name_4},
{"pname5"sv, &preset_name_5},
}};
bool start_tx();
void stop_tx();
void on_tx_progress(uint32_t progress, bool done);
void apply_timing_preset(size_t idx);
void save_preset(uint32_t slot);
void load_preset(uint32_t slot);
std::string encode_preset() const;
void decode_preset(const std::string& s);
std::string& slot_ref(uint32_t slot);
std::string& slot_name_ref(uint32_t slot);
uint32_t tone_delta(uint32_t freq_x10) const;
uint32_t ms_to_samples(uint32_t ms) const;
size_t detect_timing_preset() const;
void update_tx_time();
void update_slot_name_display();
// --- Widgets ---
Labels labels{
{{0 * 8, 1 * 16}, "CTCSS:", Theme::getInstance()->fg_light->foreground},
{{0 * 8, 2 * 16}, "A:", Theme::getInstance()->fg_light->foreground},
{{13 * 8, 2 * 16}, "B:", Theme::getInstance()->fg_light->foreground},
{{0 * 8, 3 * 16}, "ADur:", Theme::getInstance()->fg_light->foreground},
{{9 * 8, 3 * 16}, "ms", Theme::getInstance()->fg_light->foreground},
{{12 * 8, 3 * 16}, "BDur:", Theme::getInstance()->fg_light->foreground},
{{21 * 8, 3 * 16}, "ms", Theme::getInstance()->fg_light->foreground},
{{0 * 8, 4 * 16}, "Gap: ", Theme::getInstance()->fg_light->foreground},
{{9 * 8, 4 * 16}, "ms", Theme::getInstance()->fg_light->foreground},
{{0 * 8, 5 * 16}, "Timing:", Theme::getInstance()->fg_light->foreground},
{{0 * 8, 6 * 16}, "Slot: ", Theme::getInstance()->fg_light->foreground},
{{0 * 8, 9 * 16}, "AHz:", Theme::getInstance()->fg_light->foreground},
{{8 * 8, 9 * 16}, "Hz", Theme::getInstance()->fg_light->foreground},
{{13 * 8, 9 * 16}, "BHz:", Theme::getInstance()->fg_light->foreground},
{{21 * 8, 9 * 16}, "Hz", Theme::getInstance()->fg_light->foreground},
};
OptionsField options_ctcss{
{7 * 8, 1 * 16},
9,
{}};
OptionsField options_tone_a{
{3 * 8, 2 * 16},
9,
{}};
OptionsField options_tone_b{
{16 * 8, 2 * 16},
9,
{}};
NumberField field_dur_a{
{5 * 8, 3 * 16},
4,
{100, 9900},
100,
' '};
NumberField field_dur_b{
{17 * 8, 3 * 16},
4,
{100, 9900},
100,
' '};
// Digit-by-digit entry for custom tone frequency (integer Hz, 4 slots, 01009999)
SymField symfield_custom_a{
{4 * 8, 9 * 16},
4,
SymField::Type::Dec};
SymField symfield_custom_b{
{17 * 8, 9 * 16},
4,
SymField::Type::Dec};
NumberField field_gap{
{5 * 8, 4 * 16},
4,
{0, 9900},
50,
' '};
OptionsField options_timing{
{8 * 8, 5 * 16},
12,
{{"Moto Std", 0},
{"Short Alert", 1},
{"Fire Std", 2},
{"Long Alert", 3},
{"Custom", 4}}};
NumberField field_slot{
{7 * 8, 6 * 16},
1,
{1, 5},
1,
' '};
Button button_save{
{9 * 8, 6 * 16, 6 * 8, 20},
"Save"};
Button button_load{
{16 * 8, 6 * 16, 6 * 8, 20},
"Load"};
// Shows the name of the currently selected preset slot (up to 8 visible chars)
Text text_slot_name{
{22 * 8, 6 * 16, 8 * 8, 16},
""};
Text text_time{
{0, 7 * 16, 30 * 8, 16},
""};
Text text_status{
{0, 8 * 16, 30 * 8, 16},
""};
ProgressBar progressbar{
{2 * 8, 14 * 16, 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 msg = *reinterpret_cast<const TXProgressMessage*>(p);
this->on_tx_progress(msg.progress, msg.done);
}};
};
} // namespace ui::external_app::two_tone_pager
#endif /* __UI_TWO_TONE_PAGER_H__ */
+86
View File
@@ -0,0 +1,86 @@
/*
* Copyright (C) 2024 PortaPack Mayhem
*
* 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_two_tone_rx.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::two_tone_rx {
void initialize_app(ui::NavigationView& nav) {
nav.push<TwoToneRxView>();
}
} // namespace ui::external_app::two_tone_rx
extern "C" {
__attribute__((section(".external_app.app_two_tone_rx.application_information"), used)) application_information_t _application_information_two_tone_rx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::two_tone_rx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "2-Tone RX",
/*.bitmap_data = */ {
// 16×16 icon — pager device with receive arrow
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFC,
0x3F,
0xFE,
0x7F,
0x02,
0x40,
0xBA,
0x5D,
0x02,
0x40,
0xFE,
0x7F,
0xFE,
0x7F,
0x12,
0x48,
0x12,
0x48,
0xFC,
0x3F,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
// Uses the proc_tonedetect baseband processor
/*.m4_app_tag = portapack::spi_flash::image_tag_tonedetect */ {'P', 'T', 'N', 'E'},
/*.m4_app_offset = */ 0x00000000, // filled at compile time
};
} // extern "C"
@@ -0,0 +1,599 @@
/*
* Copyright (C) 2024 PortaPack Mayhem
*
* 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_two_tone_rx.hpp"
#include "audio.hpp"
#include "baseband_api.hpp"
#include "portapack.hpp"
#include "string_format.hpp"
using namespace portapack;
namespace ui::external_app::two_tone_rx {
static constexpr uint32_t DETECT_WINDOW_MS = 40;
static constexpr Coord screen_width_px = 240;
static constexpr Coord screen_height_px = 320;
static constexpr Coord tone_log_top = 4 * 16;
static constexpr Coord waterfall_top = 13 * 16;
static constexpr Coord waterfall_height = 6 * 16;
static constexpr Rect tone_log_rect{0, tone_log_top, 30 * 8, waterfall_top - tone_log_top};
// ---------------------------------------------------------------------------
// Tone tables
// ---------------------------------------------------------------------------
static const uint32_t MOTO_FREQS[45] = {
2885,
3047,
3217,
3396,
3586,
3786,
3998,
4221,
4457,
4705,
4968,
5246,
5539,
5848,
6174,
6519,
6883,
7268,
7674,
8102,
8555,
9032,
9537,
10073,
10642,
11225,
11247,
11534,
11852,
11885,
12178,
12514,
12555,
12858,
13258,
13576,
13950,
13996,
14768,
15579,
16430,
17325,
18262,
19245,
20275,
};
// Index 0 = None (0), indices 150 = standard CTCSS tones (freq × 10)
static const uint32_t CTCSS_FREQS[51] = {
0,
670,
719,
744,
770,
797,
825,
854,
885,
915,
948,
974,
1000,
1035,
1072,
1109,
1148,
1188,
1230,
1273,
1318,
1365,
1413,
1462,
1500,
1514,
1567,
1598,
1622,
1655,
1679,
1713,
1738,
1773,
1799,
1835,
1862,
1899,
1928,
1966,
1995,
2035,
2065,
2107,
2181,
2257,
2291,
2336,
2418,
2503,
2541,
};
static std::string ctcss_name(uint32_t freq_x10) {
if (freq_x10 == 0) return "None";
return to_string_dec_uint(freq_x10 / 10) + "." +
to_string_dec_uint(freq_x10 % 10) + "Hz";
}
// ---------------------------------------------------------------------------
// MOTO table helpers
// ---------------------------------------------------------------------------
static constexpr uint32_t MOTO_NONE = 255;
static constexpr uint32_t MOTO_TRANSITION_SNAP_HZ = 30; // stricter live transition tolerance
static constexpr uint32_t MOTO_FINAL_MATCH_HZ = 60; // looser phase-end/logging tolerance
static constexpr uint32_t MOTO_TRANSITION_DELTA_HZ = 25; // raw shift needed to confirm close-in A→B handoff
static uint32_t abs_diff_u32(uint32_t a, uint32_t b) {
return (a > b) ? (a - b) : (b - a);
}
// Return the nearest MOTO table index within match_hz, or MOTO_NONE.
static uint32_t moto_index(uint32_t freq_hz, uint32_t match_hz = MOTO_TRANSITION_SNAP_HZ) {
if (freq_hz == 0) return MOTO_NONE;
uint32_t best_idx = MOTO_NONE;
uint32_t best_diff = match_hz + 1;
for (size_t i = 0; i < 45; i++) {
const uint32_t hz = MOTO_FREQS[i] / 10;
const uint32_t diff = (freq_hz > hz) ? (freq_hz - hz) : (hz - freq_hz);
if (diff < best_diff) {
best_diff = diff;
best_idx = i;
}
}
return best_idx;
}
// Format a detected tone for display, snapping to nearest MOTO table entry.
static std::string format_tone(uint32_t freq_hz, uint32_t duration_ms) {
const uint32_t idx = moto_index(freq_hz, MOTO_FINAL_MATCH_HZ);
std::string freq_str;
if (idx != MOTO_NONE) {
const uint32_t matched_x10 = MOTO_FREQS[idx];
freq_str = to_string_dec_uint(matched_x10 / 10) + "." +
to_string_dec_uint(matched_x10 % 10) + "Hz";
} else {
freq_str = to_string_dec_uint(freq_hz) + "Hz";
}
return freq_str + " " + to_string_dec_uint(duration_ms) + "ms";
}
// ---------------------------------------------------------------------------
// Waterfall rect
// ---------------------------------------------------------------------------
static constexpr ui::Rect waterfall_rect{0, waterfall_top, screen_width_px, waterfall_height};
// ---------------------------------------------------------------------------
// TwoToneRxView
// ---------------------------------------------------------------------------
void TwoToneRxView::focus() {
button_startstop.focus();
}
void TwoToneRxView::on_hide() {
if (running_) stop_rx();
}
TwoToneRxView::TwoToneRxView(NavigationView& nav)
: nav_{nav} {
prior_antenna_bias_ = get_antenna_bias();
debug_file_.append(u"DEBUG/TWOTONERX.TXT");
debug_file_.write_entry("==== two_tone_rx session start ====");
add_children({
&field_frequency,
&field_rf_amp,
&field_lna,
&field_vga,
&rssi,
&field_volume,
&labels,
&options_ctcss,
&field_squelch,
&button_startstop,
&button_clear,
&text_status,
&check_bias_t,
&tone_log_view,
});
// Populate CTCSS options
using opt_t = std::pair<std::string, int32_t>;
options_ctcss.set_options([&]() {
std::vector<opt_t> opts;
opts.reserve(51);
for (size_t i = 0; i < 51; i++)
opts.push_back({ctcss_name(CTCSS_FREQS[i]), (int32_t)i});
return opts;
}());
options_ctcss.set_by_value((int32_t)ctcss_idx);
options_ctcss.on_change = [this](size_t, int32_t v) {
ctcss_idx = (uint32_t)v;
if (running_) baseband::set_tonedetect_config((uint8_t)squelch_val, CTCSS_FREQS[ctcss_idx]);
};
field_squelch.set_value((int32_t)squelch_val);
field_squelch.on_change = [this](int32_t v) {
squelch_val = (uint32_t)v;
if (running_) baseband::set_tonedetect_config((uint8_t)squelch_val, CTCSS_FREQS[ctcss_idx]);
};
button_startstop.on_select = [this](Button&) {
if (running_)
stop_rx();
else
start_rx();
};
button_clear.on_select = [this](Button&) {
tone_log_entries_.clear();
tone_log_view.set_dirty();
text_status.set("");
reset_detect_state();
};
check_bias_t.set_value(bias_t_enabled);
check_bias_t.on_select = [this](Checkbox&, bool v) {
bias_t_enabled = v;
apply_bias_t(running_);
};
field_frequency.set_step(12500);
tone_log_view.set_parent_rect(tone_log_rect);
}
TwoToneRxView::~TwoToneRxView() {
if (running_) stop_rx();
}
void TwoToneRxView::reset_detect_state() {
detect_state_ = DetectState::IDLE;
phase_window_count_ = 0;
phase_freq_accum_ = 0;
phase_valid_windows_ = 0;
phase_last_freq_ = 0;
phase_last_is_first_ = true;
t1_avg_freq_ = 0;
t1_window_count_ = 0;
t1_transition_candidate_windows_ = 0;
t2_zero_window_count_ = 0;
debug_trace_active_ = false;
debug_trace_id_ = 0;
}
void TwoToneRxView::start_rx() {
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
audio::set_rate(audio::Rate::Hz_24000);
audio::output::start();
receiver_model.set_hidden_offset(0);
receiver_model.set_sampling_rate(3072000);
receiver_model.set_baseband_bandwidth(1750000);
receiver_model.enable();
apply_bias_t(true);
baseband::set_tonedetect_config((uint8_t)squelch_val, CTCSS_FREQS[ctcss_idx]);
add_child(&waterfall);
waterfall.set_parent_rect(waterfall_rect);
running_ = true;
button_startstop.set_text("Stop");
text_status.set("");
}
void TwoToneRxView::stop_rx() {
remove_child(&waterfall);
apply_bias_t(false);
receiver_model.disable();
baseband::shutdown();
audio::output::stop();
running_ = false;
button_startstop.set_text("Start");
text_status.set("");
reset_detect_state();
}
void TwoToneRxView::apply_bias_t(bool active) {
if (active && bias_t_enabled) {
set_antenna_bias(true);
receiver_model.set_antenna_bias();
applied_bias_t_ = true;
return;
}
if (!applied_bias_t_) return;
set_antenna_bias(prior_antenna_bias_);
receiver_model.set_antenna_bias();
applied_bias_t_ = false;
}
void TwoToneRxView::debug_log(const std::string& line) {
const std::string trace_prefix = debug_trace_active_
? ("#" + to_string_dec_uint(debug_trace_id_) + " ")
: "";
const std::string entry = "[D] " + trace_prefix + line;
debug_file_.write_entry(entry);
}
void TwoToneRxView::debug_trace_begin(const std::string& line) {
if (!debug_trace_active_) {
debug_trace_id_ = ++debug_trace_counter_;
debug_trace_active_ = true;
}
debug_log(line);
}
void TwoToneRxView::finalize_detected_pair(uint32_t t2_avg, uint32_t t2_dur, const char* reason) {
const uint32_t t1_dur = t1_window_count_ * DETECT_WINDOW_MS;
const std::string suffix = std::string(" via ") + reason;
if (t1_avg_freq_ > 0 && t2_avg > 0 &&
t1_dur >= 500 && t2_dur >= 500 &&
moto_index(t1_avg_freq_, MOTO_FINAL_MATCH_HZ) != MOTO_NONE &&
moto_index(t2_avg, MOTO_FINAL_MATCH_HZ) != MOTO_NONE) {
debug_trace_begin("END ok T1=" + format_tone(t1_avg_freq_, t1_dur) +
" T2=" + format_tone(t2_avg, t2_dur) + suffix);
log_tone_pair(t1_avg_freq_, t1_dur, t2_avg, t2_dur);
} else {
debug_trace_begin("END drop T1=" + format_tone(t1_avg_freq_, t1_dur) +
" T2=" + format_tone(t2_avg, t2_dur) + suffix);
}
}
// ---------------------------------------------------------------------------
// on_tone_data — window-based two-tone detection state machine
//
// Every 40 ms the baseband sends tone_end=false with a raw frequency estimate
// for that window (freq_hz=0 if no stable QCII candidate).
// When the CTCSS gate closes it sends tone_end=true (freq_hz=0).
//
// First and last windows of each phase are discarded:
// - "First" is tracked with phase_last_is_first_.
// - "Last" is phase_last_freq_, never added to the accumulator while
// pending; discarded when the phase ends.
//
// T1→T2 transition: consecutive windows that snap to different MOTO table
// entries. The transition window becomes T2's first window.
//
// Final matching is done from the phase-average raw estimates collected here,
// not from the per-window nearest-table snap used for transition detection.
// ---------------------------------------------------------------------------
void TwoToneRxView::on_tone_data(const ToneDetectDataMessage* msg) {
if (!running_) return;
if (msg->tone_end) {
// Gate closed — finalize whatever phase we're in
if (detect_state_ == DetectState::T2_COLLECTING) {
// phase_last_freq_ is the last T2 window → discard it
uint32_t t2_avg = (phase_valid_windows_ > 0)
? (phase_freq_accum_ / phase_valid_windows_)
: phase_last_freq_;
uint32_t t2_dur = phase_window_count_ * DETECT_WINDOW_MS;
finalize_detected_pair(t2_avg, t2_dur, "tone_end");
} else if (debug_trace_active_) {
debug_log("END before T2");
}
reset_detect_state();
text_status.set("");
return;
}
// tone_end=false: this is a 40 ms measurement window
const uint32_t freq = msg->freq_hz;
if (freq == 0) {
if (detect_state_ == DetectState::T2_COLLECTING) {
const uint32_t t2_avg = (phase_valid_windows_ > 0)
? (phase_freq_accum_ / phase_valid_windows_)
: phase_last_freq_;
const uint32_t t2_dur = phase_window_count_ * DETECT_WINDOW_MS;
if (t2_avg > 0 && t2_dur >= 2000) {
finalize_detected_pair(t2_avg, t2_dur, "t2_break");
reset_detect_state();
text_status.set("");
return;
}
}
// A single weak/noisy dropout is tolerated during T2 so standard 3 s
// B tones are not lost to one marginal 40 ms estimate window.
if (detect_state_ == DetectState::T2_COLLECTING && t2_zero_window_count_ == 0) {
t2_zero_window_count_++;
if (debug_trace_active_) {
debug_log("T2 zero dropout");
}
text_status.set("T1:" + format_tone(t1_avg_freq_, t1_window_count_ * DETECT_WINDOW_MS) +
" T2 ?");
return;
}
// Otherwise, treat the missing estimate as a break in the sequence.
if (debug_trace_active_) {
debug_log("RESET zero");
}
reset_detect_state();
text_status.set("");
return;
}
t2_zero_window_count_ = 0;
switch (detect_state_) {
case DetectState::IDLE:
detect_state_ = DetectState::T1_COLLECTING;
phase_window_count_ = 1;
phase_freq_accum_ = 0;
phase_valid_windows_ = 0;
phase_last_freq_ = freq;
phase_last_is_first_ = true;
text_status.set("T1 ...");
break;
case DetectState::T1_COLLECTING: {
// Check for T1→T2 MOTO index transition.
// Skip if phase_last_freq_ is the first (noisy) window — it's
// marked for discard and must not trigger a false transition.
if (freq > 0 && phase_last_freq_ > 0 && !phase_last_is_first_) {
const uint32_t t1_ref_freq = (phase_valid_windows_ > 0)
? (phase_freq_accum_ / phase_valid_windows_)
: phase_last_freq_;
const uint32_t idx_ref = moto_index(t1_ref_freq, MOTO_FINAL_MATCH_HZ);
const uint32_t idx_last = moto_index(phase_last_freq_);
const uint32_t idx_cur = moto_index(freq);
const uint32_t idx_cur_final = moto_index(freq, MOTO_FINAL_MATCH_HZ);
bool transition_detected = false;
if (idx_last != MOTO_NONE && idx_cur != MOTO_NONE && idx_last != idx_cur) {
if (!debug_trace_active_) {
debug_trace_begin("T1 start " + format_tone(t1_ref_freq, phase_window_count_ * DETECT_WINDOW_MS));
}
debug_log("T1->T2 snap " + format_tone(phase_last_freq_, DETECT_WINDOW_MS) +
" -> " + format_tone(freq, DETECT_WINDOW_MS));
transition_detected = true;
} else if (idx_ref != MOTO_NONE &&
idx_cur_final != MOTO_NONE &&
idx_cur_final != idx_ref &&
abs_diff_u32(freq, t1_ref_freq) >= MOTO_TRANSITION_DELTA_HZ) {
t1_transition_candidate_windows_++;
if (debug_trace_active_) {
debug_log("T1 cand " + to_string_dec_uint(t1_transition_candidate_windows_) +
" ref=" + to_string_dec_uint(t1_ref_freq) +
" cur=" + to_string_dec_uint(freq));
}
transition_detected = (t1_transition_candidate_windows_ >= 2);
} else {
if (debug_trace_active_ && t1_transition_candidate_windows_ > 0) {
debug_log("T1 cand reset");
}
t1_transition_candidate_windows_ = 0;
}
if (transition_detected) {
// Transition detected.
// phase_last_freq_ is the last T1 window → discard.
t1_avg_freq_ = (phase_valid_windows_ > 0)
? (phase_freq_accum_ / phase_valid_windows_)
: phase_last_freq_;
t1_window_count_ = phase_window_count_;
// Start T2 with current window as first (also discarded)
detect_state_ = DetectState::T2_COLLECTING;
phase_window_count_ = 1;
phase_freq_accum_ = 0;
phase_valid_windows_ = 0;
phase_last_freq_ = freq;
phase_last_is_first_ = true;
t1_transition_candidate_windows_ = 0;
t2_zero_window_count_ = 0;
if (!debug_trace_active_) {
debug_trace_begin("T1 start " + format_tone(t1_avg_freq_, t1_window_count_ * DETECT_WINDOW_MS));
}
debug_log("T2 start " + format_tone(freq, DETECT_WINDOW_MS));
text_status.set("T1:" + format_tone(t1_avg_freq_, t1_window_count_ * DETECT_WINDOW_MS) + " T2...");
break;
}
}
// No transition: promote pending window into accumulator (unless first)
if (!phase_last_is_first_ && phase_last_freq_ > 0) {
phase_freq_accum_ += phase_last_freq_;
phase_valid_windows_++;
}
phase_last_freq_ = freq;
phase_last_is_first_ = false;
phase_window_count_++;
if (!debug_trace_active_ &&
phase_window_count_ >= 3 &&
moto_index(phase_last_freq_, MOTO_FINAL_MATCH_HZ) != MOTO_NONE) {
const uint32_t t1_ref_freq = (phase_valid_windows_ > 0)
? (phase_freq_accum_ / phase_valid_windows_)
: phase_last_freq_;
debug_trace_begin("T1 start " + format_tone(t1_ref_freq, phase_window_count_ * DETECT_WINDOW_MS));
}
text_status.set("T1 " + to_string_dec_uint(phase_window_count_ * DETECT_WINDOW_MS) + "ms...");
break;
}
case DetectState::T2_COLLECTING:
// Promote pending window into accumulator (unless first)
if (!phase_last_is_first_ && phase_last_freq_ > 0) {
phase_freq_accum_ += phase_last_freq_;
phase_valid_windows_++;
}
phase_last_freq_ = freq;
phase_last_is_first_ = false;
phase_window_count_++;
text_status.set("T1:" + format_tone(t1_avg_freq_, t1_window_count_ * DETECT_WINDOW_MS) +
" T2 " + to_string_dec_uint(phase_window_count_ * DETECT_WINDOW_MS) + "ms");
break;
}
}
void TwoToneRxView::log_tone_pair(uint32_t f1, uint32_t d1_ms, uint32_t f2, uint32_t d2_ms) {
// Keep the oldest entry at the top so newer pairs appear below it.
tone_log_entries_.push_back({++next_log_serial_, format_tone(f1, d1_ms) + " " + format_tone(f2, d2_ms)});
tone_log_view.set_dirty();
}
} // namespace ui::external_app::two_tone_rx
namespace ui {
template <>
void RecentEntriesTable<ui::external_app::two_tone_rx::TwoToneLogEntries>::draw(
const Entry& entry,
const Rect& target_rect,
Painter& painter,
const Style& style,
ui::RecentEntriesColumns&) {
std::string line = entry.line;
line.resize(target_rect.width() / 8, ' ');
painter.draw_string(target_rect.location(), style, line);
}
} // namespace ui
@@ -0,0 +1,214 @@
/*
* Copyright (C) 2024 PortaPack Mayhem
*
* 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_TWO_TONE_RX_H__
#define __UI_TWO_TONE_RX_H__
#include "ui.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "ui_freq_field.hpp"
#include "ui_spectrum.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "message.hpp"
#include "string_format.hpp"
#include "log_file.hpp"
#include "recent_entries.hpp"
namespace ui::external_app::two_tone_rx {
struct TwoToneLogEntry {
using Key = uint32_t;
static constexpr Key invalid_key = 0;
Key serial{};
std::string line{};
Key key() const { return serial; }
};
using TwoToneLogEntries = RecentEntries<TwoToneLogEntry>;
class TwoToneRxView : public View {
public:
TwoToneRxView(NavigationView& nav);
~TwoToneRxView();
TwoToneRxView(const TwoToneRxView&) = delete;
TwoToneRxView(TwoToneRxView&&) = delete;
TwoToneRxView& operator=(const TwoToneRxView&) = delete;
TwoToneRxView& operator=(TwoToneRxView&&) = delete;
void focus() override;
void on_hide() override;
std::string title() const override { return "2-Tone RX"; };
private:
NavigationView& nav_;
RxRadioState radio_state_{};
bool running_{false};
TwoToneLogEntries tone_log_entries_{};
uint32_t next_log_serial_{0};
uint32_t squelch_val{50};
uint32_t ctcss_idx{0};
bool bias_t_enabled{false};
bool prior_antenna_bias_{false};
bool applied_bias_t_{false};
LogFile debug_file_{};
app_settings::SettingsManager settings_{
"rx_twotone",
app_settings::Mode::RX,
{
{"tone_sq"sv, &squelch_val},
{"ctcss"sv, &ctcss_idx},
{"bias_t"sv, &bias_t_enabled},
}};
void start_rx();
void stop_rx();
void apply_bias_t(bool active);
void debug_log(const std::string& line);
void debug_trace_begin(const std::string& line);
void on_tone_data(const ToneDetectDataMessage* msg);
void log_tone_pair(uint32_t f1, uint32_t d1_ms, uint32_t f2, uint32_t d2_ms);
void finalize_detected_pair(uint32_t t2_avg, uint32_t t2_dur, const char* reason);
void reset_detect_state();
// ── Two-tone detection state machine ─────────────────────────────────────
//
// Each 40 ms measurement window from the baseband arrives as tone_end=false.
// tone_end=true signals that the CTCSS gate closed (end of transmission).
//
// Collection rule: discard first and last window of each phase.
// - "First" is always discarded (may contain carrier ramp-up).
// - "Last" is never added to the accumulator while pending; it is
// discarded when the next window confirms it is not the last, OR when
// the phase ends (tone_end=true or T1→T2 transition).
//
// Transition detection: two consecutive windows that snap to different MOTO
// table entries trigger T1→T2. The transition window becomes T2's first
// window (also discarded as T2's first).
enum class DetectState : uint8_t { IDLE,
T1_COLLECTING,
T2_COLLECTING };
DetectState detect_state_{DetectState::IDLE};
// Per-phase window collection
uint32_t phase_window_count_{0}; // total windows seen in this phase (including first)
uint32_t phase_freq_accum_{0}; // sum of non-first, non-last window frequencies
uint32_t phase_valid_windows_{0}; // count of windows in phase_freq_accum_
uint32_t phase_last_freq_{0}; // pending window (not yet added; discarded if last)
bool phase_last_is_first_{true}; // true when phase_last_freq_ is window 1 (discard)
// T1 result (stored at T1→T2 transition for use when pair is logged)
uint32_t t1_avg_freq_{0};
uint32_t t1_window_count_{0};
uint8_t t1_transition_candidate_windows_{0};
uint8_t t2_zero_window_count_{0};
bool debug_trace_active_{false};
uint32_t debug_trace_id_{0};
uint32_t debug_trace_counter_{0};
// ── Row 0: frequency + RF controls ───────────────────────────────────────
RxFrequencyField field_frequency{
{UI_POS_X(0), UI_POS_Y(0)},
nav_};
RFAmpField field_rf_amp{
{UI_POS_X(13), UI_POS_Y(0)}};
LNAGainField field_lna{
{UI_POS_X(15), UI_POS_Y(0)}};
VGAGainField field_vga{
{UI_POS_X(18), UI_POS_Y(0)}};
RSSI rssi{
{UI_POS_X(21), UI_POS_Y(0), UI_POS_WIDTH_REMAINING(24), 4}};
AudioVolumeField field_volume{
{UI_POS_X_RIGHT(2), UI_POS_Y(0)}};
// ── Row 1: CTCSS / Squelch / Start+Stop / Clear ──────────────────────────
Labels labels{
{{0 * 8, 1 * 16}, "CTCSS:", Theme::getInstance()->fg_light->foreground},
{{15 * 8, 1 * 16}, "Sq:", Theme::getInstance()->fg_light->foreground},
};
OptionsField options_ctcss{
{7 * 8, 1 * 16},
8,
{}};
NumberField field_squelch{
{19 * 8, 1 * 16},
2,
{0, 99},
1,
' '};
Button button_startstop{
{21 * 8, 1 * 16, 5 * 8, 18},
"Start"};
Button button_clear{
{26 * 8, 1 * 16, 4 * 8, 18},
"Clr"};
// ── Row 2: live status (active tone in progress) + Bias-T toggle ─────────
Text text_status{
{0, 2 * 16 + 4, 20 * 8, 16},
""};
Checkbox check_bias_t{
{20 * 8, 2 * 16 + 2},
9,
"Bias-T",
true};
ui::RecentEntriesColumns tone_log_columns{{
{"Tones", 0},
}};
ui::RecentEntriesTable<TwoToneLogEntries> tone_log_view{tone_log_entries_, tone_log_columns};
// ── Waterfall (rest of screen) ────────────────────────────────────────────
spectrum::WaterfallView waterfall{};
// ── Message handler ───────────────────────────────────────────────────────
MessageHandlerRegistration message_handler_tone{
Message::ID::ToneDetectData,
[this](const Message* const p) {
const auto* msg = reinterpret_cast<const ToneDetectDataMessage*>(p);
this->on_tone_data(msg);
}};
};
} // namespace ui::external_app::two_tone_rx
#endif /* __UI_TWO_TONE_RX_H__ */
+1 -1
View File
@@ -73,7 +73,7 @@ __attribute__((section(".external_app.app_wefax_rx.application_information"), us
0x00,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
+2
View File
@@ -134,6 +134,7 @@ options_t freqman_steps = {
{"100kHz (FM2)", 100000},
{"250kHz (N2)", 250000},
{"500kHz (WFM)", 500000},
{"750kHz ", 750000},
{"1MHz ", 1000000},
};
@@ -156,6 +157,7 @@ options_t freqman_steps_short = {
{"100kHz", 100000},
{"250kHz", 250000},
{"500kHz", 500000},
{"750kHz", 750000},
{"1MHz", 1000000},
};
+2
View File
@@ -102,6 +102,7 @@ enum class freqman_type : uint8_t {
_100kHz,
_250kHz,
_500kHz,
_750kHz,
_1MHz,
Unknown,
* };
@@ -130,6 +131,7 @@ enum class freqman_type : uint8_t {
freqman_step_info{ freqman_step::_100kHz, "100kHz", "100kHz (FM2)", 100'000 },
freqman_step_info{ freqman_step::_250kHz, "250kHz", "250kHz (N2)", 250'000 },
freqman_step_info{ freqman_step::_500kHz, "500kHz", "500kHz (WFM)", 500'000 },
freqman_step_info{ freqman_step::_750kHz, "750kHz", "750kHz ", 750'000 },
freqman_step_info{ freqman_step::_1MHz, "1MHz", "1MHz ", 1'000'000 },
freqman_step_info{ freqman_step::Unknown, "Unknown", "Unknown ", 0 },
* };
+2 -1
View File
@@ -1,4 +1,5 @@
#include "gpio_lpc.h"
#include "gpio.h"
typedef enum {
LED1 = 0,
@@ -8,7 +9,7 @@ typedef enum {
} led_t;
/* GPIO Output PinMux */
static struct gpio_t gpio_led[] = {
static struct gpio gpio_led[] = {
GPIO(2, 1),
GPIO(2, 2),
GPIO(2, 8),
+37
View File
@@ -182,20 +182,24 @@ void MAX2831::set_mode(const Mode mode) {
case Mode::Shutdown:
gpio_max2831_rx_enable.write(0); /* RXTX=0 */
gpio_max283x_enable.write(0); /* ENABLE=0 */
set_rssi_mux(0);
break;
case Mode::Standby:
gpio_max2831_rx_enable.write(1); /* RXTX=1 */
gpio_max283x_enable.write(0); /* ENABLE=0 */
set_rssi_mux(0);
break;
case Mode::Transmit:
case Mode::Tx_Calibration:
gpio_max2831_rx_enable.write(1); /* RXTX=1 for TX */
gpio_max283x_enable.write(1); /* ENABLE=1 */
set_rssi_mux(2); // transmit power
break;
case Mode::Receive:
case Mode::Rx_Calibration:
gpio_max2831_rx_enable.write(0); /* RXTX=0 for RX */
gpio_max283x_enable.write(1); /* ENABLE=1 */
set_rssi_mux(1); // RSSI
break;
}
@@ -475,5 +479,38 @@ void MAX2831::write(const address_t reg_num, const reg_t value) {
}
}
void MAX2831::set_rssi_mux(const uint8_t mode) {
/* RSSI MUX allows switching the RSSI output between different internal signals.
* 0 = disable mux
* 1 = RSSI
* 2 = TX_POWER
* 3 = TEMP
*/
uint16_t mux_val = 0;
// Select the appropriate constant based on the input mode.
if (mode == 0) {
mux_val = 0;
} else {
// Select the appropriate constant based on the input mode.
switch (mode) {
case 3:
mux_val = REG8_RSSI_MUX_TEMP;
break;
case 2:
mux_val = REG8_RSSI_MUX_TX_POWER;
break;
case 1:
default:
mux_val = REG8_RSSI_MUX_RSSI;
break;
}
mux_val |= REG8_RSSI_EN;
}
set_reg_field(8, REG8_RSSI_MUX_MASK | REG8_RSSI_EN, mux_val);
flush_reg(8);
}
} // namespace max2831
#endif
+3
View File
@@ -151,6 +151,7 @@ constexpr uint16_t REG8_RSSI_MUX_MASK = 0x0300; /* D9:D8 */
constexpr uint16_t REG8_RSSI_MUX_RSSI = (0 << REG8_RSSI_MUX_SHIFT);
constexpr uint16_t REG8_RSSI_MUX_TEMP = (1 << REG8_RSSI_MUX_SHIFT);
constexpr uint16_t REG8_RSSI_MUX_TX_POWER = (2 << REG8_RSSI_MUX_SHIFT);
constexpr uint16_t REG8_RSSI_EN = (1 << 10);
constexpr uint16_t REG8_RXVGA_GAIN_SPI_EN_SHIFT = 12;
constexpr uint16_t REG8_RXVGA_GAIN_SPI_EN = (1 << REG8_RXVGA_GAIN_SPI_EN_SHIFT);
@@ -213,6 +214,8 @@ class MAX2831 : public MAX283x {
reg_t read(const address_t reg_num) override;
void write(const address_t reg_num, const reg_t value) override;
void set_rssi_mux(const uint8_t mode);
private:
spi::arbiter::Target& _target;
Mode _mode{Mode::Standby};
+1 -1
View File
@@ -636,7 +636,7 @@ init_status_t init() {
// This function returns LD_SUCCESS (0) if the FPGA confirms the bitstream
// Call fpga_bridge_init and continue boot regardless of result
// (Watchdog was resetting device when we halted with while(1))
int load_result = fpga_bridge_init();
int load_result = fpga_bridge_init(&shared_memory.bb_data.data[0]);
(void)load_result; // Ignore result for now, just let boot continue
/* RELEASE FPGA RESET */
+8 -4
View File
@@ -24,8 +24,6 @@
#include "rf_path.hpp"
#include "rffc507x.hpp"
#include "max2837.hpp"
#include "max2839.hpp"
#ifdef PRALINE
#include "max2831.hpp"
@@ -33,6 +31,8 @@ extern "C" {
#include "fpga_bridge.h"
}
#else
#include "max2837.hpp"
#include "max2839.hpp"
#include "baseband_cpld.hpp"
#endif
@@ -122,11 +122,11 @@ static spi::arbiter::Target ssp1_target_max5864{
static rf::path::Path rf_path;
rffc507x::RFFC507x first_if;
max283x::MAX283x* second_if;
max2837::MAX2837 second_if_max2837{ssp1_target_max283x};
max2839::MAX2839 second_if_max2839{ssp1_target_max283x};
#ifdef PRALINE
max2831::MAX2831 second_if_max2831{ssp1_target_max283x};
#else
max2837::MAX2837 second_if_max2837{ssp1_target_max283x};
max2839::MAX2839 second_if_max2839{ssp1_target_max283x};
static baseband::CPLD baseband_cpld;
#endif
static max5864::MAX5864 baseband_codec{ssp1_target_max5864};
@@ -415,7 +415,11 @@ void set_rx_max283x_iq_phase_calibration(const size_t v) {
void disable() {
set_antenna_bias(false);
baseband_codec.set_mode(max5864::Mode::Shutdown);
#ifdef PRALINE
second_if->set_mode(max283x::Mode::Standby);
#else
second_if->set_mode(max2837::Mode::Standby);
#endif
first_if.disable();
set_rf_amp(false);
+1 -1
View File
@@ -265,7 +265,7 @@ void GeoMap::map_read_line_bin(ui::Color* buffer, uint16_t pixels) {
void GeoMap::draw_markers(Painter& painter) {
for (int i = 0; i < markerListLen; ++i) {
draw_marker_item(painter, markerList[i], markerList[i].color, markerList[i].color, Color::black());
draw_marker_item(painter, markerList[i], markerList[i].color, markerList[i].color, Color::magenta());
}
}
+27 -10
View File
@@ -47,12 +47,16 @@ void RSSI::paint(Painter& painter) {
const auto r = screen_rect();
constexpr int rssi_sample_range = 256;
// constexpr float rssi_voltage_min = 0.4;
constexpr float rssi_voltage_min = 0.4;
#ifdef PRALINE
constexpr float rssi_voltage_max = 2.4;
#else
constexpr float rssi_voltage_max = 2.2;
#endif
constexpr float adc_voltage_max = 3.3;
// constexpr int raw_min = rssi_sample_range * rssi_voltage_min / adc_voltage_max;
constexpr int raw_min = 0;
constexpr int raw_max = rssi_sample_range * rssi_voltage_max / adc_voltage_max;
constexpr int raw_min = (rssi_sample_range * rssi_voltage_min) / adc_voltage_max;
constexpr int raw_max = (int)(((rssi_sample_range * rssi_voltage_max) / adc_voltage_max) + 0.5f);
constexpr int raw_delta = raw_max - raw_min;
if (!vertical_rssi_enabled) {
@@ -428,25 +432,38 @@ void RSSIGraph::paint(Painter& painter) {
void RSSIGraph::add_values(int16_t rssi_min, int16_t rssi_avg, int16_t rssi_max, int16_t db) {
const auto r = screen_rect();
/* RSSI scaling based on transceiver output voltage range.
* MAX2837 (HackRF One): 0.4V to 2.2V
* MAX2831 (HackRF Pro): 0.4V to 2.4V
*/
constexpr int rssi_sample_range = 256;
// constexpr float rssi_voltage_min = 0.4;
constexpr float rssi_voltage_min = 0.4;
#ifdef PRALINE
constexpr float rssi_voltage_max = 2.4;
#else
constexpr float rssi_voltage_max = 2.2;
#endif
constexpr float adc_voltage_max = 3.3;
// constexpr int raw_min = rssi_sample_range * rssi_voltage_min / adc_voltage_max;
constexpr int raw_min = 0;
constexpr int raw_max = rssi_sample_range * rssi_voltage_max / adc_voltage_max;
constexpr int raw_min = (rssi_sample_range * rssi_voltage_min) / adc_voltage_max;
constexpr int raw_max = (int)(((rssi_sample_range * rssi_voltage_max) / adc_voltage_max) + 0.5f);
constexpr int raw_delta = raw_max - raw_min;
// vertical bottom to top level meters
// y_avg
const range_t<int> y_avg_range{0, r.height() - 1};
const int16_t y_avg = y_avg_range.clip((rssi_avg - raw_min) * r.height() / raw_delta);
// y_min
const range_t<int> y_min_range{0, y_avg};
const int16_t y_min = y_min_range.clip((rssi_min - raw_min) * r.height() / raw_delta);
const range_t<int> y_max_range{y_avg + 1, r.height() - 1};
// y_max
const range_t<int> y_max_range{y_avg, r.height() - 1};
const int16_t y_max = y_max_range.clip((rssi_max - raw_min) * r.height() / raw_delta);
// range
const range_t<int> db_range{-80, 10};
int16_t db_ = db_range.clip(db);
db_ = db_ - 10;
db_ -= 10;
db_ = db_ * r.height() / 90;
db_ = r.height() + db_;
+5 -4
View File
@@ -64,10 +64,11 @@ class RSSI : public Widget {
void set_db(int16_t db);
private:
int8_t min_ = 0;
int8_t avg_ = 0;
int8_t max_ = 0;
int8_t peak_ = 0;
uint8_t min_ = 0;
uint8_t avg_ = 0;
uint8_t max_ = 0;
uint8_t peak_ = 0;
size_t peak_duration_ = 0;
int16_t db_ = 0;
bool instant_exec_{false};
+2
View File
@@ -361,6 +361,8 @@ void WaterfallView::stop() {
baseband::spectrum_streaming_stop();
running_ = false;
}
this->channel_fifo = nullptr;
this->audio_spectrum_data = nullptr;
}
void WaterfallView::show_audio_spectrum_view(const bool show) {
+6
View File
@@ -173,12 +173,16 @@ class WaterfallView : public View {
MessageHandlerRegistration message_handler_channel_spectrum_config{
Message::ID::ChannelSpectrumConfig,
[this](const Message* const p) {
if (!running_)
return;
const auto message = *reinterpret_cast<const ChannelSpectrumConfigMessage*>(p);
this->channel_fifo = message.fifo;
}};
MessageHandlerRegistration message_handler_audio_spectrum{
Message::ID::AudioSpectrum,
[this](const Message* const p) {
if (!running_)
return;
const auto message = *reinterpret_cast<const AudioSpectrumMessage*>(p);
this->audio_spectrum_data = message.data;
this->audio_spectrum_update = true;
@@ -186,6 +190,8 @@ class WaterfallView : public View {
MessageHandlerRegistration message_handler_frame_sync{
Message::ID::DisplayFrameSync,
[this](const Message* const) {
if (!running_)
return;
if (this->channel_fifo) {
ChannelSpectrum channel_spectrum;
while (channel_fifo->out(channel_spectrum)) {
+13 -9
View File
@@ -91,7 +91,7 @@ class SDCardTestThread {
}
private:
static constexpr File::Size write_size = 16384;
static constexpr File::Size write_size = 4096; // will call it 4 times
static constexpr File::Size bytes_to_write = 16 * 1024 * 1024;
static constexpr File::Size bytes_to_read = bytes_to_write;
@@ -160,12 +160,14 @@ class SDCardTestThread {
sizeof(*buffer.get()) / sizeof(lfsr_word_t));
const halrtcnt_t write_start = halGetCounterValue();
const auto result_write = file.write(buffer->data(), buffer->size());
if (result_write.is_error()) {
break;
for (uint8_t i = 0; i < 4; i++) {
const auto result_write = file.write(buffer->data(), buffer->size());
if (result_write.is_error()) {
break;
}
_stats.write_bytes += buffer->size();
}
const halrtcnt_t write_end = halGetCounterValue();
_stats.write_bytes += buffer->size();
_stats.write_count++;
const halrtcnt_t write_duration = write_end - write_start;
@@ -202,12 +204,14 @@ class SDCardTestThread {
const halrtcnt_t test_start = halGetCounterValue();
while (!chThdShouldTerminate() && (_stats.read_bytes < bytes_to_read)) {
const halrtcnt_t read_start = halGetCounterValue();
const auto result_read = file.read(buffer->data(), buffer->size());
if (result_read.is_error()) {
break;
for (uint8_t i = 0; i < 4; i++) {
const auto result_read = file.read(buffer->data(), buffer->size());
if (result_read.is_error()) {
break;
}
_stats.read_bytes += buffer->size();
}
const halrtcnt_t read_end = halGetCounterValue();
_stats.read_bytes += buffer->size();
_stats.read_count++;
const halrtcnt_t read_duration = read_end - read_start;
+78 -16
View File
@@ -1262,7 +1262,7 @@ static void cmd_settingsreset(BaseSequentialStream* chp, int argc, char* argv[])
}
static void cmd_sendpocsag(BaseSequentialStream* chp, int argc, char* argv[]) {
const char* usage = "usage: sendpocsag <addr> <msglen> [baud] [type] [function] [phase] \r\n";
const char* usage = "usage: sendpocsag <addr> <msglen> [baud] [type] [function] [polarity:S|I] \r\n";
(void)argv;
if (argc < 2) {
chprintf(chp, usage);
@@ -1293,34 +1293,48 @@ static void cmd_sendpocsag(BaseSequentialStream* chp, int argc, char* argv[]) {
}
}
char function = 'D';
char function = 'A';
if (argc >= 5) {
function = *argv[4];
if (function < 'A' && function > 'D') {
if (function < 'A' || function > 'D') {
chprintf(chp, "error, function can be A, B, C or D\r\n");
return;
}
}
char phase = 'P';
char polarity = 'S'; /* Standard = CCIR Rec. 584 (bit 1 = negative deviation) */
if (argc >= 6) {
phase = *argv[5];
if (phase != 'P' && phase != 'N') {
chprintf(chp, "error, phase can be P or N\r\n");
polarity = *argv[5];
/*
* Legacy compatibility: old firmware used 'P'/'N' with opposite semantics.
* Old 'P' (phase=positive) = inverted codewords = standard POCSAG = new 'S' (Standard)
* Old 'N' (phase=negative) = no inversion = inverted POCSAG = new 'I' (Inverted)
* New firmware uses 'S'/'I':
* 'S' = Standard (CCIR Rec. 584, bit 1 = negative deviation)
* 'I' = Inverted (bit 1 = positive deviation)
*/
if (polarity == 'P') polarity = 'S'; /* legacy 'P' maps to Standard */
if (polarity == 'N') polarity = 'I'; /* legacy 'N' maps to Inverted */
if (polarity != 'S' && polarity != 'I') {
chprintf(chp, "error, polarity can be S (Standard) or I (Inverted)\r\n");
return;
}
}
uint8_t msg[81] = {0};
if (msglen > 0) {
chprintf(chp, "send %d bytes\r\n", msglen);
do {
size_t bytes_to_read = msglen > USB_BULK_BUFFER_SIZE ? USB_BULK_BUFFER_SIZE : msglen;
size_t bytes_read = chSequentialStreamRead(chp, &msg[0], bytes_to_read);
uint8_t msg[31] = {0};
uint8_t original_msglen = (msglen > 31) ? 31 : msglen;
if (original_msglen > 0) {
chprintf(chp, "send %d bytes\r\n", original_msglen);
size_t offset = 0;
size_t remaining = original_msglen;
while (remaining > 0) {
size_t bytes_to_read = remaining > USB_BULK_BUFFER_SIZE ? USB_BULK_BUFFER_SIZE : remaining;
size_t bytes_read = chSequentialStreamRead(chp, &msg[offset], bytes_to_read);
if (bytes_read != bytes_to_read)
return;
msglen -= bytes_read;
} while (msglen > 0);
offset += bytes_read;
remaining -= bytes_read;
}
}
auto evtd = getEventDispatcherInstance();
@@ -1334,7 +1348,54 @@ static void cmd_sendpocsag(BaseSequentialStream* chp, int argc, char* argv[]) {
return;
}
chThdSleepMilliseconds(1000); // wait for app to start
PocsagTosendMessage message{(uint16_t)baud, (uint8_t)type, function, phase, (uint8_t)msglen, msg, addr};
PocsagTosendMessage message{(uint16_t)baud, (uint8_t)type, function, polarity, original_msglen, msg, addr};
EventDispatcher::send_message(message);
chprintf(chp, "ok\r\n");
}
static void cmd_sendflex(BaseSequentialStream* chp, int argc, char* argv[]) {
const char* usage = "usage: sendflex <capcode> <type> <msglen>\r\n type: 0=alpha 1=numeric 2=short/tone 3=short numeric\r\n";
if (argc < 3) {
chprintf(chp, usage);
return;
}
uint64_t capcode = strtoull(argv[0], nullptr, 10);
if (capcode < 1 || capcode > 4297068542ULL) {
chprintf(chp, "error, capcode 1-4297068542\r\n");
return;
}
int type = atoi(argv[1]);
if (type < 0 || type > 3) {
chprintf(chp, "error, type 0=alpha 1=numeric 2=short/tone 3=short numeric\r\n");
return;
}
int msglen = atoi(argv[2]);
if (msglen < 0 || msglen > 240) {
chprintf(chp, "error, msglen max 240\r\n");
return;
}
uint8_t msg[240] = {0};
if (msglen > 0) {
chprintf(chp, "send %d bytes\r\n", msglen);
int offset = 0;
do {
size_t bytes_to_read = (msglen - offset) > USB_BULK_BUFFER_SIZE ? USB_BULK_BUFFER_SIZE : (msglen - offset);
size_t bytes_read = chSequentialStreamRead(chp, &msg[offset], bytes_to_read);
if (bytes_read != bytes_to_read)
return;
offset += bytes_read;
} while (offset < msglen);
}
auto evtd = getEventDispatcherInstance();
if (!evtd) return;
auto top_widget = evtd->getTopWidget();
if (!top_widget) return;
auto nav = static_cast<ui::SystemView*>(top_widget)->get_navigation_view();
if (!nav) return;
FlexTosendMessage message{capcode, (uint8_t)type, (uint8_t)msglen, msg};
EventDispatcher::send_message(message);
chprintf(chp, "ok\r\n");
}
@@ -1486,6 +1547,7 @@ static const ShellCommand commands[] = {
{"pmemreset", cmd_pmemreset},
{"settingsreset", cmd_settingsreset},
{"sendpocsag", cmd_sendpocsag},
{"sendflex", cmd_sendflex},
{"asyncmsg", cmd_asyncmsg},
{"setfreq", cmd_setfreq},
{"getres", cmd_getres},
+35 -14
View File
@@ -380,13 +380,6 @@ set(MODE_CPPSRC
)
DeclareTargets(PCAP capture)
### ERT
set(MODE_CPPSRC
proc_ert.cpp
)
DeclareTargets(PERT ert)
### Radiosonde
set(MODE_CPPSRC
@@ -452,13 +445,6 @@ set(MODE_CPPSRC
DeclareTargets(PREP replay)
### Tones
set(MODE_CPPSRC
proc_tones.cpp
)
DeclareTargets(PTON tones)
### Wideband Spectrum
@@ -543,6 +529,13 @@ set(MODE_CPPSRC
DeclareTargets(PEPT epirb_tx)
### P25 TX
set(MODE_CPPSRC
proc_p25_tx.cpp
)
DeclareTargets(P25T p25_tx)
### NRF RX
@@ -676,6 +669,14 @@ set(MODE_CPPSRC
)
DeclareTargets(PSCD subcar)
### Tone Detect RX
set(MODE_CPPSRC
proc_tonedetect.cpp
)
DeclareTargets(PTNE tonedetect)
### Morse RX Decoder
set(MODE_CPPSRC
@@ -692,6 +693,15 @@ set(MODE_CPPSRC
DeclareTargets(PRTR rtty_rx)
### ERT
set(MODE_CPPSRC
proc_ert.cpp
)
DeclareTargets(PERT ert)
### RTTY TX
set(MODE_CPPSRC
@@ -714,6 +724,15 @@ set(MODE_CPPSRC
)
DeclareTargets(PMRT morsetx)
### Tones
set(MODE_CPPSRC
proc_tones.cpp
)
DeclareTargets(PTON tones)
### Time Sink
set(MODE_CPPSRC
@@ -739,6 +758,8 @@ set(MODE_CPPSRC
${HACKRF_PATH}/firmware/common/usb_request.c
${HACKRF_PATH}/firmware/common/usb_standard_request.c
${HACKRF_PATH}/firmware/common/platform_detect.c
${HACKRF_PATH}/firmware/common/platform_gpio.c
${HACKRF_PATH}/firmware/common/platform_scu.c
${HACKRF_PATH}/firmware/common/gpio_lpc.c
${HACKRF_PATH}/firmware/common/firmware_info.c
${HACKRF_PATH}/firmware/common/si5351c.c
+6 -6
View File
@@ -46,15 +46,15 @@ void EPIRBTXProcessor::execute(const buffer_c8_t& buffer) {
if (mode_bpsk) {
// BPSK Manchester beacon signal
if (bpsk_pre_count < config_pre_count) {
// Pre-count state: send a negative phase carrier during pre-count
// Pre-count state: send carrier only during pre-count
bpsk_pre_count++;
re = i_neg;
im = q_neg;
re = i_carrier;
im = q_carrier;
} else if (bpsk_post_count > 0) {
// Post-count: send a negative phase carrier during post-count
// Post-count: send carrier only during post-count
bpsk_post_count++;
re = i_neg;
im = q_neg;
re = i_carrier;
im = q_carrier;
if (bpsk_post_count >= config_post_count) {
// End transmission here
byte_index = 0;
+5 -2
View File
@@ -60,14 +60,17 @@ class EPIRBTXProcessor : public BasebandProcessor {
// Size of the frame to send in BPSK mode
uint8_t frame_data_len = 0;
// BPSK parameters: Target phase +/-63° as per COSPAS/SARSAT specifications
static constexpr float phase_rad = 63.0f * M_PI / 180.0f;
// BPSK parameters: Target phase +/-1.1 RAD as per COSPAS/SARSAT specifications
static constexpr float phase_rad = 1.1f;
// I/Q values for BPSK (positive phase and negative phase)
int8_t i_pos = (int8_t)(cos(phase_rad) * 127);
int8_t q_pos = (int8_t)(sin(phase_rad) * 127);
int8_t i_neg = i_pos;
int8_t q_neg = -q_pos;
// I/Q values for carrier only
static constexpr int8_t i_carrier = 127;
static constexpr int8_t q_carrier = 0;
// COSPAS/SARSAT signal is manchester (2 states per bit) encoded 400 bit/sec
static const uint32_t samples_per_halfbit = TONES_SAMPLERATE / 400 / 2;
+742 -58
View File
@@ -7,7 +7,45 @@
#include <cmath>
#include <cstring>
#include <cstdio> // for snprintf
// BCD character table for FLEX numeric messages (index 0-15)
static const char flex_bcd[] = "0123456789.U -][";
// Lightweight string helpers (no snprintf/heap on bare-metal M4)
namespace {
char* str_append(char* dst, const char* end, const char* src) {
while (*src && dst < end - 1) *dst++ = *src++;
*dst = '\0';
return dst;
}
char* str_uint(char* dst, const char* end, uint32_t val, int min_digits = 1) {
char tmp[11];
int i = 0;
if (val == 0) {
tmp[i++] = '0';
} else {
while (val > 0) {
tmp[i++] = '0' + (val % 10);
val /= 10;
}
}
while (i < min_digits) tmp[i++] = '0';
for (int j = i - 1; j >= 0 && dst < end - 1; j--) *dst++ = tmp[j];
*dst = '\0';
return dst;
}
char* str_hex(char* dst, const char* end, uint32_t val, int digits) {
static const char hex[] = "0123456789ABCDEF";
for (int i = digits - 1; i >= 0 && dst < end - 1; i--)
*dst++ = hex[(val >> (i * 4)) & 0xF];
*dst = '\0';
return dst;
}
} // namespace
// Constants from demod_flex.c
#define FREQ_SAMP 24000 // Our sample rate
@@ -155,7 +193,6 @@ uint32_t bit_reverse_32(uint32_t x) {
void FlexProcessor::send_debug(const char* text, uint32_t v1, uint32_t v2) {
if (shared_memory.application_queue.is_empty()) return;
FlexDebugMessage message(v1, v2, text);
shared_memory.application_queue.push(message);
}
@@ -403,7 +440,9 @@ int FlexProcessor::decode_fiw() {
fiw.checksum = fiw_val & 0xF;
fiw.cycleno = (fiw_val >> 4) & 0xF;
fiw.frameno = (fiw_val >> 8) & 0x7F;
fiw.fix3 = (fiw_val >> 15) & 0x3F;
fiw.roaming = (fiw_val >> 15) & 0x01;
fiw.repeat = (fiw_val >> 16) & 0x01;
fiw.traffic = (fiw_val >> 17) & 0x0F;
unsigned int checksum = (fiw_val & 0xF);
checksum += ((fiw_val >> 4) & 0xF);
@@ -509,6 +548,9 @@ void FlexProcessor::flex_sym(unsigned char sym) {
if (state.fiwcount == 48) {
if (decode_fiw() == 0) {
state.sync2_count = 0;
state.sync2_shiftreg = 0;
state.sync2_c_pos = -1;
state.sync2_cinv_pos = -1;
demodulator.baud = sync.baud;
state.Current = flex::State::SYNC2;
send_debug("FIW OK", fiw.frameno, fiw.cycleno);
@@ -520,8 +562,48 @@ void FlexProcessor::flex_sym(unsigned char sym) {
break;
}
case flex::State::SYNC2: {
if (++state.sync2_count == sync.baud * 25 / 1000) {
state.data_count = 0;
/* S2 structure: BS2 + C(16 bits) + inv.BS2 + inv.C(16 bits)
* Total duration: 25ms at the data symbol rate.
*
* We scan for the 16-bit C pattern (0xED84) using a shift
* register. If found, we validate timing. If not found,
* we fall back to the nominal 25ms skip (current behavior).
*
* Only the MSB (bit_a) matters for C detection - it's a
* 2-level pattern even in 4FSK modes. */
unsigned char s2_sym = sync.polarity ? (3 - sym) : sym;
int bit_a = (s2_sym > 1) ? 1 : 0;
state.sync2_shiftreg = (state.sync2_shiftreg << 1) | bit_a;
state.sync2_count++;
/* Check for C pattern match (Hamming distance <= 2) */
if (state.sync2_count >= 16) {
uint16_t diff_c = state.sync2_shiftreg ^ 0xED84;
uint16_t diff_cinv = state.sync2_shiftreg ^ 0x127B;
int errs_c = __builtin_popcount(diff_c);
int errs_cinv = __builtin_popcount(diff_cinv);
if (errs_c <= 2 && state.sync2_c_pos < 0)
state.sync2_c_pos = (int)state.sync2_count;
if (errs_cinv <= 2 && state.sync2_cinv_pos < 0)
state.sync2_cinv_pos = (int)state.sync2_count;
}
/* Nominal S2 duration in symbols */
unsigned int s2_nominal = sync.baud * 25 / 1000;
/* Data starts after inv.C ends. If we detected inv.C,
* use its position as the true data boundary. Otherwise
* fall back to the nominal count. */
unsigned int s2_end = s2_nominal;
if (state.sync2_cinv_pos > 0) {
unsigned int cinv_end = (unsigned int)state.sync2_cinv_pos;
int diff = (int)cinv_end - (int)s2_nominal;
if (diff >= -1 && diff <= 1)
s2_end = cinv_end;
}
if (state.sync2_count == s2_end) {
// Clear phase data
for (int i = 0; i < 88; i++) {
data.PhaseA.buf[i] = 0;
@@ -535,9 +617,21 @@ void FlexProcessor::flex_sym(unsigned char sym) {
data.PhaseD.idle_count = 0;
data.phase_toggle = 0;
data.data_bit_counter = 0;
state.data_count = 0;
state.sync2_shiftreg = 0;
state.sync2_c_pos = -1;
state.sync2_cinv_pos = -1;
state.Current = flex::State::DATA;
}
/* Safety: don't get stuck past nominal */
if (state.sync2_count > s2_nominal + 1) {
state.sync2_shiftreg = 0;
state.sync2_c_pos = -1;
state.sync2_cinv_pos = -1;
state.Current = flex::State::SYNC1;
}
break;
}
case flex::State::DATA: {
@@ -593,26 +687,204 @@ void FlexProcessor::decode_phase(char PhaseNo) {
return;
}
/* Check if phase is all idle BEFORE BCH correction.
* Idle fill uses alternating 0xFFFFFFFF and 0x00000000 words.
* If every word is one of these two patterns, the phase has no
* real data - skip it to avoid BCH "correcting" idle into garbage. */
{
int all_idle = 1;
for (int i = 0; i < 88; i++) {
if (phaseptr[i] != 0xFFFFFFFF && phaseptr[i] != 0x00000000) {
all_idle = 0;
break;
}
}
if (all_idle) return;
}
/* BCH decode each word. Mark uncorrectable words but continue. */
uint8_t word_bad[88] = {0};
for (int i = 0; i < 88; i++) {
int decode_error = bch_fix_errors(&phaseptr[i]);
if (decode_error > 2) return;
phaseptr[i] &= 0x001FFFFF; // Extract message bits
if (decode_error > 2) {
word_bad[i] = 1;
phaseptr[i] = 0;
}
phaseptr[i] &= 0x001FFFFF;
}
/* BIW must be good to proceed */
if (word_bad[0]) return;
uint32_t biw = phaseptr[0];
if (biw == 0 || biw == 0x001FFFFF) return;
int voffset = (biw >> 10) & 0x3f;
int aoffset = ((biw >> 8) & 0x03) + 1;
int prio_count = (biw >> 4) & 0x0F; // number of priority address words
if (voffset < aoffset || voffset >= 88) return;
/* Always send BIW1 packet so the app knows we decoded a frame.
* This updates the status bar even for idle frames. */
{
flex::FlexPacket bpkt{};
bpkt.type = 9;
bpkt.bitrate = sync.baud * (sync.levels == 4 ? 2 : 1);
bpkt.cycle = fiw.cycleno;
bpkt.frame = fiw.frameno;
bpkt.phase = PhaseNo;
bpkt.is_inverted = sync.polarity;
bpkt.fiw_roaming = fiw.roaming;
bpkt.function = 0;
bpkt.biw_field = 0xFF;
bpkt.message[0] = '\0';
send_packet(bpkt);
}
/* Parse BIW words (indices 1 through aoffset-1).
* Each BIW word has a 3-bit type field (bits 4-6) that determines content.
* Send each as a BIW event packet. */
for (int bw = 1; bw < aoffset && bw < 88; bw++) {
if (word_bad[bw]) continue;
uint32_t bword = phaseptr[bw];
uint32_t btype = (bword >> 4) & 0x07;
/* Skip reserved types (3, 4, 6) */
if (btype == 3 || btype == 4 || btype == 6) continue;
flex::FlexPacket bpkt{};
bpkt.type = 9; // BIW event
bpkt.bitrate = sync.baud * (sync.levels == 4 ? 2 : 1);
bpkt.cycle = fiw.cycleno;
bpkt.frame = fiw.frameno;
bpkt.phase = PhaseNo;
bpkt.is_inverted = sync.polarity;
bpkt.fiw_roaming = fiw.roaming;
bpkt.function = bw; // BIW word index
bpkt.biw_field = btype; // BIW type (0,1,2,5,7)
bpkt.message[0] = '\0';
switch (btype) {
case 0: // SSID1: v1=lid, v2=cz
bpkt.biw_v1 = (bword >> 12) & 0x01FF;
bpkt.biw_v2 = (bword >> 7) & 0x1F;
break;
case 1: // Date: v1=year(+1994), v2=month, v3=day
bpkt.biw_v1 = ((bword >> 7) & 0x1F) + 1994;
bpkt.biw_v2 = (bword >> 17) & 0x0F;
bpkt.biw_v3 = (bword >> 12) & 0x1F;
break;
case 2: // Time: v1=hour, v2=minute, v3=sec_raw(0-7)
bpkt.biw_v1 = (bword >> 7) & 0x1F;
bpkt.biw_v2 = (bword >> 12) & 0x3F;
bpkt.biw_v3 = (bword >> 18) & 0x07;
break;
case 5: // SysInfo: v1=a_type, v2=info(10 bits)
bpkt.biw_v1 = (bword >> 7) & 0x0F;
bpkt.biw_v2 = (bword >> 11) & 0x03FF;
break;
case 7: // SSID2: v1=country, v2=tmf
bpkt.biw_v1 = (bword >> 11) & 0x03FF;
bpkt.biw_v2 = (bword >> 7) & 0x0F;
break;
default:
continue;
}
send_packet(bpkt);
}
/* Pre-scan: count valid vector words using 4-bit nibble checksum.
* Tone-only addresses sit at the end of the address field with no
* corresponding vector. We find the last vector that passes checksum.
* Note: for long addresses, the 2nd vector word (Vy) is a message word
* that won't pass checksum - so we count all passing words, not just
* consecutive ones from the start. */
int n_valid_vecs = 0;
for (int vi = 0; vi < (voffset - aoffset); vi++) {
int wi = voffset + vi;
if (wi >= 88) break;
uint32_t vw = phaseptr[wi];
uint32_t csum = (vw & 0xF) + ((vw >> 4) & 0xF) + ((vw >> 8) & 0xF) +
((vw >> 12) & 0xF) + ((vw >> 16) & 0xF) + ((vw >> 20) & 0x1);
if ((csum & 0xF) == 0xF)
n_valid_vecs = vi + 1; // track highest passing index + 1
}
/* No addresses if voffset == aoffset */
if (voffset <= aoffset) return;
int vec_count = 0;
int addr_count = 0; // tracks address word position for priority detection
for (int i = aoffset; i < voffset; i++) {
int j = voffset + i - aoffset;
int j = voffset + vec_count;
if (j >= 88) break;
if (phaseptr[i] == 0x00000000 || phaseptr[i] == 0x001FFFFF) continue;
parse_capcode(phaseptr[i]);
if (decode.long_address) continue; // Skip long addresses for now
/* Address word - all 21 information bits are address data
* per 3.8.2. Address type is determined by value range
* (Table 3.8.1-1). Temporary addresses are range
* 0x1F7800-0x1F780F (3.8.2.3), identified via addr_type. */
int is_priority = (addr_count < prio_count) ? 1 : 0;
if (decode.capcode > 4297068542ll || decode.capcode < 0) continue;
parse_capcode(phaseptr[i]);
decode.is_priority = is_priority;
addr_count++;
if (decode.long_address) {
/* Long address: 2 address words, 2 vector words.
* Read second address word and compute capcode from set. */
if (i + 1 >= voffset) break; // truncated
uint32_t aw1 = phaseptr[i];
uint32_t aw2 = phaseptr[i + 1];
if (aw2 == 0x00000000 || aw2 == 0x001FFFFF) {
i++;
addr_count++; // second address word counts
vec_count += 2;
continue;
}
int64_t cap = 0;
if (aw1 >= 0x000001 && aw1 <= 0x008000 &&
aw2 >= 0x1F7FFF && aw2 <= 0x1FFFFE) {
/* Set 1-2 */
cap = (int64_t)aw1 + (int64_t)(0x1FFFFF - aw2) * 32768LL + 2068480LL;
} else if (aw1 >= 0x000001 && aw1 <= 0x008000 &&
aw2 >= 0x1E0001 && aw2 <= 0x1F0000) {
/* Set 1-3 / 1-4 */
cap = (int64_t)aw1 + (int64_t)(aw2 - 1933312) * 32768LL + 2068480LL;
} else if (aw1 >= 0x1F7FFF && aw1 <= 0x1FFFFE &&
aw2 >= 0x1E0001 && aw2 <= 0x1F0000) {
/* Set 2-3 */
cap = (int64_t)(aw1 - 2064383) + (int64_t)(aw2 - 1867776) * 32768LL + 2068479LL;
} else {
/* Unknown set - skip */
i++;
addr_count++; // second address word counts
vec_count += 2;
continue;
}
decode.capcode = cap;
i++; // consumed 2 address words
addr_count++; // second address word also counts
/* Long addresses always have vectors - they cannot be tone-only.
* (Tone-only is only for short addresses at the end of AF.)
* The second vector word (Vy) contains the first message word,
* not a checksummed vector, so skip the pre-scan check here. */
vec_count += 2; // consumed 2 vector words
j = voffset + vec_count - 2; // point to first vector word of pair
} else {
if (decode.capcode > 4297068542ll || decode.capcode <= 0) continue;
/* Tone-only: address beyond valid vector range */
if (vec_count >= n_valid_vecs) {
parse_tone_only(phaseptr, PhaseNo, 0);
continue;
}
vec_count++;
}
uint32_t viw = phaseptr[j];
int type_val = (viw >> 4) & 0x07;
@@ -645,7 +917,14 @@ void FlexProcessor::decode_phase(char PhaseNo) {
}
int mw1 = (viw >> 7) & 0x7F;
int len = (viw >> 14) & 0x7F;
int len;
/* Numeric types (3, 4, 7) have a 3-bit n field (bits 14-16)
* encoding word_count - 1. Bits 17-20 are the K checksum.
* Alpha/hex/secure types use the full 7-bit field (bits 14-20). */
if (type_val == 3 || type_val == 4 || type_val == 7)
len = ((viw >> 14) & 0x07) + 1;
else
len = (viw >> 14) & 0x7F;
int mw2 = mw1 + (len - 1);
if (mw1 == 0 && mw2 == 0) continue;
@@ -653,121 +932,526 @@ void FlexProcessor::decode_phase(char PhaseNo) {
if (decode.type == flex::PageType::ALPHANUMERIC || decode.type == flex::PageType::SECURE) {
if (mw1 > 87 || mw2 > 87) continue;
parse_alphanumeric(phaseptr, PhaseNo, mw1, mw2, 0);
if (decode.long_address) {
/* For long addresses, body[0] (header with K,C,F,N,R,M) is at
* Vy (j+1), not at mw1. The vector's mw1 points to body[1]
* in the message field, and len includes body[0].
* parse_alphanumeric expects mw1 = header word index (it does
* mw1++ internally to skip header). So pass mw1-1 so the
* skip lands on mw1 (first real data word). */
parse_alphanumeric(phaseptr, word_bad, PhaseNo, mw1 - 1, mw2 - 1, 0);
} else {
parse_alphanumeric(phaseptr, word_bad, PhaseNo, mw1, mw2, 0);
}
} else if (decode.type == flex::PageType::STANDARD_NUMERIC || decode.type == flex::PageType::SPECIAL_NUMERIC || decode.type == flex::PageType::NUMBERED_NUMERIC) {
parse_numeric(phaseptr, PhaseNo, j);
parse_numeric(phaseptr, word_bad, PhaseNo, j);
} else if (decode.type == flex::PageType::TONE) {
parse_tone_only(phaseptr, PhaseNo, j);
} else {
// Unknown or unsupported
/* Vector type 2: Short Message (3.9.2).
* Sub-type t1t0 in bits 7-8, data d0-d11 in bits 9-20. */
uint32_t t = (viw >> 7) & 0x03;
uint32_t d = (viw >> 9) & 0x0FFF;
flex::FlexPacket packet{};
packet.bitrate = sync.baud * (sync.levels == 4 ? 2 : 1);
packet.capcode = decode.capcode;
packet.function = t;
packet.cycle = fiw.cycleno;
packet.frame = fiw.frameno;
packet.phase = PhaseNo;
packet.is_inverted = sync.polarity;
packet.fiw_roaming = fiw.roaming;
packet.addr_type = static_cast<uint8_t>(decode.addr_type);
packet.is_priority = decode.is_priority;
packet.type = 8; // SHORT
if (t == 0 && d == 0xCCC) {
/* Tone-only: all digits are space (0xC) per STD-43A
* Table 3.9.2-1 note. For long addresses, also check Vy. */
bool tone = true;
if (decode.long_address && j + 1 < 88) {
uint32_t vy = phaseptr[j + 1] & 0xFFFFF;
if (vy != 0xCCCCC) tone = false;
}
if (tone)
strcpy(packet.message, "TONE");
else
goto short_numeric;
} else if (t == 0) {
short_numeric:
/* Numeric: 3 BCD digits from Vx (d0-d11).
* Long addresses: 5 more digits from Vy (d12-d31),
* 8 digits total. d32 is spare (set to 0). */
char *p = packet.message, *e = p + sizeof(packet.message);
p = str_append(p, e, "NUM ");
*p++ = flex_bcd[(d >> 0) & 0xF];
*p++ = flex_bcd[(d >> 4) & 0xF];
*p++ = flex_bcd[(d >> 8) & 0xF];
if (decode.long_address && j + 1 < 88) {
uint32_t vy = phaseptr[j + 1];
*p++ = flex_bcd[(vy >> 0) & 0xF];
*p++ = flex_bcd[(vy >> 4) & 0xF];
*p++ = flex_bcd[(vy >> 8) & 0xF];
*p++ = flex_bcd[(vy >> 12) & 0xF];
*p++ = flex_bcd[(vy >> 16) & 0xF];
}
*p = '\0';
} else if (t == 1) {
/* Source: S2S1S0 in d0-d2 */
char *p = packet.message, *e = p + sizeof(packet.message);
p = str_append(p, e, "SRC ");
str_uint(p, e, d & 0x07);
} else if (t == 2) {
/* Numbered: S(3) + N(6) + R(1) */
uint32_t src = d & 0x07;
uint32_t n = (d >> 3) & 0x3F;
uint32_t r = (d >> 9) & 0x01;
char *p = packet.message, *e = p + sizeof(packet.message);
p = str_append(p, e, "SRC ");
p = str_uint(p, e, src);
p = str_append(p, e, " N=");
p = str_uint(p, e, n);
p = str_append(p, e, " R=");
str_uint(p, e, r);
} else {
/* Reserved */
char *p = packet.message, *e = p + sizeof(packet.message);
p = str_append(p, e, "RESERVED ");
str_hex(p, e, d, 3);
}
send_packet(packet);
} else if (decode.type == flex::PageType::BINARY) {
/* HEX/Binary message.
* Word 1 (mw1): K(12) C(1) F(2) N(6) = header
* Word 2 (mw1+1, first frag only): R(1) M(1) D(1) H(1) B(4) I(1) rsvd(4) S(8)
* Words 3+: data */
if (mw1 > 87 || mw2 > 87) continue;
/* Extract header from word 1 */
uint8_t hex_c = 0, hex_f = 0, hex_n = 0;
int hex_hdr_valid = 0;
if (!word_bad[mw1]) {
uint32_t hw1 = phaseptr[mw1];
hex_c = (hw1 >> 12) & 0x01;
hex_f = (hw1 >> 13) & 0x03;
hex_n = (hw1 >> 15) & 0x3F;
hex_hdr_valid = 1;
}
/* Extract word 2 flags (first fragment: F=3) */
uint8_t hex_r = 0, hex_m = 0, hex_d = 0, hex_b = 0;
int data_start = mw1 + 1; // default: data starts after header
if (hex_f == 3 && (mw1 + 1) <= mw2 && !word_bad[mw1 + 1]) {
uint32_t hw2 = phaseptr[mw1 + 1];
hex_r = (hw2 >> 0) & 0x01;
hex_m = (hw2 >> 1) & 0x01;
hex_d = (hw2 >> 2) & 0x01;
hex_b = (hw2 >> 4) & 0x0F;
data_start = mw1 + 2; // skip both header words
}
/* Dump data words as hex */
char message[256] = {0};
char *mp = message, *me = message + 250;
for (int w = data_start; w <= mw2 && mp < me; w++) {
if (word_bad[w]) {
mp = str_append(mp, me, "?????? ");
} else {
mp = str_hex(mp, me, phaseptr[w] & 0x1FFFFF, 5);
if (mp < me) *mp++ = ' ';
*mp = '\0';
}
}
if (mp > message && *(mp - 1) == ' ') {
mp--;
*mp = '\0';
}
int pos = (int)(mp - message);
flex::FlexPacket packet{};
packet.bitrate = sync.baud * (sync.levels == 4 ? 2 : 1);
packet.capcode = decode.capcode;
packet.function = 0;
packet.type = 6; // HEX
packet.status = 0;
packet.cycle = fiw.cycleno;
packet.frame = fiw.frameno;
packet.phase = PhaseNo;
packet.is_inverted = sync.polarity;
packet.fiw_roaming = fiw.roaming;
packet.addr_type = static_cast<uint8_t>(decode.addr_type);
packet.is_priority = decode.is_priority;
if (hex_hdr_valid) {
packet.frag = hex_f;
packet.more_frag = hex_c;
packet.seq = hex_n;
packet.has_flags = 1;
if (hex_f == 3) {
packet.is_new = hex_r;
packet.maildrop = hex_m;
/* Store b and d in function field: low nibble=b, bit4=d */
packet.function = (hex_d << 4) | hex_b;
}
}
memcpy(packet.message, message, pos + 1);
send_packet(packet);
} else if (decode.type == flex::PageType::SHORT_INSTRUCTION) {
/* Short instruction: 14-bit data in vector bits 7-20.
* i2i1i0 (bits 0-2 of data) = instruction type.
* Remaining bits = instruction-specific data. */
uint32_t instr_data = (viw >> 7) & 0x3FFF;
uint32_t itype = instr_data & 0x07;
flex::FlexPacket packet{};
packet.bitrate = sync.baud * (sync.levels == 4 ? 2 : 1);
packet.capcode = decode.capcode;
packet.function = 0;
packet.type = 1; // INS
packet.cycle = fiw.cycleno;
packet.frame = fiw.frameno;
packet.phase = PhaseNo;
packet.is_inverted = sync.polarity;
packet.fiw_roaming = fiw.roaming;
packet.addr_type = static_cast<uint8_t>(decode.addr_type);
packet.is_priority = decode.is_priority;
if (itype == 0) {
uint32_t tgt_frame = (instr_data >> 3) & 0x7F;
uint32_t slot = (instr_data >> 10) & 0x0F;
packet.biw_v1 = slot;
packet.biw_v2 = tgt_frame;
{
char *p = packet.message, *e = p + sizeof(packet.message);
p = str_append(p, e, "i=temp|slot=");
p = str_uint(p, e, slot);
p = str_append(p, e, "|target=");
str_uint(p, e, tgt_frame);
}
} else if (itype == 1) {
uint32_t flags = (instr_data >> 3) & 0x7FF;
{
char *p = packet.message, *e = p + sizeof(packet.message);
p = str_append(p, e, "i=event|flags=");
str_hex(p, e, flags, 3);
}
} else {
{
char *p = packet.message, *e = p + sizeof(packet.message);
p = str_append(p, e, "i=rsvd|type=");
p = str_uint(p, e, itype);
p = str_append(p, e, "|raw=");
str_hex(p, e, instr_data, 4);
}
}
send_packet(packet);
}
}
}
void FlexProcessor::parse_capcode(uint32_t aw1) {
decode.long_address = (aw1 < 0x008001L) || (aw1 > 0x1E0000L) || (aw1 > 0x1E7FFEL);
/* Classify address word by range. */
decode.long_address = 0;
decode.addr_type = flex::AddrType::SHORT;
if ((aw1 >= 0x000001 && aw1 <= 0x008000) || /* LA1 */
(aw1 >= 0x1E0001 && aw1 <= 0x1E8000) || /* LA3 */
(aw1 >= 0x1E8001 && aw1 <= 0x1F0000) || /* LA4 */
(aw1 >= 0x1F7FFF && aw1 <= 0x1FFFFE)) { /* LA2 */
decode.long_address = 1;
decode.addr_type = flex::AddrType::LONG;
} else if (aw1 >= 0x1F7800 && aw1 <= 0x1F780F) {
decode.addr_type = flex::AddrType::TEMPORARY;
} else if (aw1 >= 0x1F7810 && aw1 <= 0x1F781F) {
decode.addr_type = flex::AddrType::OPERATOR;
} else if (aw1 >= 0x1F6800 && aw1 <= 0x1F77FF) {
decode.addr_type = flex::AddrType::NETWORK;
} else if (aw1 >= 0x1F2800 && aw1 <= 0x1F67FF) {
decode.addr_type = flex::AddrType::INFO_SVC;
} else if ((aw1 >= 0x1F0001 && aw1 <= 0x1F27FF) ||
(aw1 >= 0x1F7820 && aw1 <= 0x1F7FFE)) {
decode.addr_type = flex::AddrType::RESERVED;
} else if (aw1 >= 0x008001 && aw1 <= 0x1E0000) {
decode.addr_type = flex::AddrType::SHORT;
} else {
decode.addr_type = flex::AddrType::UNKNOWN;
}
decode.capcode = aw1 - 0x8000;
}
void FlexProcessor::parse_alphanumeric(uint32_t* phaseptr, char, int mw1, int mw2, int) {
char message[128] = {0}; // Fixed buffer for message
void FlexProcessor::parse_alphanumeric(uint32_t* phaseptr, const uint8_t* word_bad, char PhaseNo, int mw1, int mw2, int) {
char message[256] = {0};
int currentChar = 0;
// int frag = (phaseptr[mw1] >> 11) & 0x03;
// int cont = (phaseptr[mw1] >> 0x0A) & 0x01;
// Helper logic for fragmentation (ignored for basic display)
/* First message word is the header (K, C, F, N, R, M fields).
* Extract flags before skipping to content. */
uint8_t hdr_c = 0, hdr_f = 0, hdr_n = 0, hdr_r = 0, hdr_m = 0;
uint8_t hdr_sig = 0;
int hdr_valid = 0;
if (mw1 >= 0 && mw1 < 88 && !word_bad[mw1]) {
uint32_t hdr = phaseptr[mw1];
hdr_c = (hdr >> 10) & 0x01; // bit 10
hdr_f = (hdr >> 11) & 0x03; // bits 11-12
hdr_n = (hdr >> 13) & 0x3F; // bits 13-18
hdr_r = (hdr >> 19) & 0x01; // bit 19
hdr_m = (hdr >> 20) & 0x01; // bit 20
hdr_valid = 1;
}
mw1++;
/* Extract signature from first data word (bits 0-6) */
if (mw1 >= 0 && mw1 < 88 && !word_bad[mw1]) {
hdr_sig = phaseptr[mw1] & 0x7F;
}
for (int i = mw1; i <= mw2; i++) {
unsigned int dw = phaseptr[i];
unsigned char ch;
int bad = (i >= 0 && i < 88) ? word_bad[i] : 1;
// Extract chars (7-bit ASCII)
// If i > mw1 (not first word) or fragment check (simplified here)
if (i > mw1) {
ch = dw & 0x7F;
if (ch != 0x03 && currentChar < 127) message[currentChar++] = ch;
if (bad) {
if (currentChar < 255) message[currentChar++] = '?';
} else if (ch >= 0x20 || ch == 0x0A || ch == 0x0D) {
if (currentChar < 255) message[currentChar++] = ch;
} else if (ch == 0x03 || ch == 0x00) {
if (currentChar < 255) message[currentChar++] = '\x03';
}
}
ch = (dw >> 7) & 0x7F;
if (ch != 0x03 && currentChar < 127) message[currentChar++] = ch;
if (bad) {
if (currentChar < 255) message[currentChar++] = '?';
} else if (ch >= 0x20 || ch == 0x0A || ch == 0x0D) {
if (currentChar < 255) message[currentChar++] = ch;
} else if (ch == 0x03 || ch == 0x00) {
if (currentChar < 255) message[currentChar++] = '\x03';
}
ch = (dw >> 14) & 0x7F;
if (ch != 0x03 && currentChar < 127) message[currentChar++] = ch;
if (bad) {
if (currentChar < 255) message[currentChar++] = '?';
} else if (ch >= 0x20 || ch == 0x0A || ch == 0x0D) {
if (currentChar < 255) message[currentChar++] = ch;
} else if (ch == 0x03 || ch == 0x00) {
if (currentChar < 255) message[currentChar++] = '\x03';
}
}
/* Post-process: trim trailing ETX/NUL padding, but if printable chars
* appear after an ETX/NUL, show each ETX/NUL as '?' (invalid char). */
{
/* First find the last printable character */
int last_printable = -1;
for (int k = 0; k < currentChar; k++) {
if (message[k] != '\x03') last_printable = k;
}
/* Now output up to last_printable, replacing ETX with '?' */
int out = 0;
for (int k = 0; k <= last_printable && out < 255; k++) {
if (message[k] == '\x03')
message[out++] = '?';
else
message[out++] = message[k];
}
currentChar = out;
}
message[currentChar] = '\0';
flex::FlexPacket packet;
packet.bitrate = sync.baud;
flex::FlexPacket packet{};
packet.bitrate = sync.baud * (sync.levels == 4 ? 2 : 1);
packet.capcode = decode.capcode;
packet.function = 0; // TODO extract function if available
packet.type = 5; // ALPHANUMERIC
packet.status = 0; // OK
packet.function = 0;
packet.type = (decode.type == flex::PageType::SECURE) ? 0 : 5;
packet.status = 0;
packet.cycle = fiw.cycleno;
packet.frame = fiw.frameno;
packet.phase = PhaseNo;
packet.is_inverted = sync.polarity;
packet.fiw_roaming = fiw.roaming;
packet.addr_type = static_cast<uint8_t>(decode.addr_type);
packet.is_priority = decode.is_priority;
if (hdr_valid) {
packet.frag = hdr_f;
packet.more_frag = hdr_c;
packet.seq = hdr_n;
packet.is_new = hdr_r;
packet.maildrop = hdr_m;
packet.sig = hdr_sig;
packet.has_flags = 1;
if (decode.type == flex::PageType::SECURE) {
/* Secure: bits 19-20 are t1t0 (encoding type), not R/M */
packet.sec_enc = (hdr_r) | (hdr_m << 1); // t0=bit19, t1=bit20
packet.is_new = 0;
packet.maildrop = 0;
}
}
memcpy(packet.message, message, currentChar + 1);
send_packet(packet);
}
void FlexProcessor::parse_numeric(uint32_t* phaseptr, char, int j) {
// Simplified numeric parsing
char message[128] = {0};
const char flex_bcd[] = "0123456789 U -][";
void FlexProcessor::parse_numeric(uint32_t* phaseptr, const uint8_t* word_bad, char PhaseNo, int j) {
char message[256] = {0};
/* Extract NNUM header fields from first message word if applicable.
* Layout: K5K4(2) + N0-N5(6) + R0(1) + S0(1) + BCD digits... */
uint8_t nnum_n = 0, nnum_r = 0, nnum_s = 0;
int is_nnum = (decode.type == flex::PageType::NUMBERED_NUMERIC);
int w1 = phaseptr[j] >> 7;
int w2 = w1 >> 7;
w1 = w1 & 0x7f;
w2 = (w2 & 0x07) + w1;
int n_field = w2 & 0x07; // word_count - 1
w2 = n_field + w1;
int dw;
// Handle short vs long logic if needed (simplified)
dw = phaseptr[w1];
w1++;
w2++;
// Bounds check: phase buffer is 88 words (indices 0-87)
if (w1 > 87) return;
if (w2 > 87) w2 = 87;
/* For long addresses (3.9.1):
* 1-word: b field points to Vy. body[0] at w1.
* Multi-word: body[0] at Vy (j+1). b field points to MF body[1]. */
int body0_idx;
if (decode.long_address && n_field > 0)
body0_idx = j + 1; // Vy = 2nd vector word
else
body0_idx = w1;
if (body0_idx < 0 || body0_idx >= 88) return;
int dw = phaseptr[body0_idx];
if (is_nnum) {
/* Extract N, R, S from the first message word's BCD stream.
* After K5K4 (2 bits), next 6 bits = N, then R, then S.
* These are consumed by the skip count (count starts at 4+10=14). */
nnum_n = (dw >> 2) & 0x3F; // bits 2-7
nnum_r = (dw >> 8) & 0x01; // bit 8
nnum_s = (dw >> 9) & 0x01; // bit 9
}
unsigned char digit = 0;
int count = 4; // Standard numeric skip
if (decode.type == flex::PageType::NUMBERED_NUMERIC)
count += 10;
int count = 4;
if (is_nnum)
count += 10; // skip K5K4(2) + N(6) + R(1) + S(1)
else
count += 2;
count += 2; // skip K5K4(2)
int idx = 0;
for (int i = w1; i <= w2; i++) {
/* Phase 1: decode body[0] bits.
* For short addresses, body[0] is at w1 and we advance to w1+1.
* For long addresses, body[0] is at Vy (j+1), then we continue from w1. */
if (word_bad[body0_idx]) {
/* Uncorrectable word — emit '?' for each digit slot */
int data_bits = 21 - (count - 4); /* bits available after skip */
int lost_digits = data_bits / 4;
while (lost_digits-- > 0 && idx < 255)
message[idx++] = '?';
count = 4; /* reset for next word */
digit = 0;
} else {
for (int k = 0; k < 21; k++) {
digit = (digit >> 1) & 0x0F;
if (dw & 0x01) digit ^= 0x08;
dw >>= 1;
if (--count == 0) {
if (digit != 0x0C && idx < 127) {
if (idx < 255) {
message[idx++] = flex_bcd[digit];
}
count = 4;
}
}
dw = phaseptr[i];
}
/* Phase 2: decode remaining body words from MF.
* Short: body[1..n] at w1+1 .. w2.
* Long: MF has n_field words at w1 .. w1+n_field-1.
* (n_field = total_words - 1; body[0] is at Vy, not in MF) */
int start, end;
if (decode.long_address) {
start = w1;
end = w1 + n_field - 1; // empty when n_field=0
} else {
start = w1 + 1;
end = w2;
}
for (int i = start; i <= end && i < 88; i++) {
if (word_bad[i]) {
/* Uncorrectable word — emit '?' for each digit slot (5 per word) */
int lost_digits = 21 / 4; /* 5 digits per 21-bit word */
while (lost_digits-- > 0 && idx < 255)
message[idx++] = '?';
count = 4;
digit = 0;
continue;
}
dw = phaseptr[i];
for (int k = 0; k < 21; k++) {
digit = (digit >> 1) & 0x0F;
if (dw & 0x01) digit ^= 0x08;
dw >>= 1;
if (--count == 0) {
if (idx < 255) {
message[idx++] = flex_bcd[digit];
}
count = 4;
}
}
}
/* Trim trailing BCD space padding (0x0C = ' ').
* The encoder pads unused nibble slots with 0x0C */
while (idx > 0 && message[idx - 1] == ' ')
idx--;
message[idx] = '\0';
flex::FlexPacket packet;
packet.bitrate = sync.baud;
flex::FlexPacket packet{};
packet.bitrate = sync.baud * (sync.levels == 4 ? 2 : 1);
packet.capcode = decode.capcode;
packet.function = 0;
packet.type = 3; // NUMERIC
/* Set correct type: 3=NUM, 4=SNUM, 7=NNUM */
if (decode.type == flex::PageType::SPECIAL_NUMERIC)
packet.type = 4;
else if (is_nnum)
packet.type = 7;
else
packet.type = 3;
packet.status = 0;
packet.cycle = fiw.cycleno;
packet.frame = fiw.frameno;
packet.phase = PhaseNo;
packet.is_inverted = sync.polarity;
packet.fiw_roaming = fiw.roaming;
packet.addr_type = static_cast<uint8_t>(decode.addr_type);
packet.is_priority = decode.is_priority;
if (is_nnum) {
packet.seq = nnum_n;
packet.is_new = nnum_r;
packet.nnum_s = nnum_s;
packet.has_flags = 1;
}
memcpy(packet.message, message, idx + 1);
send_packet(packet);
}
void FlexProcessor::parse_tone_only(uint32_t*, char, int) {
flex::FlexPacket packet;
packet.bitrate = sync.baud;
void FlexProcessor::parse_tone_only(uint32_t*, char PhaseNo, int) {
if (decode.capcode == 1) return; // idle artifact
flex::FlexPacket packet{};
packet.bitrate = sync.baud * (sync.levels == 4 ? 2 : 1);
packet.capcode = decode.capcode;
packet.function = 0;
packet.type = 2; // TONE
packet.status = 0;
snprintf(packet.message, sizeof(packet.message), "Tone Only");
packet.cycle = fiw.cycleno;
packet.frame = fiw.frameno;
packet.phase = PhaseNo;
packet.is_inverted = sync.polarity;
packet.fiw_roaming = fiw.roaming;
packet.addr_type = static_cast<uint8_t>(decode.addr_type);
packet.is_priority = decode.is_priority;
strcpy(packet.message, "");
send_packet(packet);
}
+23 -3
View File
@@ -66,6 +66,11 @@ struct FlexStateInfo {
unsigned int fiwcount = 0;
State Current = State::SYNC1;
State Previous = State::SYNC1;
// S2 C-pattern detection
uint16_t sync2_shiftreg = 0; // 16-bit shift register for C match
int sync2_c_pos = -1; // symbol position where C was found (-1=not found)
int sync2_cinv_pos = -1; // symbol position where inv.C was found
};
struct FlexSync {
@@ -81,7 +86,9 @@ struct FlexFIW {
unsigned int checksum = 0;
unsigned int cycleno = 0;
unsigned int frameno = 0;
unsigned int fix3 = 0;
unsigned int roaming = 0; // bit 15: n (1=roaming provided)
unsigned int repeat = 0; // bit 16: r (1=multiple transmission)
unsigned int traffic = 0; // bits 17-20: t3-t0
};
struct FlexPhase {
@@ -98,10 +105,23 @@ struct FlexData {
FlexPhase PhaseD;
};
enum class AddrType : uint8_t {
SHORT, // normal individual
LONG, // 9-10 digit
TEMPORARY, // 0x1F7800-0F (16 group slots)
OPERATOR, // 0x1F7810-1F (system messages)
NETWORK, // 0x1F6800-77FF (NID)
INFO_SVC, // 0x1F2800-67FF (under study)
RESERVED, // reserved ranges
UNKNOWN
};
struct FlexDecode {
PageType type = PageType::ALPHANUMERIC;
int long_address = 0;
int64_t capcode = 0;
AddrType addr_type = AddrType::SHORT;
int is_priority = 0;
};
} // namespace flex
@@ -161,8 +181,8 @@ class FlexProcessor : public BasebandProcessor {
// Parsing
void parse_capcode(uint32_t aw1);
void parse_alphanumeric(uint32_t* phaseptr, char PhaseNo, int mw1, int mw2, int flex_groupmessage);
void parse_numeric(uint32_t* phaseptr, char PhaseNo, int j);
void parse_alphanumeric(uint32_t* phaseptr, const uint8_t* word_bad, char PhaseNo, int mw1, int mw2, int flex_groupmessage);
void parse_numeric(uint32_t* phaseptr, const uint8_t* word_bad, char PhaseNo, int j);
void parse_tone_only(uint32_t* phaseptr, char PhaseNo, int j);
void parse_unknown(uint32_t* phaseptr, char PhaseNo, int mw1, int mw2);
+93
View File
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2024 PortaPack-MAYHEM Contributors
*
* 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 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "proc_p25_tx.hpp"
#include "portapack_shared_memory.hpp"
#include "sine_table_int8.hpp"
#include "event_m4.hpp"
#include <cstdint>
// Gray-coded dibit → FM deviation level:
// dibit 0 → +1 unit (+600 Hz)
// dibit 1 → +3 units (+1800 Hz)
// dibit 2 → -1 unit (-600 Hz)
// dibit 3 → -3 units (-1800 Hz)
static constexpr int8_t dibit_to_level[4] = {1, 3, -1, -3};
void P25TxProcessor::execute(const buffer_c8_t& buffer) {
if (!configured) {
// Zero output - never emit garbage while idle
for (size_t i = 0; i < buffer.count; i++)
buffer.p[i] = {0, 0};
return;
}
for (size_t i = 0; i < buffer.count; i++) {
if (sample_count == 0) {
if (dibit_index >= frame_length) {
// Frame complete - notify A7 and stop
txprogress_message.done = true;
shared_memory.application_queue.push(txprogress_message);
configured = false;
for (size_t j = i; j < buffer.count; j++)
buffer.p[j] = {0, 0};
return;
}
}
// Current dibit → frequency level
uint8_t dibit = shared_memory.bb_data.data[dibit_index] & 0x03;
int8_t level = dibit_to_level[dibit];
// Accumulate FM phase at ±level × base_phase_step per sample
phase += (uint32_t)((int32_t)level * (int32_t)base_phase_step);
int8_t re = sine_table_i8[(phase + 0x40000000) >> 24]; // cos
int8_t im = sine_table_i8[phase >> 24]; // sin
buffer.p[i] = {re, im};
sample_count++;
if (sample_count >= P25_SAMPLES_PER_DIBIT) {
sample_count = 0;
dibit_index++;
}
}
}
void P25TxProcessor::on_message(const Message* const msg) {
if (msg->id == Message::ID::P25TxConfigure) {
const auto& m = *reinterpret_cast<const P25TxConfigureMessage*>(msg);
if (m.frame_length == 0) {
configured = false;
return;
}
frame_length = m.frame_length;
dibit_index = 0;
sample_count = 0;
txprogress_message.done = false;
configured = true;
}
}
int main() {
EventDispatcher event_dispatcher{std::make_unique<P25TxProcessor>()};
event_dispatcher.run();
return 0;
}
+55
View File
@@ -0,0 +1,55 @@
/*
* Copyright (C) 2024 PortaPack-MAYHEM Contributors
*
* 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 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __PROC_P25_TX_H__
#define __PROC_P25_TX_H__
#include "baseband_processor.hpp"
#include "baseband_thread.hpp"
#include "message.hpp"
// P25 C4FM: 4800 baud, 2.4 Msps = 500 samples per dibit
#define P25_SAMPLERATE 2400000
#define P25_SAMPLES_PER_DIBIT 500
class P25TxProcessor : public BasebandProcessor {
public:
void execute(const buffer_c8_t& buffer) override;
void on_message(const Message* const msg) override;
private:
bool configured{false};
uint16_t frame_length{0}; // total dibits in frame
uint16_t dibit_index{0}; // current dibit being transmitted
uint32_t sample_count{0}; // samples emitted for current dibit
// FM phase accumulator (32-bit wrapping)
uint32_t phase{0};
// Phase step per sample per deviation unit (600 Hz at 2.4 Msps)
// = round(600 * 2^32 / 2400000) = 1073742
static constexpr uint32_t base_phase_step{1073742};
TXProgressMessage txprogress_message{};
/* NB: Threads should be the last members in the class definition. */
BasebandThread baseband_thread{P25_SAMPLERATE, this, baseband::Direction::Transmit};
};
#endif /* __PROC_P25_TX_H__ */
+2 -8
View File
@@ -38,14 +38,7 @@ using namespace std;
namespace {
/* Count of bits that differ between the two values. */
uint8_t diff_bit_count(uint32_t left, uint32_t right) {
uint32_t diff = left ^ right;
uint8_t count = 0;
for (size_t i = 0; i < sizeof(diff) * 8; ++i) {
if (((diff >> i) & 0x1) == 1)
++count;
}
return count;
return __builtin_popcount(left ^ right);
}
} // namespace
@@ -426,6 +419,7 @@ void POCSAGProcessor::send_packet() {
packet.set_flag(pocsag::PacketFlag::NORMAL);
packet.set_timestamp(Timestamp::now());
packet.set_bitrate(bit_extractor.baud_rate());
packet.set_inverted(word_extractor.inverted());
packet.set(word_extractor.batch());
POCSAGPacketMessage message(packet);
+3
View File
@@ -153,6 +153,9 @@ class CodewordExtractor {
/* Returns true if the batch has as sync frame. */
bool has_sync() const { return has_sync_; }
/* Returns true if the signal was received with inverted polarity. */
bool inverted() const { return inverted_; }
private:
/* Sync frame codeword. */
static constexpr uint32_t sync_codeword = 0x7cd215d8;
+332
View File
@@ -0,0 +1,332 @@
/*
* Copyright (C) 2024 PortaPack Mayhem
*
* 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 "proc_tonedetect.hpp"
#include "audio_dma.hpp"
#include "portapack_shared_memory.hpp"
#include "event_m4.hpp"
#include <cmath>
static constexpr float SAMPLE_RATE = 24000.0f;
static constexpr uint32_t WINDOW_SAMPLES = 960; // 40 ms at 24 kHz (30 execute() calls)
static constexpr uint32_t WINDOW_MS = (1000 * WINDOW_SAMPLES) / (uint32_t)SAMPLE_RATE;
static constexpr uint32_t AUDIO_BLOCK_SAMPLES = 32; // demod_fm emits 32 audio samples per execute()
static constexpr uint32_t SQUELCH_HOLD_BLOCKS =
(100 * (uint32_t)SAMPLE_RATE) / (1000 * AUDIO_BLOCK_SAMPLES); // 100 ms hold at execute() block rate
static constexpr float PI_F = 3.14159265f;
// Motorola/EIA QCII paging frequencies (×10 to avoid float in table)
static constexpr uint32_t MOTO_FREQS_X10[45] = {
2885,
3047,
3217,
3396,
3586,
3786,
3998,
4221,
4457,
4705,
4968,
5246,
5539,
5848,
6174,
6519,
6883,
7268,
7674,
8102,
8555,
9032,
9537,
10073,
10642,
11225,
11247,
11534,
11852,
11885,
12178,
12514,
12555,
12858,
13258,
13576,
13950,
13996,
14768,
15579,
16430,
17325,
18262,
19245,
20275,
};
// Minimum coherent Goertzel energy for MOTO tone detection.
// For amplitude A over WINDOW_SAMPLES: energy ≈ (A × N/2)² = (A × 240)².
// Threshold 1000 → requires A > ~13% of FM demod full scale (~650 Hz deviation).
// Set high enough that FM broadband noise (σ ≈ 0.3, expected per-bin energy ≈ 43)
// never triggers a false detection even when the carrier gate is briefly open.
static constexpr float MOTO_ENERGY_THRESHOLD = 1000.0f;
// Fixed carrier-detect threshold for the detection gate (independent of user squelch).
// FMSquelch returns true when HF noise is BELOW this value (= FM carrier present).
// 0.20 opens reliably on any clean FM carrier without false-opening on noise.
static constexpr float CARRIER_DETECT_THRESHOLD = 0.20f;
// Goertzel energy threshold for CTCSS detection.
// Pure CTCSS at 5% amplitude over 960 samples → energy ≈ (0.05 × 480)² = 576.
static constexpr float CTCSS_ENERGY_THRESHOLD = 30.0f;
void ToneDetectProcessor::configure(uint8_t squelch, uint32_t ctcss_f_x10) {
configured = false;
user_squelch_level = squelch;
ctcss_freq_x10 = ctcss_f_x10;
decim_0.configure(taps_11k0_decim_0.taps);
decim_1.configure(taps_11k0_decim_1.taps);
channel_filter.configure(taps_11k0_channel.taps, 2);
demod_fm.configure(24000, 5000);
audio_output.configure(false);
fm_squelch.set_threshold((float)user_squelch_level / 100.0f);
channel_spectrum.set_decimation_factor(1);
// Precompute Goertzel coefficient for CTCSS (if active).
// k = nearest DFT bin for the CTCSS frequency over WINDOW_SAMPLES.
if (ctcss_freq_x10 > 0) {
const float freq = (float)ctcss_freq_x10 / 10.0f;
const float k = roundf((float)WINDOW_SAMPLES * freq / SAMPLE_RATE);
const float omega = 2.0f * PI_F * k / (float)WINDOW_SAMPLES;
goertzel_coeff = 2.0f * cosf(omega);
} else {
goertzel_coeff = 0.0f;
}
// Precompute Goertzel coefficients for all 45 MOTO frequencies.
// Each filter is tuned to the EXACT MOTO frequency (not the nearest DFT bin center)
// so that every entry has a unique coefficient and maximum energy only at its
// specific frequency. This eliminates bin-sharing ambiguity and gives the best
// discrimination between close entries such as 1357.6 Hz and 1395.0 Hz.
for (size_t i = 0; i < 45; i++) {
const float freq = (float)MOTO_FREQS_X10[i] / 10.0f;
const float omega = 2.0f * PI_F * freq / SAMPLE_RATE;
moto_coeff[i] = 2.0f * cosf(omega);
moto_s1[i] = 0.0f;
moto_s2[i] = 0.0f;
}
// Fixed carrier-detect squelch — threshold never changes with user settings.
carrier_sq.set_threshold(CARRIER_DETECT_THRESHOLD);
// Reset all per-window state
goertzel_s1 = 0.0f;
goertzel_s2 = 0.0f;
window_sample_count = 0;
was_ctcss_detected = false;
tone_duration_windows = 0;
squelch_is_open = false;
squelch_hold = 0;
carrier_is_open = false;
carrier_hold = 0;
configured = true;
}
void ToneDetectProcessor::execute(const buffer_c8_t& buffer) {
if (!configured) return;
const auto decim_0_out = decim_0.execute(buffer, dst_buffer);
const auto decim_1_out = decim_1.execute(decim_0_out, dst_buffer);
// Feed IQ data into spectrum collector for the RF waterfall.
channel_spectrum.feed(decim_1_out, -5500, 5500, 3400);
const auto channel_out = channel_filter.execute(decim_1_out, dst_buffer);
auto audio_buf = demod_fm.execute(channel_out, audio_buffer);
// --- Audio muting squelch (user-adjustable level) ---
// FMSquelch returns true when HF noise is LOW (carrier present).
const bool fm_open = fm_squelch.execute(audio_buf);
if (fm_open) {
squelch_hold = SQUELCH_HOLD_BLOCKS;
squelch_is_open = true;
} else if (squelch_hold > 0) {
squelch_hold--;
} else {
squelch_is_open = false;
}
// --- Fixed carrier-detect gate (independent of user squelch level) ---
// carrier_sq always uses CARRIER_DETECT_THRESHOLD (0.20) regardless of squelch_val.
// This ensures the detection gate closes when the carrier disappears even when the
// user sets squelch=0 (always-open audio), preventing the state machine from
// accumulating noise windows or getting stuck between transmissions.
const bool carrier_raw = carrier_sq.execute(audio_buf);
if (carrier_raw) {
carrier_hold = SQUELCH_HOLD_BLOCKS;
carrier_is_open = true;
} else if (carrier_hold > 0) {
carrier_hold--;
} else {
carrier_is_open = false;
}
for (size_t i = 0; i < audio_buf.count; i++) {
const float s = audio_buf.p[i];
// Mute audio output when FM squelch is closed (does not affect Goertzel).
if (!squelch_is_open) audio_buf.p[i] = 0.0f;
// CTCSS Goertzel step (CTCSS mode only).
// Uses original unmuted sample so CTCSS energy is unaffected by audio muting.
if (ctcss_freq_x10 > 0) {
const float s0 = s + goertzel_coeff * goertzel_s1 - goertzel_s2;
goertzel_s2 = goertzel_s1;
goertzel_s1 = s0;
}
// MOTO frequency bank — Goertzel step for all 45 MOTO bins.
// Runs unconditionally so the full window always contributes to energy.
// Benefit over zero-crossing: coherent detection, no warm-up period,
// accurate on the very first window after the gate opens.
for (size_t j = 0; j < 45; j++) {
const float s0 = s + moto_coeff[j] * moto_s1[j] - moto_s2[j];
moto_s2[j] = moto_s1[j];
moto_s1[j] = s0;
}
// Window boundary: every WINDOW_SAMPLES samples = one 40 ms estimate window
if (++window_sample_count >= WINDOW_SAMPLES) {
window_sample_count = 0;
// --- Detection gate ---
// Carrier presence (carrier_is_open) is always required — without it,
// the FM demod outputs broadband noise that floods every Goertzel bin and
// triggers false detections regardless of the CTCSS threshold.
// CTCSS mode adds a second requirement: coherent CTCSS energy must also
// be present. This is the standard two-condition squelch used in real radios.
bool gate_open;
if (ctcss_freq_x10 > 0) {
const float power = goertzel_s1 * goertzel_s1 + goertzel_s2 * goertzel_s2 - goertzel_coeff * goertzel_s1 * goertzel_s2;
gate_open = carrier_is_open && (power > CTCSS_ENERGY_THRESHOLD);
goertzel_s1 = 0.0f;
goertzel_s2 = 0.0f;
} else {
gate_open = carrier_is_open;
}
// --- MOTO frequency identification via Goertzel energy ---
// Find the MOTO table entry with the highest coherent energy this window.
// Reset all states regardless of gate so each window starts fresh.
float energies[45]{};
uint32_t best_idx = 45; // 45 = sentinel (no match)
float best_energy = MOTO_ENERGY_THRESHOLD;
for (size_t j = 0; j < 45; j++) {
const float pwr = moto_s1[j] * moto_s1[j] + moto_s2[j] * moto_s2[j] - moto_coeff[j] * moto_s1[j] * moto_s2[j];
energies[j] = pwr;
moto_s1[j] = 0.0f;
moto_s2[j] = 0.0f;
if (pwr > best_energy) {
best_energy = pwr;
best_idx = j;
}
}
// Report a raw estimate from the local energy centroid around the best
// entry, and let the UI do the final table snap from the phase average.
uint32_t win_freq_hz = 0;
if (best_idx < 45) {
const size_t start = (best_idx > 0) ? (best_idx - 1) : best_idx;
const size_t end = (best_idx + 1 < 45) ? (best_idx + 1) : best_idx;
float weight_sum = 0.0f;
float weighted_freq_x10 = 0.0f;
for (size_t j = start; j <= end; j++) {
const float weight = energies[j] - MOTO_ENERGY_THRESHOLD;
if (weight > 0.0f) {
weight_sum += weight;
weighted_freq_x10 += weight * (float)MOTO_FREQS_X10[j];
}
}
if (weight_sum > 0.0f) {
win_freq_hz = (uint32_t)((weighted_freq_x10 / weight_sum) / 10.0f + 0.5f);
} else {
win_freq_hz = MOTO_FREQS_X10[best_idx] / 10;
}
}
if (gate_open) {
if (!was_ctcss_detected) {
tone_duration_windows = 0;
}
tone_duration_windows++;
was_ctcss_detected = true;
data_message.freq_hz = win_freq_hz;
data_message.duration_ms = tone_duration_windows * WINDOW_MS;
data_message.tone_end = false;
shared_memory.application_queue.push(data_message);
} else {
if (was_ctcss_detected) {
// Gate just closed — signal tone end to application
data_message.freq_hz = 0;
data_message.duration_ms = tone_duration_windows * WINDOW_MS;
data_message.tone_end = true;
shared_memory.application_queue.push(data_message);
tone_duration_windows = 0;
}
was_ctcss_detected = false;
}
}
}
audio_output.write(audio_buf);
}
void ToneDetectProcessor::on_message(const Message* const p) {
switch (p->id) {
case Message::ID::ToneDetectConfig: {
const auto& msg = *reinterpret_cast<const ToneDetectConfigureMessage*>(p);
configure(msg.squelch_level, msg.ctcss_freq_x10);
break;
}
case Message::ID::NBFMConfigure: {
const auto& msg = *reinterpret_cast<const NBFMConfigureMessage*>(p);
user_squelch_level = msg.squelch_level;
fm_squelch.set_threshold((float)user_squelch_level / 100.0f);
break;
}
case Message::ID::UpdateSpectrum:
case Message::ID::SpectrumStreamingConfig:
channel_spectrum.on_message(p);
break;
default:
break;
}
}
int main() {
audio::dma::init_audio_out();
EventDispatcher event_dispatcher{std::make_unique<ToneDetectProcessor>()};
event_dispatcher.run();
return 0;
}
+94
View File
@@ -0,0 +1,94 @@
/*
* Copyright (C) 2024 PortaPack Mayhem
*
* 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 __PROC_TONEDETECT_H__
#define __PROC_TONEDETECT_H__
#include "baseband_processor.hpp"
#include "baseband_thread.hpp"
#include "message.hpp"
#include "dsp_decimate.hpp"
#include "dsp_demodulate.hpp"
#include "audio_output.hpp"
#include "dsp_fir_taps.hpp"
#include "rssi_thread.hpp"
#include "spectrum_collector.hpp"
#include "dsp_squelch.hpp"
class ToneDetectProcessor : public BasebandProcessor {
public:
ToneDetectProcessor() {}
void execute(const buffer_c8_t& buffer) override;
void on_message(const Message* const p) override;
private:
void configure(uint8_t squelch, uint32_t ctcss_freq_x10);
BasebandThread baseband_thread{3072000, this, baseband::Direction::Receive};
RSSIThread rssi_thread{};
std::array<complex16_t, 512> dst{};
const buffer_c16_t dst_buffer{dst.data(), dst.size()};
std::array<float, 32> audio{};
const buffer_f32_t audio_buffer{audio.data(), audio.size()};
dsp::decimate::FIRC8xR16x24FS4Decim8 decim_0{};
dsp::decimate::FIRC16xR16x32Decim8 decim_1{};
dsp::decimate::FIRAndDecimateComplex channel_filter{};
dsp::demodulate::FM demod_fm{};
AudioOutput audio_output{};
bool configured{false};
uint8_t user_squelch_level{0};
FMSquelch fm_squelch{}; // user-adjustable: drives audio muting only
FMSquelch carrier_sq{}; // fixed threshold: drives detection gate
// Audio muting squelch state (user-adjustable level, has hold for smooth audio)
bool squelch_is_open{false};
uint32_t squelch_hold{0};
// Carrier-detect gate state (fixed 0.20 threshold, separate from audio squelch)
bool carrier_is_open{false};
uint32_t carrier_hold{0};
// CTCSS gate via Goertzel algorithm (per 40 ms window)
uint32_t ctcss_freq_x10{0}; // 0 = None → fall back to FMSquelch gate
float goertzel_coeff{0.0f}; // 2 * cos(2π * k / WINDOW_SAMPLES)
float goertzel_s1{0.0f};
float goertzel_s2{0.0f};
// 40 ms measurement window
uint32_t window_sample_count{0};
bool was_ctcss_detected{false};
uint32_t tone_duration_windows{0};
// MOTO frequency bank — one Goertzel filter per MOTO table entry.
// States reset each window; coefficients set once in configure().
float moto_coeff[45]{};
float moto_s1[45]{};
float moto_s2[45]{};
ToneDetectDataMessage data_message{};
SpectrumCollector channel_spectrum{};
};
#endif /* __PROC_TONEDETECT_H__ */
+154 -142
View File
@@ -35,6 +35,9 @@
#include "i2c_lpc.h"
#include "cpld_jtag.h"
#include "platform_detect.h"
#include "platform_gpio.h"
#include "platform_scu.h"
#include "fixed_point.h"
#include "clkin.h"
#include <libopencm3/lpc43xx/cgu.h>
#include <libopencm3/lpc43xx/ccu.h>
@@ -48,7 +51,7 @@
#include "gpio_lpc.h"
/* GPIO Output PinMux */
static struct gpio_t gpio_led[] = {
static struct gpio gpio_led[] = {
GPIO(2, 1),
GPIO(2, 2),
GPIO(2, 8),
@@ -58,90 +61,89 @@ static struct gpio_t gpio_led[] = {
};
// clang-format off
static struct gpio_t gpio_1v8_enable = GPIO(3, 6);
static struct gpio gpio_1v8_enable = GPIO(3, 6);
/* MAX283x GPIO (XCVR_CTL) PinMux */
static struct gpio_t gpio_max283x_select = GPIO(0, 15);
static struct gpio gpio_max283x_select = GPIO(0, 15);
/* MAX5864 SPI chip select (AD_CS) GPIO PinMux */
static struct gpio_t gpio_max5864_select = GPIO(2, 7);
static struct gpio gpio_max5864_select = GPIO(2, 7);
/* RFFC5071 GPIO serial interface PinMux */
// #ifdef RAD1O
// static struct gpio_t gpio_rffc5072_select = GPIO(2, 13);
// static struct gpio_t gpio_rffc5072_clock = GPIO(5, 6);
// static struct gpio_t gpio_rffc5072_data = GPIO(3, 3);
// static struct gpio_t gpio_rffc5072_reset = GPIO(2, 14);
// static struct gpio gpio_rffc5072_select = GPIO(2, 13);
// static struct gpio gpio_rffc5072_clock = GPIO(5, 6);
// static struct gpio gpio_rffc5072_data = GPIO(3, 3);
// static struct gpio gpio_rffc5072_reset = GPIO(2, 14);
// #endif
/* RF supply (VAA) control */
#ifdef HACKRF_ONE
static struct gpio_t gpio_vaa_disable = GPIO(2, 9);
static struct gpio gpio_vaa_disable = GPIO(2, 9);
#endif
#ifdef RAD1O
static struct gpio_t gpio_vaa_enable = GPIO(2, 9);
static struct gpio gpio_vaa_enable = GPIO(2, 9);
#endif
static struct gpio_t gpio_w25q80bv_hold = GPIO(1, 14);
static struct gpio_t gpio_w25q80bv_wp = GPIO(1, 15);
static struct gpio_t gpio_w25q80bv_select = GPIO(5, 11);
static struct gpio gpio_w25q80bv_hold = GPIO(1, 14);
static struct gpio gpio_w25q80bv_wp = GPIO(1, 15);
/* RF switch control */
#ifdef HACKRF_ONE
static struct gpio_t gpio_hp = GPIO(2, 0);
static struct gpio_t gpio_lp = GPIO(2, 10);
static struct gpio_t gpio_tx_mix_bp = GPIO(2, 11);
static struct gpio_t gpio_no_mix_bypass = GPIO(1, 0);
static struct gpio_t gpio_rx_mix_bp = GPIO(2, 12);
static struct gpio_t gpio_tx_amp = GPIO(2, 15);
static struct gpio_t gpio_tx = GPIO(5, 15);
static struct gpio_t gpio_mix_bypass = GPIO(5, 16);
static struct gpio_t gpio_rx = GPIO(5, 5);
static struct gpio_t gpio_no_tx_amp_pwr = GPIO(3, 5);
static struct gpio_t gpio_amp_bypass = GPIO(0, 14);
static struct gpio_t gpio_rx_amp = GPIO(1, 11);
static struct gpio_t gpio_no_rx_amp_pwr = GPIO(1, 12);
static struct gpio gpio_hp = GPIO(2, 0);
static struct gpio gpio_lp = GPIO(2, 10);
static struct gpio gpio_tx_mix_bp = GPIO(2, 11);
static struct gpio gpio_no_mix_bypass = GPIO(1, 0);
static struct gpio gpio_rx_mix_bp = GPIO(2, 12);
static struct gpio gpio_tx_amp = GPIO(2, 15);
static struct gpio gpio_tx = GPIO(5, 15);
static struct gpio gpio_mix_bypass = GPIO(5, 16);
static struct gpio gpio_rx = GPIO(5, 5);
static struct gpio gpio_no_tx_amp_pwr = GPIO(3, 5);
static struct gpio gpio_amp_bypass = GPIO(0, 14);
static struct gpio gpio_rx_amp = GPIO(1, 11);
static struct gpio gpio_no_rx_amp_pwr = GPIO(1, 12);
#endif
#ifdef RAD1O
static struct gpio_t gpio_tx_rx_n = GPIO(1, 11);
static struct gpio_t gpio_tx_rx = GPIO(0, 14);
static struct gpio_t gpio_by_mix = GPIO(1, 12);
static struct gpio_t gpio_by_mix_n = GPIO(2, 10);
static struct gpio_t gpio_by_amp = GPIO(1, 0);
static struct gpio_t gpio_by_amp_n = GPIO(5, 5);
static struct gpio_t gpio_mixer_en = GPIO(5, 16);
static struct gpio_t gpio_low_high_filt = GPIO(2, 11);
static struct gpio_t gpio_low_high_filt_n = GPIO(2, 12);
static struct gpio_t gpio_tx_amp = GPIO(2, 15);
static struct gpio_t gpio_rx_lna = GPIO(5, 15);
static struct gpio gpio_tx_rx_n = GPIO(1, 11);
static struct gpio gpio_tx_rx = GPIO(0, 14);
static struct gpio gpio_by_mix = GPIO(1, 12);
static struct gpio gpio_by_mix_n = GPIO(2, 10);
static struct gpio gpio_by_amp = GPIO(1, 0);
static struct gpio gpio_by_amp_n = GPIO(5, 5);
static struct gpio gpio_mixer_en = GPIO(5, 16);
static struct gpio gpio_low_high_filt = GPIO(2, 11);
static struct gpio gpio_low_high_filt_n = GPIO(2, 12);
static struct gpio gpio_tx_amp = GPIO(2, 15);
static struct gpio gpio_rx_lna = GPIO(5, 15);
#endif
/* CPLD JTAG interface GPIO pins */
static struct gpio_t gpio_cpld_tdo = GPIO(5, 18);
static struct gpio_t gpio_cpld_tck = GPIO(3, 0);
static struct gpio gpio_cpld_tdo = GPIO(5, 18);
static struct gpio gpio_cpld_tck = GPIO(3, 0);
#if (defined HACKRF_ONE || defined RAD1O)
static struct gpio_t gpio_cpld_tms = GPIO(3, 4);
static struct gpio_t gpio_cpld_tdi = GPIO(3, 1);
static struct gpio gpio_cpld_tms = GPIO(3, 4);
static struct gpio gpio_cpld_tdi = GPIO(3, 1);
#else
static struct gpio_t gpio_cpld_tms = GPIO(3, 1);
static struct gpio_t gpio_cpld_tdi = GPIO(3, 4);
static struct gpio gpio_cpld_tms = GPIO(3, 1);
static struct gpio gpio_cpld_tdi = GPIO(3, 4);
#endif
#ifdef HACKRF_ONE
static struct gpio_t gpio_cpld_pp_tms = GPIO(1, 1);
static struct gpio_t gpio_cpld_pp_tdo = GPIO(1, 8);
static struct gpio gpio_cpld_pp_tms = GPIO(1, 1);
static struct gpio gpio_cpld_pp_tdo = GPIO(1, 8);
#endif
/* other CPLD interface GPIO pins */
static struct gpio_t gpio_hw_sync_enable = GPIO(5, 12);
static struct gpio_t gpio_q_invert = GPIO(0, 13);
static struct gpio gpio_hw_sync_enable = GPIO(5, 12);
static struct gpio gpio_q_invert = GPIO(0, 13);
/* HackRF One r9 */
#ifdef HACKRF_ONE
static struct gpio_t gpio_h1r9_rx = GPIO(0, 7);
static struct gpio_t gpio_h1r9_1v8_enable = GPIO(2, 9);
static struct gpio_t gpio_h1r9_vaa_disable = GPIO(3, 6);
static struct gpio_t gpio_h1r9_hw_sync_enable = GPIO(5, 5);
static struct gpio gpio_h1r9_rx = GPIO(0, 7);
static struct gpio gpio_h1r9_1v8_enable = GPIO(2, 9);
static struct gpio gpio_h1r9_vaa_disable = GPIO(3, 6);
static struct gpio gpio_h1r9_hw_sync_enable = GPIO(5, 5);
#endif
// clang-format on
@@ -216,11 +218,10 @@ max5864_driver_t max5864 = {
.target_init = max5864_target_init,
};
const ssp_config_t ssp_config_w25q80bv = {
ssp_config_t ssp_config_w25q80bv = {
.data_bits = SSP_DATA_8BITS,
.serial_clock_rate = 2,
.clock_prescale_rate = 2,
.gpio_select = &gpio_w25q80bv_select,
};
spi_bus_t spi_bus_ssp0 = {
@@ -431,96 +432,105 @@ bool sample_rate_frac_set(uint32_t rate_num, uint32_t rate_denom) {
return true;
}
bool sample_rate_set(const uint32_t sample_rate_hz) {
uint32_t p1 = 4608;
uint32_t p2 = 0;
uint32_t p3 = 0;
/*
* Configure clock generator to produce sample clock in units of 1/(2**24) Hz.
* Can be called with program=false for a dry run that returns the resultant
* frequency without actually configuring the clock generator.
*/
fp_40_24_t sample_rate_set(const fp_40_24_t sample_rate, const bool program) {
const fp_40_24_t vco = 800 * FP_ONE_MHZ;
uint64_t p1, p2, p3;
uint64_t n, d, q;
fp_40_24_t remainder, resultant_rate;
switch (sample_rate_hz) {
case 8000000:
p1 = SI_INTDIV(50); // 800MHz / 50 = 16 MHz (SGPIO), 8 MHz (codec)
break;
fp_40_24_t rate = sample_rate * 2;
case 9216000:
// 43.40277777777778: a = 43; b = 29; c = 72
p1 = 5043;
p2 = 40;
p3 = 72;
break;
p1 = ((128 * vco) / rate) - 512;
if (vco % rate) {
n = (128 * vco) - (rate * (p1 + 512));
d = rate / FP_ONE_HZ;
n += (d / 2);
p2 = n / d;
p3 = 1 << 24;
case 10000000:
p1 = SI_INTDIV(40); // 800MHz / 40 = 20 MHz (SGPIO), 10 MHz (codec)
break;
unsigned int shift = p2 ? __builtin_ctzll(p2) : 24;
p2 >>= shift;
p3 >>= shift;
case 12288000:
// 32.552083333333336: a = 32; b = 159; c = 288
p1 = 3654;
p2 = 192;
p3 = 288;
break;
const uint64_t p3_max = 0xfffff;
if (p3 > p3_max) {
p2 *= p3_max;
p2 += (p3 / 2);
p2 /= p3;
p3 = p3_max;
}
case 12500000:
p1 = SI_INTDIV(32); // 800MHz / 32 = 25 MHz (SGPIO), 12.5 MHz (codec)
break;
if (p2 >= p3) {
p1++;
p2 = 0;
}
} else {
p2 = 0;
}
case 16000000:
p1 = SI_INTDIV(25); // 800MHz / 25 = 32 MHz (SGPIO), 16 MHz (codec)
break;
if (p1 > 0x3fe00) {
p1 = 0x3fe00;
p2 = 0;
}
case 18432000:
// 21.70138888889: a = 21; b = 101; c = 144
p1 = 2265;
p2 = 112;
p3 = 144;
break;
if (p2 == 0) {
p3 = 1;
n = (vco * 128);
d = (p1 + 512);
n += (d / 2);
resultant_rate = n / d;
} else {
const uint64_t vco_hz = vco / FP_ONE_HZ;
n = p3 * vco_hz * 128;
d = p3 * (p1 + 512) + p2;
const uint64_t rate_hz = n / d;
remainder = (n - (d * rate_hz)) * FP_ONE_HZ;
remainder += (d / 2);
q = remainder / d;
resultant_rate = (rate_hz * FP_ONE_HZ) + q;
}
case 20000000:
p1 = SI_INTDIV(20); // 800MHz / 20 = 40 MHz (SGPIO), 20 MHz (codec)
break;
resultant_rate = (resultant_rate + 1) / 2;
default:
return false;
if (!program) {
return resultant_rate;
}
bool streaming = sgpio_cpld_stream_is_enabled(&sgpio_config);
if (streaming) {
sgpio_cpld_stream_disable(&sgpio_config);
}
if (p1 & 0x1 || p2) {
si5351c_set_int_mode(&clock_gen, 0, 0);
} else {
si5351c_set_int_mode(&clock_gen, 0, 1);
}
if (detected_platform() == BOARD_ID_HACKRF1_R9) {
/*
* On HackRF One r9 all sample clocks are externally derived
* from MS1/CLK1 operating at twice the sample rate.
*/
si5351c_configure_multisynth(&clock_gen, 1, p1, p2, p3, 0);
} else {
/*
* On other platforms the clock generator produces three
* different sample clocks, all derived from multisynth 0.
*/
/* MS0/CLK0 is the source for the MAX5864/CPLD (CODEC_CLK). */
si5351c_configure_multisynth(&clock_gen, 0, p1, p2, p3, 1);
/* MS0/CLK1 is the source for the CPLD (CODEC_X2_CLK). */
si5351c_configure_multisynth(
&clock_gen,
1,
p1,
0,
1,
0); // p1 doesn't matter
/* MS0/CLK2 is the source for SGPIO (CODEC_X2_CLK) */
si5351c_configure_multisynth(
&clock_gen,
2,
p1,
0,
1,
0); // p1 doesn't matter
si5351c_configure_multisynth(&clock_gen, 1, 0, 0, 0, 0);
si5351c_configure_multisynth(&clock_gen, 2, 0, 0, 0, 0);
}
return true;
if (streaming) {
sgpio_cpld_stream_enable(&sgpio_config);
}
return resultant_rate;
}
bool baseband_filter_bandwidth_set(const uint32_t bandwidth_hz) {
uint32_t bandwidth_hz_real;
bandwidth_hz_real = max283x_set_lpf_bandwidth(&max283x, bandwidth_hz);
bandwidth_hz_real = max283x_set_lpf_bandwidth(&max283x, MAX283x_MODE_RX, bandwidth_hz);
if (bandwidth_hz_real) {
hackrf_ui()->set_filter_bw(bandwidth_hz_real);
@@ -615,8 +625,8 @@ void cpu_clock_init(void) {
si5351c_power_down_all_clocks(&clock_gen);
si5351c_set_crystal_configuration(&clock_gen);
si5351c_enable_xo_and_ms_fanout(&clock_gen);
si5351c_configure_pll_sources(&clock_gen);
si5351c_configure_pll_multisynth(&clock_gen);
si5351c_configure_pll_sources(&clock_gen, PLL_SOURCE_XTAL);
si5351c_configure_pll_multisynth(&clock_gen, PLL_SOURCE_XTAL);
/*
* Clocks on HackRF One r9:
@@ -667,7 +677,7 @@ void cpu_clock_init(void) {
/* MS7/CLK7 is unused. */
/* Set to 10 MHz, the common rate between Jawbreaker and HackRF One. */
sample_rate_set(10000000);
sample_rate_set(10000000 * (fp_40_24_t)FP_ONE_HZ, true);
si5351c_set_clock_source(&clock_gen, PLL_SOURCE_XTAL);
// soft reset
@@ -854,6 +864,8 @@ void ssp1_set_mode_max5864(void) {
}
void pin_setup(void) {
const platform_scu_t* scu = platform_scu();
/* Configure all GPIO as Input (safe state) */
// gpio_init();
@@ -872,26 +884,26 @@ void pin_setup(void) {
* LPC43xx pull-up and pull-down resistors are approximately 53K.
*/
#ifdef HACKRF_ONE
scu_pinmux(SCU_PINMUX_PP_TMS, SCU_GPIO_PUP | SCU_CONF_FUNCTION0);
scu_pinmux(SCU_PINMUX_PP_TDO, SCU_GPIO_PDN | SCU_CONF_FUNCTION0);
scu_pinmux(scu->PINMUX_PP_TMS, SCU_GPIO_PUP | SCU_CONF_FUNCTION0);
scu_pinmux(scu->PINMUX_PP_TDO, SCU_GPIO_PDN | SCU_CONF_FUNCTION0);
#endif
scu_pinmux(SCU_PINMUX_CPLD_TMS, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION0);
scu_pinmux(SCU_PINMUX_CPLD_TDI, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION0);
scu_pinmux(SCU_PINMUX_CPLD_TDO, SCU_GPIO_PDN | SCU_CONF_FUNCTION4);
scu_pinmux(SCU_PINMUX_CPLD_TCK, SCU_GPIO_PDN | SCU_CONF_FUNCTION0);
scu_pinmux(scu->PINMUX_CPLD_TMS, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION0);
scu_pinmux(scu->PINMUX_CPLD_TDI, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION0);
scu_pinmux(scu->PINMUX_CPLD_TDO, SCU_GPIO_PDN | SCU_CONF_FUNCTION4);
scu_pinmux(scu->PINMUX_CPLD_TCK, SCU_GPIO_PDN | SCU_CONF_FUNCTION0);
/* Configure SCU Pin Mux as GPIO */
scu_pinmux(SCU_PINMUX_LED1, SCU_GPIO_NOPULL);
scu_pinmux(SCU_PINMUX_LED2, SCU_GPIO_NOPULL);
scu_pinmux(SCU_PINMUX_LED3, SCU_GPIO_NOPULL);
scu_pinmux(scu->PINMUX_LED1, SCU_GPIO_NOPULL);
scu_pinmux(scu->PINMUX_LED2, SCU_GPIO_NOPULL);
scu_pinmux(scu->PINMUX_LED3, SCU_GPIO_NOPULL);
#ifdef RAD1O
scu_pinmux(SCU_PINMUX_LED4, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION4);
scu_pinmux(scu->PINMUX_LED4, SCU_GPIO_NOPULL | SCU_CONF_FUNCTION4);
#endif
/* Configure USB indicators */
#ifdef JAWBREAKER
scu_pinmux(SCU_PINMUX_USB_LED0, SCU_CONF_FUNCTION3);
scu_pinmux(SCU_PINMUX_USB_LED1, SCU_CONF_FUNCTION3);
scu_pinmux(scu->PINMUX_USB_LED0, SCU_CONF_FUNCTION3);
scu_pinmux(scu->PINMUX_USB_LED1, SCU_CONF_FUNCTION3);
#endif
gpio_output(&gpio_led[0]);
@@ -905,11 +917,11 @@ void pin_setup(void) {
if (detected_platform() == BOARD_ID_HACKRF1_R9) {
#ifdef HACKRF_ONE
gpio_output(&gpio_h1r9_1v8_enable);
scu_pinmux(SCU_H1R9_EN1V8, SCU_GPIO_FAST | SCU_CONF_FUNCTION0);
scu_pinmux(scu->H1R9_EN1V8, SCU_GPIO_FAST | SCU_CONF_FUNCTION0);
#endif
} else {
gpio_output(&gpio_1v8_enable);
scu_pinmux(SCU_PINMUX_EN1V8, SCU_GPIO_FAST | SCU_CONF_FUNCTION0);
scu_pinmux(scu->PINMUX_EN1V8, SCU_GPIO_FAST | SCU_CONF_FUNCTION0);
}
#ifdef HACKRF_ONE
@@ -935,8 +947,8 @@ void pin_setup(void) {
scu_pinmux(CLK0, SCU_CLK_IN | SCU_CONF_FUNCTION7);
scu_pinmux(CLK2, SCU_CLK_IN | SCU_CONF_FUNCTION7);
scu_pinmux(SCU_PINMUX_GPIO3_10, SCU_GPIO_PDN | SCU_CONF_FUNCTION0);
scu_pinmux(SCU_PINMUX_GPIO3_11, SCU_GPIO_PDN | SCU_CONF_FUNCTION0);
scu_pinmux(scu->PINMUX_GPIO3_10, SCU_GPIO_PDN | SCU_CONF_FUNCTION0);
scu_pinmux(scu->PINMUX_GPIO3_11, SCU_GPIO_PDN | SCU_CONF_FUNCTION0);
#endif
@@ -956,7 +968,7 @@ void pin_setup(void) {
rf_path_pin_setup(&rf_path);
/* Configure external clock in */
scu_pinmux(SCU_PINMUX_GP_CLKIN, SCU_CLK_IN | SCU_CONF_FUNCTION1);
scu_pinmux(scu->PINMUX_GP_CLKIN, SCU_CLK_IN | SCU_CONF_FUNCTION1);
sgpio_configure_pin_functions(&sgpio_config);
}
+2 -1
View File
@@ -22,6 +22,7 @@
#include "scsi.h"
#include "diskio.h"
#include "gpio_lpc.h"
#include <libopencm3/lpc43xx/scu.h>
#include <libopencm3/lpc43xx/rgu.h>
#include <libopencm3/lpc43xx/wwdt.h>
@@ -286,7 +287,7 @@ void scsi_command(msd_cbw_t* msd_cbw_data) {
case SCSI_CMD_START_STOP_UNIT:
SCU_SFSP2_8 = (SCU_SFSP2_8 & ~(7)) | 4;
struct gpio_t dfu = GPIO(5, 7);
struct gpio dfu = GPIO(5, 7);
gpio_output(&dfu);
gpio_clear(&dfu);

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