Compare commits

...

23 Commits

Author SHA1 Message Date
gullradriel 95eafeb812 fix clang format workflow, update hackrf submodule, fix subghzd compilation warning, remove flashsize.h (#2992)
* trying to fix clang format workflow
* try without docker repo, classic apt install
* find what installed clang format 18 version is
* removed auto generated flashsize
* comment on flashsize.h
* modified to use repo owned clang-format binaries
* code format for windows hosts
* add clang-format binaries for linux x86_64/arm64, macos-arm64, windows x86_64
* add helper script to download specific llvm clang-format version
* add helper to download missing libraries (use docker)
* use custom clang-format
* fix ui_subghzd.cpp:85:29: warning: narrowing conversion of 'this->ui::SubGhzDRecentEntryDetailView::cnt' from 'uint32_t' {aka 'long unsigned int'} to 'uint16_t' {aka 'short unsigned int'} [-Wnarrowing]
* remove auto generated file
* Update tools/clang-format.sh
* removed fallback
* updated hackrf submodule
2026-02-15 21:29:26 +00:00
gullradriel 94d46036f8 up to latest (#2984) 2026-02-12 12:00:22 +00:00
Totoo 68000f0b94 fix compile (#2983) 2026-02-12 12:41:12 +01:00
lifegame1lu111 eff68693ad Add support for decrypting and saving KeeLoq signals for SubGhzD (#2982) 2026-02-12 10:41:56 +01:00
jLynx 2f468fd37c Add Multi-Device Build Support to Release Workflows (#2978) 2026-02-11 10:44:07 +01:00
stafur 39424632bb HackRF Pro (praline) arch-port initial PR (#2958)
* Initial commit and pr for HackRF Pro (praline) arch-port to mayhem-firmware. Please see https://github.com/portapack-mayhem/mayhem-firmware/issues/2957. Added flash specifics for -DBOARD=PRALINE. This firmware only builds with toolchain v9.2.1 if hackrf codebase has -B arm in firmware/hackrf_usb/CMakeLists.txt.

* Updated CMakeLists.txt per coordination with @HtoToo. For -DBOARD=PRALINE FLASH_MB_SIZE and FLASH_MB_LIMIT_SIZE are now 4. Removed praline specific variable for FLASH limits.

* Updated chibios-portapack's board.cpp to support initialization of the HachRF-Pro (praline) FPGA. Added append_fpga_bitstream.py tool to ensure that praline_fgpa.bin bitstream can be appended to -DBOARD=PRALINE produced firmware. In order to ensure successful execution of append_fpga_bitstream.py to append the fpga bitstream we should expect that the bistsream will be located at 0x180000 in flash. This requires that FLASH_MB_LIMIT_SIZE must be 1.5, and FLASH_BYTES_LIMIT_SIZE must be 1535 * 1024. If we want to allow more or less space for the base firmware image sans the fpga bitstream the location of the bistream must be moved to a location other than 0x180000.

* Updated location of praline_fpga.bin bitstream to 0x380000 to allow more room for firmware. Firmware now has 3.5MB, or 2MB more available than before as coordinated with @HTotoo.

* Expanded #ifndef PRALINE to include og and r9 gpio and pin setup as coordinated with @HTotoo.

* Added note for PRALINE FLASH_MB_LIMIT_SIZE and FLASH_BYTES_LIMIT_SIZE to explain why we are using the 3.5 and 3584 values respectively as coordinated with @HTotoo.

* Next round of modifications derived heavily, if not entirely  from work done by @banandana at https://github.com/Banandana/mayhem-firmware. This commit should power on the HackRF Pro (praline) display, power on the fpga, and enable gpio, and provide debug utilties. There is still a lot of work to be done to fully enable the new praline board with this build and firmware architectural porting effort. However, hackrf-one boards do not seem to be adversely impacted by the #ifdef PRALINE statements, and CMakeLists updates, as far as I have been able to test.

* Ran format-code.sh. Updates for this commit are only due to formatting. Tested builds and they seem to work as exptected.

* Addressed fixes in firmware/application and firmware/baseband. Stream now flows to capture and looking glass. Issues were related to thread management. Issues were originally addressed by @banandana.

* Ran format-code.sh to allow for consistency with autoamted clang checks.

* Update hackrf ref repo to mayhem-portapack-hackrf next from https://github.com/portapack-mayhem/hackrf

* Addressed format edits necessary to pass clang-format check.

* Starting addressing Si5351 Clocks for radio sampling. These updates correctly set the Si5351 clock at start up. There appears to be an issue during runtime when testing with RX Test Init, Capture and Looking glass.

* Updated clock_manager.cpp to restore correct function introduced by @banandana when testing with Rx Test Init.

* Switched to using decimation for setting the sample rate without changing the Si5351 clock. This assumes that for the praline board Si5351 CLK0 runs at fixed 8 MHz (constant) and the FPGA decimates to get the desired sample rate. For example, for a 1 MHz sample rate -> Si5351 outputs 8 MHz, FPGA decimates by 8. There is still more work needed here, and potential verification that this is the correct way to operate with this new archteitecture.

* After deliberating on hackrf_usb hackrf_core.c and radio.c, and reviewing firmware/application/hw/si5351.cpp the original approach of using the aproach detailed in hackrf_core.c sample_rate_frac_set() lines 580-582, via the implementation in firmware/application/hw/si5351.cpp seems like the best place to continue testing efforts.

* Tested at ~2.4GHz (2.3 - 2.5) with lookgin glass and was able to receive signals. Added a Signal Path debug app to test gains, and readio mode (receive/transmit).

* Added two debug apps for the RFFC507x. Status View and Tuning View. This helped debug some of the potential issues with tuning.

* update submodule

* format code

* Small touch up merging latest next and ensuring build for HackRF One.

* Reverted edits to re: firmware/baseband/sd_over_usb/scsi.c and firmware/application/portapack.cpp. Source now builds, had to pull latest hackrf submodule.

* Skipped detect hardware for praline board to avoid backscreen in HackRF Pro praline board.

---------

Co-authored-by: gullradriel <gullradriel@users.noreply.github.com>
2026-02-11 09:15:11 +01:00
E.T. cd30022b61 Do hardware detection on init for shell info (#2975)
and reset gpio state afterward
2026-02-09 21:49:16 +01:00
gullradriel be872003ec Update hackrf submodule (#2973)
* update submodule
* fix warning missing delay declaration
* update: fix get board messing up radio/waterfalls
2026-02-09 20:25:40 +00:00
gullradriel 9e7758718c update submodule (#2971) 2026-02-08 20:44:14 +01:00
E.T. 89b878d3bb Better hackrf board detection for the serial info command (#2967) 2026-02-07 15:45:26 +01:00
gullradriel 56d965f3ae update submodule to latest (#2968) 2026-02-06 19:55:53 +01:00
Totoo fe9f0c228f SubCar fm mode (#2965) 2026-02-06 17:20:14 +01:00
Totoo 6562e596e8 OSM change detection 2026-02-06 15:07:07 +01:00
Totoo c27192bdbb Flipper fsk tx support (#2964) 2026-02-06 09:48:20 +01:00
gullradriel 927e3b11e7 Morse rx cleanings (#2962)
* fix ui overlap, align with log box
* bring back enum inside the class as a simple enum
* correctly restore saved setting whatever the modulation was at exit
* set squelch / field_squelch / receiver model in one go, add audio/receiver model stop and start
2026-02-04 14:01:29 +01:00
Pezsma a44a00acf0 Morse rx further development (#2959)
* filters OK, radio configurations set

* all modes are working, noise still needs work, especially in FM. A baseband enum is also needed

* audio and decoding fixed, clipping and the baseband enum are still missing
2026-02-03 22:25:52 +01:00
gullradriel 6739b43914 disable select key repeat in Mic TX (#2956) 2026-02-01 19:44:56 +01:00
gullradriel b306a0d490 Revert "Update Map view labels to match marine navigation standards (#2951)" (#2955)
This reverts commit c6130c6e8d.
2026-01-31 21:15:12 +01:00
Herbenderbler c6130c6e8d Update Map view labels to match marine navigation standards (#2951)
Replace Alt: with CoG: and Spd: with SoG: in the Map view to better align with standard marine navigation terminology and the AIS Rx screen.

- Alt (Altitude) → CoG (Course over Ground)
- Spd (Speed) → SoG (Speed over Ground)

Rationale: AIS is primarily used for marine navigation where altitude is typically zero (sea level), while Course over Ground is essential navigation information. This change provides consistency with the AIS Rx screen which already displays CoG and SoG.

Modified files:
- firmware/application/ui/ui_geomap.hpp
- firmware/standalone/common/ui/ui_geomap.hpp
2026-01-31 20:53:58 +01:00
Herbenderbler 97f2ca42f1 Fix aviation 8.33kHz step size to reduce frequency drift (#2950)
Update aviation radio step size from 8330 Hz to 8333 Hz in freqman_steps
and freqman_steps_short arrays. This better represents the actual 8⅓ kHz
(25000/3 Hz) aviation channel spacing and significantly reduces frequency
drift during dial tuning.
With this fix, stepping 24 times from 123.000 MHz now correctly reaches
123.200 MHz instead of 123.199 MHz.
2026-01-31 19:35:14 +01:00
Pezsma e2b642ae25 New Morse TX app (#2948)
* morse tx
* global button repeat function improvement
2026-01-30 17:18:13 +01:00
gullradriel 106d9b1207 updated submodule (#2947) 2026-01-30 10:14:08 +01:00
gullradriel c8ae419e0b updated submodule (#2946) 2026-01-30 00:21:36 +01:00
120 changed files with 8474 additions and 391 deletions
+18 -10
View File
@@ -3,7 +3,7 @@ name: Check formatting
on: [pull_request]
jobs:
check_date:
check_format:
runs-on: ubuntu-latest
name: Check formatting
strategy:
@@ -13,12 +13,20 @@ jobs:
- "firmware/application"
- "firmware/baseband"
steps:
- uses: actions/checkout@v2
- name: print latest_commit
run: echo ${{ github.sha }}
- name: clang-format Check
uses: jidicula/clang-format-action@v4.11.0
with:
clang-format-version: '18'
check-path: ${{ matrix.path }}
fallback-style: Chromium
- uses: actions/checkout@v4
- name: clang-format check (repo pinned)
run: |
set -euo pipefail
CF="./tools/clang-format.sh"
chmod +x "$CF" || true
"$CF" --version
ROOT="${{ matrix.path }}"
find "$ROOT" -type f \( \
-name '*.c' -o -name '*.cpp' -o \
-name '*.h' -o -name '*.hpp' \
\) -print0 \
| xargs -0 -r "$CF" --dry-run --Werror --style=file
+150 -30
View File
@@ -3,7 +3,7 @@ name: Nightly Release
on:
schedule:
- cron: "0 0 * * *"
workflow_dispatch:
jobs:
@@ -21,27 +21,36 @@ jobs:
id: should_run
continue-on-error: true
run: test -z $(git rev-list --after="24 hours" ${{ github.sha }}) && echo "should_run=false" >> $GITHUB_OUTPUT
build:
needs: check_date
if: ${{ needs.check_date.outputs.should_run != 'false' }}
runs-on: ubuntu-latest
name: build (${{ matrix.device_name }})
strategy:
fail-fast: false
matrix:
include:
- device: default
device_name: HackRF
cmake_args: ""
artifact_suffix: "_hackrf"
- device: portarf
device_name: PortaRF
cmake_args: "-DFLASH_MB_SIZE=2 -DFLASH_MB_LIMIT_SIZE=2"
artifact_suffix: "_portarf"
- device: hpro
device_name: HackRF Pro
cmake_args: "-DBOARD=PRALINE"
artifact_suffix: "_hpro"
steps:
- name: Get current date
id: date
run: echo "date=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT
- name: Get version date
id: version_date
run: echo "date=n_$(date +'%y%m%d')" >> $GITHUB_OUTPUT
- name: Checkout
- name: Checkout
uses: actions/checkout@master
with:
fetch-depth: 0
#ref: next
# The branch, tag or SHA to checkout. When checking out the repository that
# triggered a workflow, this defaults to the reference or SHA for that event.
# Otherwise, uses the default branch.
# https://github.com/actions/checkout
# So scheduled runs will use the default branch (next) but its now possible to trigger a workflow from another branch
submodules: true
- name: Git Sumbodule Update
run: |
@@ -51,10 +60,10 @@ 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
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 }}_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 ..
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 ..
- name: Download world map
run: |
wget https://github.com/portapack-mayhem/mayhem-firmware/releases/download/world_map/world_map.zip
@@ -69,7 +78,47 @@ jobs:
zip -j firmware.zip build/firmware/portapack-mayhem-firmware.bin && cd flashing && zip -r ../firmware.zip *
- name: Create SD Card ZIP
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 }}_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.zip . && cd ..
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.zip . && cd ..
- name: Upload firmware zip artifact
uses: actions/upload-artifact@v4
with:
name: firmware-${{ matrix.device }}
path: ./firmware.zip
- name: Upload SD card artifact
uses: actions/upload-artifact@v4
with:
name: sdcard-${{ matrix.device }}
path: ./sdcard.zip
- name: Upload SD card no-map artifact
uses: actions/upload-artifact@v4
with:
name: sdcard-no-map-${{ matrix.device }}
path: ./sdcard-no-map.zip
- name: Upload OCI tar artifact
uses: actions/upload-artifact@v4
with:
name: oci-tar-${{ matrix.device }}
path: build/firmware/portapack-mayhem_OCI.ppfw.tar
release:
needs: build
runs-on: ubuntu-latest
steps:
- name: Get current date
id: date
run: echo "date=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT
- name: Get version date
id: version_date
run: echo "date=n_$(date +'%y%m%d')" >> $GITHUB_OUTPUT
- name: Checkout
uses: actions/checkout@master
with:
fetch-depth: 0
submodules: true
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Create changelog
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -96,43 +145,114 @@ jobs:
${{ steps.changelog.outputs.content }}
draft: false
prerelease: true
- name: Upload Firmware TAR Asset
id: upload-firmware-tar-asset
# Default device assets
- name: Upload Default Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: build/firmware/portapack-mayhem_OCI.ppfw.tar
asset_name: mayhem_nightly_${{ steps.version_date.outputs.date }}_OCI.ppfw.tar
asset_path: artifacts/oci-tar-default/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_hackrf_mayhem_nightly_${{ steps.version_date.outputs.date }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload Firmware Asset
id: upload-firmware-asset
- name: Upload Default Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./firmware.zip
asset_name: mayhem_nightly_${{ steps.version_date.outputs.date }}_FIRMWARE.zip
asset_path: artifacts/firmware-default/firmware.zip
asset_name: FIRMWARE_hackrf_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload SD Card Assets
id: upload-sd-card-asset
- name: Upload Default SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./sdcard.zip
asset_name: mayhem_nightly_${{ steps.version_date.outputs.date }}_COPY_TO_SDCARD.zip
asset_path: artifacts/sdcard-default/sdcard.zip
asset_name: COPY_TO_SDCARD_hackrf_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload SD Card Assets - No Map
id: upload-sd-card-asset-no-map
- name: Upload Default SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./sdcard-no-map.zip
asset_name: mayhem_nightly_${{ steps.version_date.outputs.date }}_COPY_TO_SDCARD-no-world-map.zip
asset_path: artifacts/sdcard-no-map-default/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_hackrf_mayhem_nightly_${{ steps.version_date.outputs.date }}-no-world-map.zip
asset_content_type: application/zip
# PortaRF device assets
- name: Upload PortaRF Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-portarf/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_portarf_mayhem_nightly_${{ steps.version_date.outputs.date }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload PortaRF Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-portarf/firmware.zip
asset_name: FIRMWARE_portarf_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload PortaRF SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-portarf/sdcard.zip
asset_name: COPY_TO_SDCARD_portarf_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload PortaRF SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-portarf/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_portarf_mayhem_nightly_${{ steps.version_date.outputs.date }}-no-world-map.zip
asset_content_type: application/zip
# HPro device assets
- name: Upload HPro Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-hpro/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_hpro_mayhem_nightly_${{ steps.version_date.outputs.date }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload HPro Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-hpro/firmware.zip
asset_name: FIRMWARE_hpro_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload HPro SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-hpro/sdcard.zip
asset_name: COPY_TO_SDCARD_hpro_mayhem_nightly_${{ steps.version_date.outputs.date }}.zip
asset_content_type: application/zip
- name: Upload HPro SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-hpro/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_hpro_mayhem_nightly_${{ steps.version_date.outputs.date }}-no-world-map.zip
asset_content_type: application/zip
+153 -32
View File
@@ -1,25 +1,36 @@
name: Stable Release
on:
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
name: build (${{ matrix.device_name }})
strategy:
fail-fast: false
matrix:
include:
- device: default
device_name: HackRF
cmake_args: ""
artifact_suffix: "_hackrf"
- device: portarf
device_name: PortaRF
cmake_args: "-DFLASH_MB_SIZE=2 -DFLASH_MB_LIMIT_SIZE=2"
artifact_suffix: "_portarf"
- device: hpro
device_name: HackRF Pro
cmake_args: "-DBOARD=PRALINE"
artifact_suffix: "_hpro"
steps:
- name: Get current date
id: date
run: echo "date=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT
- name: Checkout
- name: Checkout
uses: actions/checkout@master
with:
fetch-depth: 0
#ref: next
# The branch, tag or SHA to checkout. When checking out the repository that
# triggered a workflow, this defaults to the reference or SHA for that event.
# Otherwise, uses the default branch.
# https://github.com/actions/checkout
# So scheduled runs will use the default branch (next) but its now possible to trigger a workflow from another branch
submodules: true
- name: Git Sumbodule Update
run: |
@@ -27,18 +38,15 @@ jobs:
- name: Get version
id: version
run: echo "version=$(cat .github/workflows/version.txt)" >> $GITHUB_OUTPUT
- name: Get past version
id: past_version
run: echo "past_version=$(cat .github/workflows/past_version.txt)" >> $GITHUB_OUTPUT
- name: Build the Docker image
run: docker build -t portapack-dev -f dockerfile-nogit . --tag my-image-name:$(date +%s)
- 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
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 }}_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 ..
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 ..
- name: Download world map
run: |
wget https://github.com/portapack-mayhem/mayhem-firmware/releases/download/world_map/world_map.zip
@@ -53,7 +61,50 @@ jobs:
zip -j firmware.zip build/firmware/portapack-mayhem-firmware.bin && cd flashing && zip -r ../firmware.zip *
- name: Create SD Card ZIP
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 }}_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.zip . && cd ..
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.zip . && cd ..
- name: Upload firmware zip artifact
uses: actions/upload-artifact@v4
with:
name: firmware-${{ matrix.device }}
path: ./firmware.zip
- name: Upload SD card artifact
uses: actions/upload-artifact@v4
with:
name: sdcard-${{ matrix.device }}
path: ./sdcard.zip
- name: Upload SD card no-map artifact
uses: actions/upload-artifact@v4
with:
name: sdcard-no-map-${{ matrix.device }}
path: ./sdcard-no-map.zip
- name: Upload OCI tar artifact
uses: actions/upload-artifact@v4
with:
name: oci-tar-${{ matrix.device }}
path: build/firmware/portapack-mayhem_OCI.ppfw.tar
release:
needs: build
runs-on: ubuntu-latest
steps:
- name: Get current date
id: date
run: echo "date=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT
- name: Checkout
uses: actions/checkout@master
with:
fetch-depth: 0
submodules: true
- name: Get version
id: version
run: echo "version=$(cat .github/workflows/version.txt)" >> $GITHUB_OUTPUT
- name: Get past version
id: past_version
run: echo "past_version=$(cat .github/workflows/past_version.txt)" >> $GITHUB_OUTPUT
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Create changelog
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -78,7 +129,7 @@ jobs:
## Release notes
### Revision (${{ steps.version.outputs.version }}):
${{ steps.changelog.outputs.content }}
**Full Changelog**: https://github.com/portapack-mayhem/mayhem-firmware/compare/${{ steps.past_version.outputs.past_version }}...${{ steps.version.outputs.version }}
## Installation
@@ -90,44 +141,114 @@ jobs:
For certain functionality, like external apps, the world map, GPS simulator, and others you need to uncompress (using [7-zip](https://www.7-zip.org/download.html)) the files from `mayhem_vX.Y.Z_COPY_TO_SDCARD.zip` to a FAT32 formatted MicroSD card.
draft: true
prerelease: false
- name: Upload Firmware TAR Asset
id: upload-firmware-tar-asset
# Default device assets
- name: Upload Default Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: build/firmware/portapack-mayhem_OCI.ppfw.tar
asset_name: mayhem_${{ steps.version.outputs.version }}_OCI.ppfw.tar
asset_path: artifacts/oci-tar-default/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_hackrf_mayhem_${{ steps.version.outputs.version }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload Firmware Asset
id: upload-firmware-asset
- name: Upload Default Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./firmware.zip
asset_name: mayhem_${{ steps.version.outputs.version }}_FIRMWARE.zip
asset_path: artifacts/firmware-default/firmware.zip
asset_name: FIRMWARE_hackrf_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload SD Card Assets
id: upload-sd-card-asset
- name: Upload Default SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./sdcard.zip
asset_name: mayhem_${{ steps.version.outputs.version }}_COPY_TO_SDCARD.zip
asset_path: artifacts/sdcard-default/sdcard.zip
asset_name: COPY_TO_SDCARD_hackrf_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload SD Card Assets - No Map
id: upload-sd-card-asset-no-map
- name: Upload Default SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./sdcard-no-map.zip
asset_name: mayhem_${{ steps.version.outputs.version }}_COPY_TO_SDCARD-no-world-map.zip
asset_path: artifacts/sdcard-no-map-default/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_hackrf_mayhem_${{ steps.version.outputs.version }}-no-world-map.zip
asset_content_type: application/zip
# PortaRF device assets
- name: Upload PortaRF Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-portarf/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_portarf_mayhem_${{ steps.version.outputs.version }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload PortaRF Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-portarf/firmware.zip
asset_name: FIRMWARE_portarf_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload PortaRF SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-portarf/sdcard.zip
asset_name: COPY_TO_SDCARD_portarf_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload PortaRF SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-portarf/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_portarf_mayhem_${{ steps.version.outputs.version }}-no-world-map.zip
asset_content_type: application/zip
# HPro device assets
- name: Upload HPro Firmware TAR Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/oci-tar-hpro/portapack-mayhem_OCI.ppfw.tar
asset_name: OCI_hpro_mayhem_${{ steps.version.outputs.version }}.ppfw.tar
asset_content_type: application/x-tar
- name: Upload HPro Firmware Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/firmware-hpro/firmware.zip
asset_name: FIRMWARE_hpro_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload HPro SD Card Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-hpro/sdcard.zip
asset_name: COPY_TO_SDCARD_hpro_mayhem_${{ steps.version.outputs.version }}.zip
asset_content_type: application/zip
- name: Upload HPro SD Card Asset - No Map
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: artifacts/sdcard-no-map-hpro/sdcard-no-map.zip
asset_name: COPY_TO_SDCARD_hpro_mayhem_${{ steps.version.outputs.version }}-no-world-map.zip
asset_content_type: application/zip
+2 -1
View File
@@ -83,4 +83,5 @@ venv/
# generated bitmap arr file
# TODO: generate bitmap during build, since we use python during build anyway, lemme know if this is a bad idea @zxkmm
/firmware/tools/bitmap.hpp
firmware/flashsize.h
# flashsize is generated by cmake
/firmware/flashsize.h
+16 -3
View File
@@ -30,12 +30,20 @@ add_compile_options(-fdiagnostics-color=always)
#Flash size related options
#This is the size of the flash memory we SUPPORT. Don't worry, the internl flash app has harder limits based on device type.
if(NOT DEFINED FLASH_MB_SIZE)
set(FLASH_MB_SIZE 2) # Default to 2MB if not provided. For PortaRf this should be 2MB passed to cmake with -DFLASH_MB_SIZE=2
if(BOARD STREQUAL "PRALINE")
set(FLASH_MB_SIZE 4) # PRALINE has 4MB flash
else()
set(FLASH_MB_SIZE 2) # Default to 2MB if not provided. For PortaRf this should be 2MB passed to cmake with -DFLASH_MB_SIZE=2
endif()
endif()
message("Configuring for FLASH_MB_SIZE=${FLASH_MB_SIZE}MB")
#This is the flash memory size we build. This can be less, so the FW size will be less, so can be flashed with older utils.
if(NOT DEFINED FLASH_MB_LIMIT_SIZE)
set(FLASH_MB_LIMIT_SIZE 1) #TODO: should be ${FLASH_MB_SIZE} remove once we got a stable build for all devices we support with bigger than 1 mb flash
if(BOARD STREQUAL "PRALINE")
set(FLASH_MB_LIMIT_SIZE 3.5) #PRALINE 4 MB = 3.5 firmware + 0.5 MB fpga bitstream.
else()
set(FLASH_MB_LIMIT_SIZE 1) #TODO: should be ${FLASH_MB_SIZE} remove once we got a stable build for all devices we support with bigger than 1 mb flash
endif()
endif()
message("Configuring for FLASH_MB_LIMIT_SIZE=${FLASH_MB_LIMIT_SIZE}MB")
@@ -44,7 +52,12 @@ if(FLASH_MB_SIZE LESS FLASH_MB_LIMIT_SIZE)
endif()
math(EXPR FLASH_BYTES_SIZE "${FLASH_MB_SIZE} * 1024 * 1024")
math(EXPR FLASH_BYTES_LIMIT_SIZE "${FLASH_MB_LIMIT_SIZE} * 1024 * 1024")
if(BOARD STREQUAL "PRALINE")
math(EXPR FLASH_BYTES_LIMIT_SIZE "3584 * 1024") #4 MB = 3.5 firmware + 0.5 MB fpga bitstream.
else()
math(EXPR FLASH_BYTES_LIMIT_SIZE "${FLASH_MB_LIMIT_SIZE} * 1024 * 1024")
endif()
#generate h files
configure_file(flashsize.h.in ${CMAKE_CURRENT_SOURCE_DIR}/firmware/flashsize.h)
+18
View File
@@ -67,6 +67,24 @@ add_custom_target(
DEPENDS ${FIRMWARE_FILENAME} ${HACKRF_FIRMWARE_DFU_FILENAME} ${HACKRF_FIRMWARE_FILENAME}
)
# PRALINE: Append FPGA bitstream to firmware at offset 0x180000
# The base firmware is 1MB, FPGA goes at 1MB offset, final size is 2MB
if(BOARD STREQUAL "PRALINE")
math(EXPR PRALINE_FINAL_SIZE "4 * 1024 * 1024")
set(PRALINE_FPGA_BIN ${CMAKE_CURRENT_SOURCE_DIR}/../hackrf/firmware/fpga/build/praline_fpga.bin)
set(APPEND_FPGA_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/tools/append_fpga_bitstream.py)
add_custom_command(
TARGET firmware POST_BUILD
COMMAND ${CMAKE_COMMAND} -E echo "Appending PRALINE FPGA bitstream to firmware..."
COMMAND python3 ${APPEND_FPGA_SCRIPT} ${FIRMWARE_FILENAME} ${PRALINE_FPGA_BIN} ${FIRMWARE_FILENAME}.tmp ${PRALINE_FINAL_SIZE}
COMMAND ${CMAKE_COMMAND} -E rename ${FIRMWARE_FILENAME}.tmp ${FIRMWARE_FILENAME}
COMMAND ${CMAKE_COMMAND} -E echo "PRALINE firmware with FPGA bitstream created:"
COMMAND ls -la ${FIRMWARE_FILENAME}
COMMENT "Appending PRALINE FPGA bitstream"
VERBATIM
)
endif()
if(${GCC_VERSION_MISMATCH})
set(COMPILER_MISMATCH_MESSAGE "WARNING: Compiler version mismatch, please use the official compiler version ${EXPECTED_GCC_VERSION} when sharing builds! Current compiler version: ${CMAKE_CXX_COMPILER_VERSION}")
message(${COMPILER_MISMATCH_MESSAGE})
+23 -1
View File
@@ -86,6 +86,9 @@ set(CPLD_20150901_DATA_CPP ${CMAKE_CURRENT_BINARY_DIR}/portapack_cpld_20150901_d
set(CPLD_20170522_SVF_PATH ${HARDWARE_PATH}/portapack_h1/cpld/20170522/output_files/portapack_h1_cpld.svf)
set(CPLD_20170522_DATA_CPP ${CMAKE_CURRENT_BINARY_DIR}/portapack_cpld_20170522_data.cpp)
set(CPLD_H4M_SVF_PATH ${HARDWARE_PATH}/portapack_h4m/CPLD/AG256SL100/output_files/portapack_h4m_cpld.svf)
set(CPLD_H4M_DATA_CPP ${CMAKE_CURRENT_BINARY_DIR}/portapack_cpld_h4m_data.cpp)
set(HACKRF_CPLD_DATA_HPP ${CMAKE_CURRENT_BINARY_DIR}/hackrf_cpld_data.hpp)
set(HACKRF_CPLD_DATA_CPP ${CMAKE_CURRENT_BINARY_DIR}/hackrf_cpld_data.cpp)
@@ -118,11 +121,16 @@ set(CSRC
usb_serial_endpoints.c
usb_serial_device_to_host.c
i2c_device_to_host.c
hackrf_core_mini.c
${HACKRF_PATH}/firmware/common/adc.c
${HACKRF_PATH}/firmware/common/usb.c
${HACKRF_PATH}/firmware/common/usb_queue.c
${HACKRF_PATH}/firmware/hackrf_usb/usb_device.c
${HACKRF_PATH}/firmware/common/usb_request.c
${HACKRF_PATH}/firmware/common/usb_standard_request.c
${HACKRF_PATH}/firmware/libopencm3/lib/lpc43xx/scu.c
${HACKRF_PATH}/firmware/common/gpio_lpc.c
${HACKRF_PATH}/firmware/common/platform_detect.c
${CHIBIOS}/os/various/chprintf.c
)
@@ -205,6 +213,8 @@ set(CPPSRC
irq_controls.cpp
irq_lcd_frame.cpp
irq_rtc.cpp
keeloq_file.cpp
keeloq_keystore.cpp
log_file.cpp
metadata_file.cpp
flipper_subfile.cpp
@@ -237,6 +247,7 @@ set(CPPSRC
hw/encoder.cpp
hw/max2837.cpp
hw/max2839.cpp
hw/max2831.cpp
hw/max5864.cpp
hw/rffc507x.cpp
hw/rffc507x_spi.cpp
@@ -317,6 +328,7 @@ set(CPPSRC
config_mode.cpp
${CPLD_20150901_DATA_CPP}
${CPLD_20170522_DATA_CPP}
${CPLD_H4M_DATA_CPP}
${HACKRF_CPLD_DATA_CPP}
ui_external_items_menu_loader.cpp
view_factory_base.cpp
@@ -402,7 +414,11 @@ set(CPPWARN "-Wall -Wextra -Wno-psabi")
# List all default C defines here, like -D_DEBUG=1
# TODO: Switch -DCRT0_INIT_DATA depending on load from RAM or SPIFI?
# NOTE: _RANDOM_TCC to kill a GCC 4.9.3 error with std::max argument types
set(DDEFS "-DLPC43XX -DLPC43XX_M0 -D__NEWLIB__ -DHACKRF_ONE -DTOOLCHAIN_GCC -DTOOLCHAIN_GCC_ARM -D_RANDOM_TCC=0 -D'VERSION_STRING=\"${VERSION}\"' -DVERSION_MD5=${VERSION_MD5} -D'GCC_VERSION_MISMATCH=${GCC_VERSION_MISMATCH}'")
# Use BOARD variable if set, otherwise default to HACKRF_ONE
if(NOT DEFINED BOARD)
set(BOARD "HACKRF_ONE")
endif()
set(DDEFS "-DLPC43XX -DLPC43XX_M0 -D__NEWLIB__ -D${BOARD} -DTOOLCHAIN_GCC -DTOOLCHAIN_GCC_ARM -D_RANDOM_TCC=0 -D'VERSION_STRING=\"${VERSION}\"' -DVERSION_MD5=${VERSION_MD5} -D'GCC_VERSION_MISMATCH=${GCC_VERSION_MISMATCH}'")
# List all default ASM defines here, like -D_DEBUG=1
set(DADEFS)
@@ -460,6 +476,12 @@ add_custom_command(
DEPENDS ${EXTRACT_CPLD_DATA} ${CPLD_20170522_SVF_PATH}
)
add_custom_command(
OUTPUT ${CPLD_H4M_DATA_CPP}
COMMAND ${EXTRACT_CPLD_DATA} ${CPLD_H4M_SVF_PATH} rev_h4m >${CPLD_H4M_DATA_CPP}
DEPENDS ${EXTRACT_CPLD_DATA} ${CPLD_H4M_SVF_PATH}
)
add_custom_command(
OUTPUT ${HACKRF_CPLD_DATA_CPP}
COMMAND ${HACKRF_CPLD_TOOL} --xsvf ${HACKRF_CPLD_XSVF_PATH} --portapack-data ${HACKRF_CPLD_DATA_CPP}
File diff suppressed because it is too large Load Diff
+457
View File
@@ -93,6 +93,10 @@ typedef enum {
CT_SI5351,
CT_AUDIO,
CT_MAX17055,
#ifdef PRALINE
CT_FPGA,
#endif
CT_SGPIO,
} chip_type_t;
struct RegistersWidgetConfig {
@@ -373,6 +377,459 @@ private:
};
};*/
/* Radio Signal Path Diagnostics View
* Shows status of each component in the RX/TX signal chain:
* Antenna -> RF Path -> RFFC5072 -> MAX283x -> MAX5864 -> FPGA -> SGPIO -> MCU
*/
class RadioDiagnosticsView : public View {
public:
RadioDiagnosticsView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Radio Diag"; };
private:
NavigationView& nav_;
void update_status();
Text text_title{{0, 0, 240, 16}, "=== Signal Path Status ==="};
Text text_lbl_rffc{{0, 20, 140, 16}, "RFFC5072 (1st IF):"};
Text text_rffc_status{{144, 20, 96, 16}, "---"};
Text text_lbl_max{{0, 36, 140, 16}, "MAX283x (2nd IF):"};
Text text_max_status{{144, 36, 96, 16}, "---"};
Text text_lbl_adc{{0, 52, 140, 16}, "MAX5864 (ADC):"};
Text text_adc_status{{144, 52, 96, 16}, "---"};
Text text_lbl_fpga{{0, 68, 140, 16}, "FPGA/CPLD:"};
Text text_fpga_status{{144, 68, 96, 16}, "---"};
Text text_lbl_sgpio{{0, 84, 140, 16}, "SGPIO:"};
Text text_sgpio_status{{144, 84, 96, 16}, "---"};
Text text_lbl_clock{{0, 100, 140, 16}, "Si5351 Clocks:"};
Text text_clock_status{{144, 100, 96, 16}, "---"};
Text text_regs_title{{0, 124, 240, 16}, "=== Key Registers ==="};
Text text_lbl_rffc_reg{{0, 144, 80, 16}, "RFFC R0:"};
Text text_rffc_reg{{80, 144, 160, 16}, "---"};
Text text_lbl_max_reg{{0, 160, 80, 16}, "MAX R0:"};
Text text_max_reg{{80, 160, 160, 16}, "---"};
Text text_lbl_fpga_reg{{0, 176, 80, 16}, "FPGA:"};
Text text_fpga_reg{{80, 176, 160, 16}, "---"};
Text text_lbl_sgpio_reg{{0, 192, 80, 16}, "SGPIO:"};
Text text_sgpio_reg{{80, 192, 160, 16}, "---"};
Text text_test_result{{0, 220, 240, 32}, ""};
Button button_refresh{
{8, 280, 72, 24},
"Refresh"};
Button button_done{
{168, 280, 64, 24},
"Done"};
};
/* BasebandStatusView ***************************************************/
class BasebandStatusView : public View {
public:
BasebandStatusView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Baseband Status"; };
private:
NavigationView& nav_;
void update();
Text text_title{{0, 0, 240, 16}, "=== Baseband Counters ==="};
Text text_lbl_marker{{0, 20, 140, 16}, "Streaming Marker:"};
Text text_marker{{144, 20, 96, 16}, "---"};
Text text_lbl_loops{{0, 36, 140, 16}, "Baseband Loops:"};
Text text_loops{{144, 36, 96, 16}, "---"};
Text text_lbl_wait{{0, 52, 140, 16}, "DMA Wait Count:"};
Text text_wait{{144, 52, 96, 16}, "---"};
Text text_lbl_xfr{{0, 68, 140, 16}, "DMA Xfr Count:"};
Text text_xfr{{144, 68, 96, 16}, "---"};
Text text_lbl_missed{{0, 84, 140, 16}, "Buffer Missed:"};
Text text_missed{{144, 84, 96, 16}, "---"};
Text text_status_line1{{0, 110, 240, 16}, ""};
Text text_status_line2{{0, 126, 240, 16}, ""};
Text text_status_line3{{0, 142, 240, 16}, ""};
Button button_refresh{
{8, 280, 72, 24},
"Refresh"};
Button button_done{
{168, 280, 64, 24},
"Done"};
MessageHandlerRegistration message_handler_frame_sync{
Message::ID::DisplayFrameSync,
[this](const Message* const) { this->update(); }};
};
/* SGPIOLiveMonitorView ***************************************************/
class SGPIOLiveMonitorView : public View {
public:
SGPIOLiveMonitorView(NavigationView& nav);
void focus() override;
std::string title() const override { return "SGPIO Live"; };
private:
NavigationView& nav_;
void update();
Text text_title{{0, 0, 240, 16}, "=== SGPIO Registers ==="};
Text text_lbl_ctrl{{0, 20, 140, 16}, "CTRL_ENABLE:"};
Text text_ctrl{{144, 20, 96, 16}, "---"};
Text text_lbl_in{{0, 36, 140, 16}, "GPIO_INREG:"};
Text text_in{{144, 36, 96, 16}, "---"};
Text text_lbl_ss{{0, 52, 140, 16}, "REG_SS[0]:"};
Text text_ss{{144, 52, 96, 16}, "---"};
Text text_lbl_status{{0, 68, 140, 16}, "STATUS_1:"};
Text text_status{{144, 68, 96, 16}, "---"};
Text text_lbl_out{{0, 84, 140, 16}, "GPIO_OUTREG:"};
Text text_out{{144, 84, 96, 16}, "---"};
Text text_lbl_oen{{0, 100, 140, 16}, "GPIO_OENREG:"};
Text text_oen{{144, 100, 96, 16}, "---"};
Text text_diag_line1{{0, 126, 240, 16}, ""};
Text text_diag_line2{{0, 142, 240, 16}, ""};
Text text_diag_line3{{0, 158, 240, 16}, ""};
Text text_diag_line4{{0, 174, 240, 16}, ""};
Button button_refresh{
{8, 280, 72, 24},
"Refresh"};
Button button_done{
{168, 280, 64, 24},
"Done"};
MessageHandlerRegistration message_handler_frame_sync{
Message::ID::DisplayFrameSync,
[this](const Message* const) { this->update(); }};
};
/* Radio RX Step-by-Step Test View
* Tests radio hardware directly without M0 baseband involvement.
* Logs each step to help isolate where the signal chain breaks.
*/
class RadioRxTestView : public View {
public:
RadioRxTestView(NavigationView& nav);
void focus() override;
std::string title() const override { return "RX Test"; };
private:
NavigationView& nav_;
bool radio_initialized_{false};
uint32_t test_frequency_{433000000}; // 433 MHz default
void log(const std::string& msg);
void log_registers(const std::string& label);
void run_init_test();
void run_rx_mode_test();
void run_freq_test();
void run_sgpio_test();
void run_full_test();
void run_step_test();
bool check_gpio_changing();
Labels labels{
{{0, 0}, "=== Radio RX Test ===", Theme::getInstance()->fg_yellow->foreground}};
Console console{
{0, 20, 240, 200}};
Button button_init{
{0, 224, 56, 24},
"Init"};
Button button_rx{
{60, 224, 56, 24},
"RX"};
Button button_freq{
{120, 224, 56, 24},
"Freq"};
Button button_sgpio{
{180, 224, 56, 24},
"SGPIO"};
Button button_full{
{0, 252, 56, 24},
"Full"};
Button button_step{
{60, 252, 56, 24},
"Step"};
Button button_done{
{120, 252, 112, 24},
"Done"};
};
/* SGPIO8 Clock Detector View
* Samples SGPIO8 pin to verify external clock is present.
* Shows toggle count and estimated frequency.
*/
class SGPIO8ClockDetectorView : public View {
public:
SGPIO8ClockDetectorView(NavigationView& nav);
void focus() override;
std::string title() const override { return "SGPIO8 Clock"; };
private:
NavigationView& nav_;
Text text_title{{8, 16, 224, 16}, "SGPIO8 Clock Detector"};
Text text_lbl_samples{{8, 48, 160, 16}, "Samples (first 20):"};
Text text_samples{{8, 64, 224, 16}, " "};
Text text_lbl_toggles{{8, 96, 160, 16}, "Toggle count:"};
Text text_toggles{{8, 112, 224, 16}, " "};
Text text_status{{8, 144, 224, 32}, " "};
Button button_sample{{8, 200, 96, 24}, "Sample"};
Button button_done{{128, 200, 96, 24}, "Done"};
void sample_sgpio8();
};
/* Slice Status View
* Shows SGPIO slice status: which slices are enabled vs active,
* counter values, and data capture status.
*/
/* Si5351 Debug View
* Dedicated diagnostic tool for Si5351 clock generator.
* Shows PLL lock status, clock configurations, and allows testing.
*/
class Si5351DebugView : public View {
public:
Si5351DebugView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Si5351 Clocks"; };
private:
NavigationView& nav_;
Text text_title{{8, 16, 200, 16}, "Si5351 Clock Generator"};
Text text_status_label{{8, 40, 80, 16}, "Status Reg:"};
Text text_status_value{{96, 40, 144, 16}, ""};
Text text_pll_a_label{{8, 60, 80, 16}, "PLL A:"};
Text text_pll_a_status{{96, 60, 144, 16}, ""};
Text text_pll_b_label{{8, 80, 80, 16}, "PLL B:"};
Text text_pll_b_status{{96, 80, 144, 16}, ""};
Text text_sys_init_label{{8, 100, 80, 16}, "SYS_INIT:"};
Text text_sys_init_status{{96, 100, 144, 16}, ""};
Text text_xtal_cap_label{{8, 120, 80, 16}, "XTAL Cap:"};
Text text_xtal_cap_value{{96, 120, 144, 16}, ""};
Text text_clk0_label{{8, 150, 72, 16}, "CLK0:"};
Text text_clk0_status{{88, 150, 152, 16}, ""};
Text text_clk0_freq_label{{8, 170, 72, 16}, " Freq:"};
Text text_clk0_freq_value{{88, 170, 152, 16}, ""};
Text text_clk0_div_label{{8, 190, 72, 16}, " Div:"};
Text text_clk0_div_value{{88, 190, 152, 16}, ""};
Text text_clk1_label{{8, 210, 96, 16}, "CLK1 (SCT):"};
Text text_clk1_status{{112, 210, 128, 16}, ""};
Button button_refresh{{8, 240, 72, 24}, "Refresh"};
Button button_reset_pll{{88, 240, 72, 24}, "Reset PLL"};
Button button_done{{168, 240, 64, 24}, "Done"};
void refresh_status();
void reset_pll();
};
#ifdef PRALINE
/* SignalPathStatusView *************************************************/
class SignalPathStatusView : public View {
public:
SignalPathStatusView(NavigationView& nav);
void focus() override;
std::string title() const override { return "Signal Path"; };
private:
NavigationView& nav_;
void refresh_status();
Text text_title{{0, 0, 240, 16}, "=== Signal Path Status ==="};
Text text_lbl_max_enable{{0, 20, 1114, 16}, "MAX2831:"};
Text text_max_enable{{116, 20, 124, 16}, "---"};
Text text_lbl_max_mode{{0, 36, 114, 16}, "RX Mode:"};
Text text_max_mode{{116, 36, 124, 16}, "---"};
Text text_lbl_rf_path{{0, 52, 114, 16}, "RF Path:"};
Text text_rf_path{{116, 52, 124, 16}, "---"};
Text text_lbl_rf_amp{{0, 68, 114, 16}, "RF Amp:"};
Text text_rf_amp{{116, 68, 124, 16}, "---"};
Text text_lbl_lna{{0, 84, 114, 16}, "LNA Gain:"};
Text text_lna{{116, 84, 124, 16}, "---"};
Text text_lbl_vga{{0, 100, 114, 16}, "VGA Gain:"};
Text text_vga{{116, 100, 124, 16}, "---"};
Text text_lbl_fpga_decim{{0, 116, 114, 16}, "FPGA Decim:"};
Text text_fpga_decim{{116, 116, 124, 16}, "---"};
Text text_status{{0, 140, 240, 32}, ""};
Button button_refresh{{8, 280, 72, 24}, "Refresh"};
Button button_done{{168, 280, 64, 24}, "Done"};
};
#endif
#ifdef PRALINE
/* RFFC5072StatusView *************************************************/
class RFFC5072StatusView : public View {
public:
RFFC5072StatusView(NavigationView& nav);
void focus() override;
std::string title() const override { return "RFFC5072 Status"; };
private:
NavigationView& nav_;
void refresh_status();
Text text_title{{0, 0, 240, 16}, "=== RFFC5072 (1st IF) ==="};
Text text_lbl_enabled{{0, 20, 114, 16}, "Status:"};
Text text_enabled{{116, 20, 124, 16}, "---"};
Text text_lbl_freq{{0, 36, 114, 16}, "LO Freq:"};
Text text_freq{{116, 36, 124, 16}, "---"};
Text text_lbl_path{{0, 52, 114, 16}, "Path:"};
Text text_path{{116, 52, 124, 16}, "---"};
Text text_lbl_mixer{{0, 68, 114, 16}, "Mixer:"};
Text text_mixer{{116, 68, 124, 16}, "---"};
Text text_lbl_r0{{0, 92, 114, 16}, "Reg 0:"};
Text text_r0{{116, 92, 124, 16}, "---"};
Text text_lbl_r1{{0, 108, 114, 16}, "Reg 1 (N):"};
Text text_r1{{116, 108, 124, 16}, "---"};
Text text_lbl_r2{{0, 124, 114, 16}, "Reg 2:"};
Text text_r2{{116, 124, 124, 16}, "---"};
Text text_lbl_decode{{0, 148, 240, 16}, "--- Decoded Values ---"};
Text text_lbl_n{{0, 168, 114, 16}, "N divider:"};
Text text_n{{116, 168, 124, 16}, "---"};
Text text_lbl_lodiv{{0, 184, 114, 16}, "LO divider:"};
Text text_lodiv{{116, 184, 124, 16}, "---"};
Text text_lbl_calc{{0, 200, 114, 16}, "Calc freq:"};
Text text_calc{{116, 200, 124, 16}, "---"};
Text text_status{{0, 224, 240, 32}, ""};
Button button_refresh{{8, 280, 72, 24}, "Refresh"};
Button button_done{{168, 280, 64, 24}, "Done"};
};
#ifdef PRALINE
/* RFFCTuningDebugView *************************************************/
class RFFCTuningDebugView : public View {
public:
RFFCTuningDebugView(NavigationView& nav);
void focus() override;
std::string title() const override { return "RFFC Tuning Debug"; };
private:
void refresh();
Text text_title{{0, 0, 240, 16}, "RFFC5072 Tuning Debug"};
Text text_lbl_called{{0, 18, 120, 16}, "Freq Set:"};
Text text_called{{122, 18, 118, 16}, "NO"};
Text text_lbl_req{{0, 38, 120, 16}, "Requested:"};
Text text_req{{122, 38, 118, 16}, "---"};
Text text_lbl_exp_n{{0, 56, 120, 16}, "Expected N:"};
Text text_exp_n{{122, 56, 118, 16}, "---"};
Text text_lbl_act_n{{0, 74, 120, 16}, "Actual N:"};
Text text_act_n{{122, 74, 118, 16}, "---"};
Text text_lbl_exp_div{{0, 92, 120, 16}, "Exp LO/Pres:"};
Text text_exp_div{{122, 92, 118, 16}, "---"};
Text text_lbl_act_div{{0, 110, 120, 16}, "Act LO/Pres:"};
Text text_act_div{{122, 110, 118, 16}, "---"};
Text text_lbl_calc{{0, 128, 120, 16}, "Calc LO freq:"};
Text text_calc{{122, 128, 118, 16}, "---"};
Text text_lbl_calc_lo{{0, 146, 120, 16}, "Calc input:"};
Text text_calc_lo{{122, 146, 118, 16}, "---"};
Text text_lbl_calc_vco{{0, 164, 120, 16}, "In Calc VCO:"};
Text text_calc_vco{{122, 164, 118, 16}, "---"};
Text text_lbl_vco{{0, 182, 120, 16}, "Calc VCO:"};
Text text_vco{{122, 182, 118, 16}, "---"};
Text text_lbl_n_q24{{0, 200, 120, 16}, "N (Q24):"};
Text text_n_q24{{122, 200, 118, 16}, "---"};
Text text_status{{0, 224, 240, 48}, ""};
Button button_refresh{{8, 280, 72, 24}, "Refresh"};
Button button_done{{168, 280, 64, 24}, "Done"};
};
#endif
#endif
class DebugPeripheralsMenuView : public BtnGridView {
public:
DebugPeripheralsMenuView(NavigationView& nav);
+9
View File
@@ -350,6 +350,12 @@ MicTXView::MicTXView(
&tx_button,
&tx_icon});
// disable key repeat on select
initial_switch_config_ = get_switches_repeat_config();
SwitchesState config = initial_switch_config_;
config[toUType(Switch::Sel)] = false;
set_switches_repeat_config(config);
set_rxbw_options();
set_rxbw_defaults(settings_.loaded());
@@ -640,6 +646,9 @@ MicTXView::MicTXView(
}
MicTXView::~MicTXView() {
// restore select key repeat mode
set_switches_repeat_config(initial_switch_config_);
audio::input::stop();
if (rx_enabled) { // Also turn off both (audio rx if enabled, and disable mic_loop to HP)
rxaudio(false);
+3
View File
@@ -90,6 +90,9 @@ class MicTXView : public View {
sampling_rate /* sampling rate */
};
// structure used to control key repeat
SwitchesState initial_switch_config_{};
enum Mic_Modulation : uint32_t {
MIC_MOD_NFM = 0,
MIC_MOD_WFM = 1,
+131 -1
View File
@@ -25,6 +25,9 @@
#include "baseband_api.hpp"
#include "string_format.hpp"
#include "file_path.hpp"
#include "ui_textentry.hpp"
#include "../keeloq_keystore.hpp"
#include "../keeloq_file.hpp"
#include "portapack_persistent_memory.hpp"
using namespace portapack;
@@ -56,6 +59,38 @@ void SubGhzDRecentEntryDetailView::update_data() {
if (cnt != SD_NO_CNT) console.writeln("Cnt: " + to_string_dec_uint(cnt));
if (entry_.data != 0) console.writeln("Data: " + to_string_hex(entry_.data));
if (entry_.sensorType == FPS_KEELOQ) {
console.writeln("Fix: " + to_string_hex(fix));
console.writeln("Encrypted: " + to_string_hex(encrypted));
console.writeln("Manufacturer: " + mf_name);
if (hop != SD_NO_HOP) {
console.writeln("Hop: " + to_string_hex(hop));
add_children({&button_save});
button_save.on_select = [this](const Button&) {
keeloq_file_buffer.clear();
text_prompt(
nav_,
keeloq_file_buffer,
64,
ENTER_KEYBOARD_MODE_ALPHA,
[this](std::string& buffer) {
KeeloqData params{
mf_name,
serial,
cnt,
btn};
ensure_directory(keeloq_remotes_dir);
write_keeloq_file(keeloq_remotes_dir / buffer + ".KEELOQ", params);
});
};
}
}
}
SubGhzDRecentEntryDetailView::SubGhzDRecentEntryDetailView(NavigationView& nav, const SubGhzDRecentEntry& entry)
@@ -303,6 +338,51 @@ void atomo_decrypt(uint8_t* buff) {
}
}
bool SubGhzDRecentEntryDetailView::keeloq_check_decrypt(uint32_t decrypt) {
uint16_t end_serial = serial & 0xFF;
if ((decrypt >> 28 == btn) && (((((uint16_t)(decrypt >> 16)) & 0xFF) == end_serial) ||
((((uint16_t)(decrypt >> 16)) & 0xFF) == 0))) {
cnt = decrypt & 0xFFFF;
return true;
}
return false;
}
bool SubGhzDRecentEntryDetailView::keeloq_check_decrypt_centurion(uint32_t decrypt) {
if ((decrypt >> 28 == btn) && ((((uint16_t)(decrypt >> 16)) & 0x3FF) == 0x1CE)) {
cnt = decrypt & 0xFFFF;
return true;
}
return false;
}
uint32_t keeloq_decrypt(const uint32_t data, const uint64_t key) {
uint32_t x = data, r;
for (r = 0; r < 528; r++)
x = (x << 1) ^ bit(x, 31) ^ bit(x, 15) ^ (uint32_t)bit(key, (15 - r) & 63) ^
bit(KEELOQ_NLF, g5(x, 0, 8, 19, 25, 30));
return x;
}
uint64_t keeloq_normal_learning(uint32_t data, const uint64_t key) {
uint32_t k1, k2;
data &= 0x0FFFFFFF;
data |= 0x20000000;
k1 = keeloq_decrypt(data, key);
data &= 0x0FFFFFFF;
data |= 0x60000000;
k2 = keeloq_decrypt(data, key);
return ((uint64_t)k2 << 32) | k1;
}
const uint32_t came_twee_magic_numbers_xor[15] = {
0x0E0E0E00,
0x1D1D1D11,
@@ -591,7 +671,57 @@ void SubGhzDRecentEntryDetailView::parseProtocol() {
}
if (entry_.sensorType == FPS_KEELOQ) {
// too many sub protocol versions, skipping. maybe in future when we'll have much more fw space
uint64_t data_rev = FProtoGeneral::subghz_protocol_blocks_reverse_key(entry_.data, 64);
btn = data_rev >> 60;
serial = (data_rev >> 32) & 0xFFFFFFF;
fix = data_rev >> 32;
encrypted = data_rev & 0xFFFFFFFF;
KeeloqKeystore keystore{};
const auto& keys = keystore.get_keys();
if (keys.empty()) {
return;
}
for (const auto& key : keys) {
switch (key.type) {
case KEELOQ_SIMPLE_LEARNING: {
uint32_t decrypted = keeloq_decrypt(encrypted, key.key);
if (keeloq_check_decrypt(decrypted)) {
mf_name = key.mf_name;
hop = decrypted;
return;
}
break;
}
case KEELOQ_NORMAL_LEARNING: {
uint64_t man = keeloq_normal_learning(fix, key.key);
uint32_t decrypted = keeloq_decrypt(encrypted, man);
if (key.mf_name == "Centurion" && keeloq_check_decrypt_centurion(decrypted)) {
mf_name = "Centurion";
hop = decrypted;
return;
} else if (keeloq_check_decrypt(decrypted)) {
mf_name = key.mf_name;
hop = decrypted;
return;
}
break;
}
}
}
return;
}
+28 -1
View File
@@ -25,7 +25,17 @@
#define SD_NO_SERIAL 0xFFFFFFFF
#define SD_NO_BTN 0xFF
#define SD_NO_CNT 0xFF
#define SD_NO_CNT 0xFFFFFFFF
#define SD_NO_HOP 0xFFFFFFFF
#define SD_NO_FIX 0xFFFFFFFF
#define SD_NO_ENCRYPTED 0xFFFFFFFF
#define bit(x, n) (((x) >> (n)) & 1)
#define g5(x, a, b, c, d, e) \
(bit(x, a) + bit(x, b) * 2 + bit(x, c) * 4 + bit(x, d) * 8 + bit(x, e) * 16)
#define KEELOQ_NLF 0x3A5C742E
#include "ui.hpp"
#include "ui_navigation.hpp"
@@ -191,6 +201,19 @@ class SubGhzDRecentEntryDetailView : public View {
uint32_t cnt = SD_NO_CNT;
uint32_t seed = 0;
// keeloq specific
std::string keeloq_file_buffer{};
uint32_t hop = SD_NO_HOP;
uint32_t fix = SD_NO_FIX;
uint32_t encrypted = SD_NO_ENCRYPTED;
std::string mf_name = "Unknown";
bool keeloq_check_decrypt(uint32_t decrypt);
bool keeloq_check_decrypt_centurion(uint32_t decrypt);
// end keeloq specific
Text text_type{{UI_POS_X(0), 1 * 16, 15 * 8, 16}, "?"};
Text text_id{{6 * 8, 2 * 16, 10 * 8, 16}, "?"};
@@ -207,6 +230,10 @@ class SubGhzDRecentEntryDetailView : public View {
{screen_width - 96 - 4, screen_height - 32 - 12, 96, 32},
"Done"};
Button button_save{
{4, screen_height - 32 - 12, 96, 32},
"Save"};
void parseProtocol();
};
+24
View File
@@ -52,12 +52,21 @@ static void send_message(const Message* const message) {
creg::m0apptxevent::assert_event();
if constexpr (check_for_message_hang) {
#ifdef PRALINE
/* Timeout: ~3 seconds at typical clock speeds */
auto count = 200'000'000u;
#else
auto count = UINT32_MAX;
#endif
while (shared_memory.baseband_message && --count)
/* spin */;
if (count == 0)
#ifdef PRALINE
chDbgPanic("BB Msg Timeout");
#else
chDbgPanic("Baseband Send Fail");
#endif
} else {
while (shared_memory.baseband_message)
/* spin */;
@@ -373,6 +382,21 @@ void set_moreserx_config(uint8_t mode) {
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);
}
void set_morsetx_key(bool key_down) {
const MorseTXkeyMessage message{key_down};
send_message(&message);
}
void set_bitstream_config(uint32_t deviation, uint8_t mode) {
const StreamTXConfigurationMessage message{deviation, mode};
send_message(&message);
}
static bool baseband_image_running = false;
void run_image(const spi_flash::image_tag_t image_tag) {
+3
View File
@@ -103,9 +103,12 @@ 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_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);
void set_noaaapt_config();
void set_flex_config();
void set_bitstream_config(uint32_t deviation, uint8_t mode); // mode 0 for am, 1 for 2fsk
void request_roger_beep();
void request_rssi_beep();
+256
View File
@@ -23,6 +23,7 @@
#include "portapack_persistent_memory.hpp"
#include "portapack_io.hpp"
#include "portapack.hpp"
#include "hackrf_hal.hpp"
using namespace hackrf::one;
@@ -30,6 +31,14 @@ using namespace hackrf::one;
#include "lpc43xx_cpp.hpp"
using namespace lpc43xx;
#ifdef PRALINE
extern "C" {
#include "fpga_bridge.h"
}
// Need access to ssp1_arbiter from radio namespace
#include "radio.hpp"
#endif
constexpr uint32_t si5351_vco_f = 800000000;
constexpr si5351::Inputs si5351_inputs{
@@ -54,6 +63,12 @@ constexpr si5351::PLL si5351_pll_xtal_25m{
.c = 1,
};
constexpr auto si5351_pll_a_xtal_reg = si5351_pll_xtal_25m.reg(0);
#ifdef PRALINE
static_assert(si5351_pll_xtal_25m.f_vco() == si5351_vco_f, "PLL XTAL frequency wrong");
static_assert(si5351_pll_xtal_25m.p1() == 3584, "PLL XTAL P1 wrong");
static_assert(si5351_pll_xtal_25m.p2() == 0, "PLL XTAL P2 wrong");
static_assert(si5351_pll_xtal_25m.p3() == 1, "PLL XTAL P3 wrong");
#endif
constexpr si5351::PLL si5351_pll_clkin_10m{
.f_in = si5351_inputs.f_clkin_out(),
@@ -64,10 +79,12 @@ constexpr si5351::PLL si5351_pll_clkin_10m{
constexpr auto si5351c_pll_b_clkin_reg = si5351_pll_clkin_10m.reg(1);
constexpr auto si5351a_pll_a_clkin_reg = si5351_pll_clkin_10m.reg(0);
#ifndef PRALINE
static_assert(si5351_pll_xtal_25m.f_vco() == si5351_vco_f, "PLL XTAL frequency wrong");
static_assert(si5351_pll_xtal_25m.p1() == 3584, "PLL XTAL P1 wrong");
static_assert(si5351_pll_xtal_25m.p2() == 0, "PLL XTAL P2 wrong");
static_assert(si5351_pll_xtal_25m.p3() == 1, "PLL XTAL P3 wrong");
#endif
static_assert(si5351_pll_clkin_10m.f_vco() == si5351_vco_f, "PLL CLKIN frequency wrong");
static_assert(si5351_pll_clkin_10m.p1() == 9728, "PLL CLKIN P1 wrong");
@@ -101,6 +118,22 @@ constexpr si5351::MultisynthFractional si5351_ms_0_8m{
};
constexpr auto si5351c_ms_0_8m_reg = si5351_ms_0_8m.reg(clock_generator_output_og_codec);
#ifdef PRALINE
// Verify compile-time values for 8 MHz config
static_assert(si5351_ms_0_8m.p1() == 5888, "MS0 8MHz P1 should be 5888 (0x1700)");
static_assert(si5351_ms_0_8m.p2() == 0, "MS0 8MHz P2 should be 0");
static_assert(si5351_ms_0_8m.p3() == 1, "MS0 8MHz P3 should be 1");
static_assert(si5351_ms_0_8m.f_out() == 8000000, "MS0 should output 8 MHz");
// Verify register array encoding
static_assert(si5351c_ms_0_8m_reg[0] == 42, "MS0 base register should be 42");
static_assert(si5351c_ms_0_8m_reg[1] == 0x00, "MS0 reg43 P3[15:8] should be 0x00");
static_assert(si5351c_ms_0_8m_reg[2] == 0x01, "MS0 reg44 P3[7:0] should be 0x01");
static_assert(si5351c_ms_0_8m_reg[3] == 0x10, "MS0 reg45 R_DIV should be 0x10");
static_assert(si5351c_ms_0_8m_reg[4] == 0x17, "MS0 reg46 P1[15:8] should be 0x17");
static_assert(si5351c_ms_0_8m_reg[5] == 0x00, "MS0 reg47 P1[7:0] should be 0x00");
#endif
constexpr si5351::MultisynthFractional si5351_ms_group{
.f_src = si5351_vco_f,
.a = 80, /* Don't care */
@@ -204,7 +237,11 @@ constexpr ClockControls si5351c_clock_control_common{{
}};
constexpr ClockControls si5351a_clock_control_common{{
#ifndef PRALINE
{ClockControl::ClockCurrentDrive::_6mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
#else
{ClockControl::ClockCurrentDrive::_6mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Fractional, ClockControl::ClockPowerDown::Power_Off}, // CLK0: MUST be Fractional for 8 MHz!
#endif
{ClockControl::ClockCurrentDrive::_4mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Fractional, ClockControl::ClockPowerDown::Power_Off},
{ClockControl::ClockCurrentDrive::_8mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
{ClockControl::ClockCurrentDrive::_2mA, ClockControl::ClockSource::MS_Self, ClockControl::ClockInvert::Normal, ClockControl::MultiSynthSource::PLLA, ClockControl::MultiSynthMode::Integer, ClockControl::ClockPowerDown::Power_Off},
@@ -255,9 +292,48 @@ static void portapack_tcxo_disable() {
using namespace hackrf::one;
void ClockManager::init_clock_generator() {
#ifdef PRALINE
// PRALINE: Configure clock input mux GPIO
// GPIO0_15 (clkin_ctrl) selects GP_CLKIN source:
// 0 = P1 connector (external)
// 1 = P22 (internal Si5351 CLK2)
constexpr GPIO gpio_clkin_ctrl = gpio[GPIO0_15];
gpio_clkin_ctrl.output();
gpio_clkin_ctrl.write(1); // CLKIN_SIGNAL_P22 = 1 = internal Si5351 CLK2
// Also enable MCU clock gate (GPIO0_8)
gpio_r9_mcu_clk_en.output();
gpio_r9_mcu_clk_en.write(1);
#else
// HackRF One r9: GPIO0_8 (mcu_clk_en) gates Si5351 CLK2/CLK7 to GP_CLKIN
if (hackrf_r9) {
gpio_r9_mcu_clk_en.output();
gpio_r9_mcu_clk_en.write(1);
}
#endif
clock_generator.reset();
clock_generator.set_crystal_internal_load_capacitance(CrystalInternalLoadCapacitance::XTAL_CL_8pF);
clock_generator.enable_fanout();
#ifdef PRALINE
/* PRALINE has Si5351A (NOT Si5351C like HackRF One OG).
* Must use Si5351A configuration: PLLA only, no CLKIN support.
*
* IMPORTANT: Follow HackRF reference sequence:
* 1. Set PLL input sources
* 2. Configure PLL and multisynths
* 3. Set clock control registers (AFTER multisynths!)
* 4. Reset PLLs
* 5. Enable outputs
*/
clock_generator.set_pll_input_sources(si5351a_pll_input_sources);
/* Skip MCU CLKIN setup and reference detection for PRALINE - not applicable */
reference = Reference{ReferenceSource::Xtal, 0};
/* Clock control will be set AFTER multisynth configuration - see below */
#else
clock_generator.set_pll_input_sources(hackrf_r9
? si5351a_pll_input_sources
: si5351c_pll_input_sources);
@@ -298,7 +374,62 @@ void ClockManager::init_clock_generator() {
si5351_clock_control_common[7].ms_src(ref_pll),
}};
clock_generator.set_clock_control(si5351_clock_control);
#endif
#ifdef PRALINE
/* PRALINE uses Si5351A with:
* CLK0 = AFE_CLK (codec/FPGA sample clock)
* CLK1 = SCT_CLK (FPGA timing clock at 2x sample rate)
* CLK4 = first IF (RFFC5072)
* CLK5 = second IF (MAX2831)
* Uses PLLA on XTAL only (no CLKIN support).
*/
/* Step 1: Write PLL A configuration (800 MHz VCO from 25 MHz XTAL) */
/* Use single-byte writes to debug I2C issues */
{
const auto& pll_regs = si5351_pll_a_xtal_reg;
const uint8_t base_reg = pll_regs[0];
for (size_t i = 1; i < pll_regs.size(); i++) {
clock_generator.write_register(base_reg + i - 1, pll_regs[i]);
}
}
/* Step 2: Write multisynth configurations using single-byte writes */
clock_generator.write_ms_single_byte(0, si5351_ms_0_8m); // MS0 = divider 50, r_div=1 for 8 MHz
clock_generator.write_ms_single_byte(1, si5351_ms_16m); // MS1 = divider 50, r_div=0 for 16 MHz
/* CLK4 and CLK5 - use single-byte writes too */
{
const auto& ms4_regs = si5351c_ms_4_reg;
const uint8_t base_reg = ms4_regs[0];
for (size_t i = 1; i < ms4_regs.size(); i++) {
clock_generator.write_register(base_reg + i - 1, ms4_regs[i]);
}
}
{
const auto& ms5_regs = si5351c_ms_5_reg;
const uint8_t base_reg = ms5_regs[0];
for (size_t i = 1; i < ms5_regs.size(); i++) {
clock_generator.write_register(base_reg + i - 1, ms5_regs[i]);
}
}
clock_generator.write(si5351a_ms6_7_off_reg); // MS6/7 off - short write is OK
/* Step 3: NOW set clock control registers (AFTER multisynths per HackRF reference) */
const auto ref_pll = ClockControl::MultiSynthSource::PLLA;
const ClockControls si5351_clock_control = ClockControls{{
si5351a_clock_control_common[0].ms_src(ref_pll),
si5351a_clock_control_common[1].ms_src(ref_pll),
si5351a_clock_control_common[2].ms_src(ref_pll),
si5351a_clock_control_common[3].ms_src(ref_pll),
si5351a_clock_control_common[4].ms_src(ref_pll),
si5351a_clock_control_common[5].ms_src(ref_pll),
si5351a_clock_control_common[6].ms_src(ref_pll),
si5351a_clock_control_common[7].ms_src(ref_pll),
}};
clock_generator.set_clock_control(si5351_clock_control);
#else
if (hackrf_r9) {
const PLLReg pll_reg = (reference.source == ReferenceSource::Xtal)
? si5351_pll_a_xtal_reg
@@ -319,21 +450,45 @@ void ClockManager::init_clock_generator() {
clock_generator.write(si5351c_ms_5_reg);
clock_generator.write(si5351c_ms6_7_off_mcu_clkin_reg);
}
#endif
clock_generator.reset_plls();
// Wait for PLL(s) to lock.
#ifdef PRALINE
// PRALINE: Wait for PLLA to lock (0x20 = LOL_A bit)
uint8_t device_status_mask = 0x20;
uint32_t pll_timeout = 100000;
while ((clock_generator.device_status() & device_status_mask) != 0 && pll_timeout > 0) {
pll_timeout--;
}
// Store PLL lock status for debugging
static volatile uint32_t pll_lock_timeout = pll_timeout;
(void)pll_lock_timeout;
// CRITICAL: Add delay to ensure Si5351 writes complete before I2C bus stops
chThdSleepMilliseconds(100);
#else
// Wait for PLL(s) to lock - with timeout to prevent hang
uint8_t device_status_mask = hackrf_r9
? 0x20
: (ref_pll == ClockControl::MultiSynthSource::PLLB)
? 0x40
: 0x20;
#ifndef PRALINE
while ((clock_generator.device_status() & device_status_mask) != 0);
#else
uint32_t pll_timeout = 100000;
while ((clock_generator.device_status() & device_status_mask) != 0 && pll_timeout > 0) {
pll_timeout--;
}
#endif
clock_generator.set_clock_control(
clock_generator_output_mcu_clkin,
si5351_clock_control_common[clock_generator_output_mcu_clkin].ms_src(ref_pll).clk_pdn(ClockControl::ClockPowerDown::Power_On));
clock_generator.enable_output(clock_generator_output_mcu_clkin);
#endif
}
uint32_t ClockManager::measure_gp_clkin_frequency() {
@@ -400,6 +555,15 @@ void ClockManager::shutdown() {
}
void ClockManager::enable_codec_clocks() {
#ifdef PRALINE
/* PRALINE: CLK0 (AFE_CLK) for codec/FPGA, CLK1 (SCT_CLK) for FPGA timing.
* Reference hackrf_core.c shows PRALINE needs both CLK0 and CLK1. */
clock_generator.enable_clock(clock_generator_output_og_codec); /* CLK0 */
clock_generator.enable_clock(clock_generator_output_og_cpld); /* CLK1 */
clock_generator.enable_output_mask(
(1U << clock_generator_output_og_codec) |
(1U << clock_generator_output_og_cpld));
#else
if (hackrf_r9) {
clock_generator.enable_clock(clock_generator_output_r9_sgpio);
} else {
@@ -417,6 +581,7 @@ void ClockManager::enable_codec_clocks() {
clock_generator.enable_output_mask(
(1U << clock_generator_output_og_codec) | (1U << clock_generator_output_og_cpld) | (1U << clock_generator_output_og_sgpio));
}
#endif
}
void ClockManager::disable_codec_clocks() {
@@ -424,6 +589,14 @@ void ClockManager::disable_codec_clocks() {
* be enabled for the output to come to rest at the state specified by
* CLKx_DISABLE_STATE.
*/
#ifdef PRALINE
/* PRALINE: CLK0 (AFE_CLK) and CLK1 (SCT_CLK) used for codec/FPGA */
clock_generator.disable_output_mask(
(1U << clock_generator_output_og_codec) |
(1U << clock_generator_output_og_cpld));
clock_generator.disable_clock(clock_generator_output_og_codec);
clock_generator.disable_clock(clock_generator_output_og_cpld);
#else
if (hackrf_r9) {
clock_generator.disable_output_mask(1U << clock_generator_output_r9_sgpio);
clock_generator.disable_clock(clock_generator_output_r9_sgpio);
@@ -434,9 +607,17 @@ void ClockManager::disable_codec_clocks() {
clock_generator.disable_clock(clock_generator_output_og_cpld);
clock_generator.disable_clock(clock_generator_output_og_sgpio);
}
#endif
}
void ClockManager::enable_if_clocks() {
#ifdef PRALINE
/* PRALINE uses CLK4 (first IF) and CLK5 (second IF) like original HackRF One */
clock_generator.enable_clock(clock_generator_output_og_first_if);
clock_generator.enable_output_mask(1U << clock_generator_output_og_first_if);
clock_generator.enable_clock(clock_generator_output_og_second_if);
clock_generator.enable_output_mask(1U << clock_generator_output_og_second_if);
#else
if (hackrf_r9) {
clock_generator.enable_clock(clock_generator_output_r9_if);
clock_generator.enable_output_mask(1U << clock_generator_output_r9_if);
@@ -446,9 +627,16 @@ void ClockManager::enable_if_clocks() {
clock_generator.enable_clock(clock_generator_output_og_second_if);
clock_generator.enable_output_mask(1U << clock_generator_output_og_second_if);
}
#endif
}
void ClockManager::disable_if_clocks() {
#ifdef PRALINE
clock_generator.disable_output_mask(1U << clock_generator_output_og_first_if);
clock_generator.disable_clock(clock_generator_output_og_first_if);
clock_generator.disable_output_mask(1U << clock_generator_output_og_second_if);
clock_generator.disable_clock(clock_generator_output_og_second_if);
#else
if (hackrf_r9) {
clock_generator.disable_output_mask(1U << clock_generator_output_r9_if);
clock_generator.disable_clock(clock_generator_output_r9_if);
@@ -458,19 +646,39 @@ void ClockManager::disable_if_clocks() {
clock_generator.disable_output_mask(1U << clock_generator_output_og_second_if);
clock_generator.disable_clock(clock_generator_output_og_second_if);
}
#endif
}
void ClockManager::set_sampling_frequency(const uint32_t frequency) {
#ifdef PRALINE
/* PRALINE: CLK0=AFE_CLK runs at sample rate (VCO/divider/2)
* CLK1=SCT_CLK runs at 2x sample rate (VCO/divider/1)
* Reference: hackrf_core.c sample_rate_frac_set() lines 580-582
*/
/* PRALINE: Match HackRF USB sample_rate_frac_set()
* Reference: hackrf_usb radio.c lines 29-91, hackrf_core.c lines 501-685 */
// Set FPGA decimation to 0 (no decimation) for direct passthrough
fpga_debug_register_write(2, 0);
radio::invalidate_spi_config();
// The following was originally from @kitty. Adopting for testing radio.
clock_generator.set_ms_frequency(0, frequency * 2, si5351_vco_f, 1); // CLK0: r_div=1 (÷2)
clock_generator.set_ms_frequency(1, frequency * 2, si5351_vco_f, 0); // CLK1: r_div=0 (÷1)
#else
/* Codec clock is at sampling frequency, CPLD and SGPIO clocks are at
* twice the frequency, and derived from the MS0 synth. So it's only
* necessary to change the MS0 synth frequency, and ensure the output
* is divided by two.
*/
if (hackrf_r9) {
clock_generator.set_ms_frequency(clock_generator_output_r9_sgpio, frequency * 2, si5351_vco_f, 0);
} else {
clock_generator.set_ms_frequency(clock_generator_output_og_codec, frequency * 2, si5351_vco_f, 1);
}
#endif
}
void ClockManager::set_reference_ppb(const int32_t ppb) {
@@ -510,7 +718,15 @@ void ClockManager::start_frequency_monitor_measurement(const cgu::CLK_SEL clk_se
void ClockManager::wait_For_frequency_monitor_measurement_done() {
// FREQ_MON mechanism fails to finish if there's no clock present on selected input?!
#ifndef PRALINE
while (LPC_CGU->FREQ_MON.MEAS == 1);
#else
// PRALINE FIX: Add timeout to prevent infinite hang
uint32_t timeout = 100000;
while (LPC_CGU->FREQ_MON.MEAS == 1 && timeout > 0) {
timeout--;
}
#endif
}
uint32_t ClockManager::get_frequency_monitor_measurement_in_hertz() {
@@ -521,6 +737,35 @@ uint32_t ClockManager::get_frequency_monitor_measurement_in_hertz() {
}
void ClockManager::start_audio_pll() {
#ifdef PRALINE
/* PRALINE: Use 12MHz XTAL for audio PLL
* For 12MHz XTAL input, 48kHz audio rate, 256Fs MCLK:
* Fout=12.288MHz, Fcco=491.52MHz
* 12MHz * 1024 / 25 = 491.52MHz
* MSEL=1024, NSEL=25, PSEL=20
*/
cgu::pll0audio::ctrl({
.pd = 1,
.bypass = 0,
.directi = 0,
.directo = 0,
.clken = 0,
.frm = 0,
.autoblock = 1,
.pllfract_req = 0,
.sel_ext = 1,
.mod_pd = 1,
.clk_sel = cgu::CLK_SEL::XTAL,
});
cgu::pll0audio::mdiv({
.mdec = 22625UL, // MDEC for MSEL=1024
});
cgu::pll0audio::np_div({
.pdec = 31, // PSEL=20
.ndec = 69, // NDEC for NSEL=25
});
#else
cgu::pll0audio::ctrl({
.pd = 1,
.bypass = 0,
@@ -549,13 +794,24 @@ void ClockManager::start_audio_pll() {
.pdec = 31,
.ndec = 45,
});
#endif
cgu::pll0audio::frac({
.pllfract_ctrl = 0,
});
cgu::pll0audio::power_up();
#ifndef PRALINE
while (!cgu::pll0audio::is_locked());
#else
// PRALINE FIX: Add timeout to prevent infinite hang if GP_CLKIN not present
{
uint32_t timeout = 100000;
while (!cgu::pll0audio::is_locked() && timeout > 0) {
timeout--;
}
}
#endif
cgu::pll0audio::clock_enable();
set_base_audio_clock_divider(1);
+7
View File
@@ -72,6 +72,13 @@ class ClockManager {
void set_reference_ppb(const int32_t ppb);
#ifdef PRALINE
// Si5351 diagnostic methods
uint8_t si5351_read_status() { return clock_generator.device_status(); }
uint8_t si5351_read_register(uint8_t reg) { return clock_generator.read_register(reg); }
void si5351_write_register(uint8_t reg, uint8_t value) { clock_generator.write_register(reg, value); }
#endif
uint32_t get_frequency_monitor_measurement_in_hertz();
Reference get_reference() const;
+19 -10
View File
@@ -91,9 +91,9 @@ set(EXTCPPSRC
external/adsbtx/main.cpp
external/adsbtx/ui_adsb_tx.cpp
#morse_tx 768 bytes
external/morse_tx/main.cpp
external/morse_tx/ui_morse.cpp
#morse_tx 768 bytes -- disabled because of the new morse tx app with more functions
#external/morse_tx/main.cpp
#external/morse_tx/ui_morse.cpp
#sstvtx 456 bytes
external/sstvtx/main.cpp
@@ -285,14 +285,13 @@ set(EXTCPPSRC
external/siggen/main.cpp
external/siggen/ui_siggen.cpp
#sdusb
external/sdusb/main.cpp
external/sdusb/ui_sd_over_usb.cpp
#morse_radio
external/morse_radio/main.cpp
external/morse_radio/ui_morse_radio.cpp
#morseradiotx
external/morseradiotx/main.cpp
external/morseradiotx/ui_morse_radiotx.cpp
)
set(EXTAPPLIST
@@ -317,7 +316,7 @@ set(EXTAPPLIST
tpmsrx
protoview
adsbtx
morse_tx
#morse_tx
sstvtx
sstvrx
random_password
@@ -364,6 +363,16 @@ set(EXTAPPLIST
flex_rx
subcarrx
siggen
sdusb
morse_radio
morseradiotx
)
# sdusb has type conflicts with PRALINE (HackRF Pro) - add only for non-PRALINE builds
if(NOT BOARD STREQUAL "PRALINE")
list(APPEND EXTCPPSRC
external/sdusb/main.cpp
external/sdusb/ui_sd_over_usb.cpp
)
list(APPEND EXTAPPLIST sdusb)
endif()
+8
View File
@@ -93,6 +93,7 @@ MEMORY
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
}
SECTIONS
@@ -518,5 +519,12 @@ SECTIONS
KEEP(*(.external_app.app_morse_radio.application_information));
*(*ui*external_app*morse_radio*);
} > ram_external_app_morse_radio
.external_app_morseradiotx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_morseradiotx.application_information));
*(*ui*external_app*morseradiotx*);
} > ram_external_app_morseradiotx
}
+6 -1
View File
@@ -80,7 +80,7 @@ bool FlipperTxView::on_file_changed(std::filesystem::path new_file_path) {
return false;
}
preset = submeta.value().preset;
if (preset != FLIPPER_PRESET_OOK) {
if (preset != FLIPPER_PRESET_OOK && preset != FLIPPER_PRESET_2FSK) {
field_filename.set_text("File: err, not supp. preset");
return false;
}
@@ -108,8 +108,13 @@ void FlipperTxView::stop() {
bool FlipperTxView::start() {
if (filename.empty()) return false;
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
transmitter_model.set_sampling_rate(OOK_SAMPLERATE);
transmitter_model.enable();
button_startstop.set_text(LanguageHelper::currentMessages[LANG_STOP]);
uint8_t mode = 0;
if (preset == FLIPPER_PRESET_2FSK)
mode = 1;
baseband::set_bitstream_config(FM_DEVIATION, mode);
// start thread
replay_thread = std::make_unique<FlipperPlayThread>(
filename,
@@ -28,6 +28,8 @@ using namespace ui;
namespace ui::external_app::flippertx {
#define OOK_SAMPLERATE 2280000U
#define FM_DEVIATION 60000U
class FlipperPlayThread;
class FlipperTxView : public View {
public:
@@ -12,6 +12,13 @@ MorsePracticeView::MorsePracticeView(ui::NavigationView& nav)
&btn_clear,
&console_text,
&field_volume});
initial_switch_config_ = get_switches_repeat_config();
SwitchesState config = initial_switch_config_;
config[toUType(Switch::Sel)] = false;
set_switches_repeat_config(config);
audio::set_rate(audio::Rate::Hz_24000);
btn_tt.on_select = [this](Button&) {
@@ -43,6 +50,7 @@ MorsePracticeView::MorsePracticeView(ui::NavigationView& nav)
}
MorsePracticeView::~MorsePracticeView() {
set_switches_repeat_config(initial_switch_config_);
receiver_model.disable();
baseband::shutdown();
audio::output::stop();
@@ -68,7 +68,7 @@ class MorsePracticeView : public ui::View {
ui::Text txt_last{{UI_POS_X(0), UI_POS_Y(6), UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, ""};
ui::Button btn_clear{{UI_POS_X(0), UI_POS_Y_BOTTOM(2), UI_POS_WIDTH(6), UI_POS_HEIGHT(1)}, "CLR"};
ui::Console console_text{{UI_POS_X(0), UI_POS_Y(7), UI_POS_MAXWIDTH, UI_POS_HEIGHT_REMAINING(10)}};
AudioVolumeField field_volume{{UI_POS_X_RIGHT(2), UI_POS_X(0)}};
AudioVolumeField field_volume{{UI_POS_X_RIGHT(2), UI_POS_Y(0)}};
uint8_t last_color_id = 255;
uint8_t color_id = 255;
@@ -77,6 +77,7 @@ class MorsePracticeView : public ui::View {
bool button_touch = false;
bool button_was_selected = false;
bool decode_timeout_calc = false;
SwitchesState initial_switch_config_{};
MessageHandlerRegistration message_handler_framesync{
Message::ID::DisplayFrameSync,
+35 -27
View File
@@ -17,6 +17,7 @@ MorseRadioView::MorseRadioView(ui::NavigationView& nav)
&txt_last,
&txt_speed,
&txt_freq,
&txt_clip,
&options_mode,
&btn_clear,
&console_text,
@@ -33,41 +34,44 @@ MorseRadioView::MorseRadioView(ui::NavigationView& nav)
logger->init_daily_log(logs_dir);
};
audio::output::start();
receiver_model.set_sampling_rate(3072000);
receiver_model.set_baseband_bandwidth(1750000);
receiver_model.enable();
field_squelch.on_change = [this](int32_t v) {
receiver_model.set_squelch_level(v);
};
options_mode.on_change = [this](size_t, int32_t value) {
current_mode = (uint8_t)value;
options_mode.on_change = [this](size_t, int32_t mode) {
audio::output::stop();
receiver_model.disable();
morse_decoder_.resetLearning();
if (current_mode == 0) {
if (mode == MORSE_NFM) {
receiver_model.set_am_configuration(4);
receiver_model.set_modulation(ReceiverModel::Mode::NarrowbandFMAudio);
field_squelch.set_style(Theme::getInstance()->option_active);
field_squelch.set_focusable(true);
receiver_model.set_squelch_level(field_squelch.value());
field_squelch.set_value(receiver_model.squelch_level());
audio::set_rate(audio::Rate::Hz_24000);
} else {
audio::set_rate(audio::Rate::Hz_12000);
receiver_model.set_modulation(ReceiverModel::Mode::AMAudio);
receiver_model.set_am_configuration(current_mode + 7);
receiver_model.set_squelch_level(0);
if (mode == MORSE_AM_CW || mode == MORSE_AM_DSB)
receiver_model.set_am_configuration(7);
else if (mode == MORSE_AM_USB)
receiver_model.set_am_configuration(9);
else // LSB
receiver_model.set_am_configuration(10);
field_squelch.set_style(Theme::getInstance()->fg_dark);
field_squelch.set_focusable(false);
audio::set_rate(audio::Rate::Hz_12000);
}
baseband::set_moreserx_config(current_mode);
};
field_squelch.set_value(receiver_model.squelch_level(), false); // will be sent later, no need to send 2x
field_squelch.on_change = [this](int32_t v) {
if (current_mode == 0)
receiver_model.set_squelch_level(v);
};
options_mode.set_selected_index(current_mode, true);
baseband::set_moreserx_config(mode);
saved_mode = mode;
auto vol = field_volume.value(); // audio volume fix
field_volume.set_value(0);
field_volume.set_value(vol);
audio::output::start();
receiver_model.set_headphone_volume(receiver_model.headphone_volume()); // WM8731 hack.
receiver_model.set_sampling_rate(3072000);
receiver_model.set_baseband_bandwidth(1750000);
receiver_model.enable();
};
options_mode.set_selected_index(saved_mode);
logger = std::make_unique<MorseLogger>();
chk_log.on_select = [this](Checkbox&, bool save) {
@@ -103,21 +107,21 @@ void MorseLogger::init_daily_log(const std::filesystem::path& log_dir) {
}
}
void MorseLogger::radio_set_log(uint8_t current_mode) {
void MorseLogger::radio_set_log(const std::string& morse_mode) {
int64_t freq = receiver_model.target_frequency();
std::string header = "Freq:" + to_string_rounded_freq(freq, 4);
header += "MHz, ";
header += "RX MODE:" + std::string(current_mode == 0 ? "CW/FM" : (current_mode == 1 ? "USB" : "LSB"));
header += "RX MODE:" + morse_mode;
header += "\r\nMessage:";
log_file.write_raw(header);
}
bool MorseLogger::on_packet(const std::string& content, bool time, uint8_t current_mode) {
bool MorseLogger::on_packet(const std::string& content, bool time, const std::string& morse_mode) {
if (!time) {
log_file.write_raw_no_newline("\r\n\r\n");
auto timestamp = to_string_datetime(rtc_time::now(), YMDHMS);
log_file.write_raw("[" + timestamp + "] ");
radio_set_log(current_mode);
radio_set_log(morse_mode);
char_count = 0;
time = true;
}
@@ -152,6 +156,8 @@ MorseRadioView::~MorseRadioView() {
void MorseRadioView::focus() {
field_frequency.focus();
txt_clip.set_style(Theme::getInstance()->fg_red);
txt_clip.hidden(true);
}
void MorseRadioView::check_for_timeout() {
@@ -205,6 +211,8 @@ int32_t MorseRadioView::ProcessSignal(int32_t sig_time_us) {
void MorseRadioView::on_data(const MorseRXDataMessage* message) {
int32_t r;
txt_clip.hidden(!message->clipped);
for (uint8_t i = 0; i <= message->state_cnt; ++i) {
r = ProcessSignal(message->state_durations[i]);
auto result = morse_decoder_.handleInput((r != 0) ? r : 0);
@@ -212,7 +220,7 @@ void MorseRadioView::on_data(const MorseRXDataMessage* message) {
last_activity_time = chTimeNow(); // start reset timer on valid input
writeCharToConsole(result.text, result.confidence);
if (logger && save_log) {
time_stamp = logger->on_packet(result.text, time_stamp, current_mode);
time_stamp = logger->on_packet(result.text, time_stamp, options_mode.selected_index_name());
}
float dah_time = morse_decoder_.getCurrentTimeUnit() * 3.0f;
if (dah_time > 0) {
@@ -54,8 +54,8 @@ class MorseLogger {
}
void init_daily_log(const std::filesystem::path& log_dir);
bool on_packet(const std::string& content, bool time, uint8_t current_mode);
void radio_set_log(uint8_t current_mode);
bool on_packet(const std::string& content, bool time, const std::string& morse_mode);
void radio_set_log(const std::string& morse_mode);
private:
LogFile log_file{};
@@ -83,12 +83,21 @@ class MorseRadioView : public ui::View {
RxRadioState radio_state_{};
std::unique_ptr<MorseLogger> logger{};
uint8_t current_mode{0}; // 0=CW/FM, 1=USB, 2=LSB
enum morse_modes : uint8_t {
MORSE_AM_CW = 0,
MORSE_NFM,
MORSE_AM_DSB,
MORSE_AM_USB,
MORSE_AM_LSB,
};
uint8_t saved_mode = MORSE_AM_CW;
app_settings::SettingsManager settings_{
"rx_morese_radio",
"rx_morse_radio",
app_settings::Mode::RX,
{{"cwmode"sv, &current_mode}}};
{
{"cwmode"sv, &saved_mode},
}};
RxFrequencyField field_frequency{
{UI_POS_X(0), UI_POS_Y(0)},
@@ -115,6 +124,7 @@ class MorseRadioView : public ui::View {
ui::Text txt_speed{{UI_POS_X(23), UI_POS_Y(1), UI_POS_WIDTH(3), UI_POS_HEIGHT(1)}, "??"};
ui::Text txt_last{{UI_POS_X(12), UI_POS_Y(4), UI_POS_WIDTH_REMAINING(12), UI_POS_HEIGHT(1)}, ""};
ui::Text txt_freq{{UI_POS_X(21), UI_POS_Y(2), UI_POS_WIDTH(5), UI_POS_HEIGHT(1)}, "??"};
ui::Text txt_clip{{UI_POS_X(15), UI_POS_Y(3), UI_POS_WIDTH(5), UI_POS_HEIGHT(1)}, "clipping"};
ui::Console console_text{{UI_POS_X(0), UI_POS_Y(5), UI_POS_MAXWIDTH, UI_POS_HEIGHT_REMAINING(7)}};
ui::Labels labels{
{{UI_POS_X(0), UI_POS_Y(1)}, "Squelch:", Theme::getInstance()->fg_light->foreground},
@@ -125,9 +135,15 @@ class MorseRadioView : public ui::View {
{{UI_POS_X(27), UI_POS_Y(2)}, "Hz", Theme::getInstance()->fg_light->foreground}};
ui::OptionsField options_mode{
{UI_POS_X(9), UI_POS_Y(2)},
5,
{{"CW/FM", 0}, {"USB", 1}, {"LSB", 2}}};
{UI_POS_X(8), UI_POS_Y(2) + 4}, // +4 to align with 'Log' checkbox text
6,
{
{"AM/CW", MORSE_AM_CW},
{"NFM", MORSE_NFM},
{"AM/DSB", MORSE_AM_DSB},
{"AM/USB", MORSE_AM_USB},
{"AM/LSB", MORSE_AM_LSB},
}};
Checkbox chk_log{{UI_POS_X(0), UI_POS_Y(2)}, 12, "Log", false};
ui::Button btn_clear{{UI_POS_X(0), UI_POS_Y_BOTTOM(2), UI_POS_WIDTH(6), UI_POS_HEIGHT(1)}, "CLR"};
+87
View File
@@ -0,0 +1,87 @@
/*
* Copyright (C) 2026 Pezsma
*
* This file is part of PortaPack.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include "ui.hpp"
#include "ui_morse_radiotx.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::morseradiotx {
void initialize_app(NavigationView& nav) {
nav.push<MorseRadiotxView>();
}
} // namespace ui::external_app::morseradiotx
extern "C" {
__attribute__((section(".external_app.app_morseradiotx.application_information"), used))
application_information_t _application_information_morseradiotx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::morseradiotx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "Morse 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::yellow().v,
/*.menu_location = */ app_location_t::TX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_none */ {'P', 'M', 'R', 'T'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
} // extern "C"
@@ -0,0 +1,389 @@
#ifndef __MORSEDECODER_HPP__
#define __MORSEDECODER_HPP__
/*
* Copyright (C) 2025 Pezsma
*
* This file is part of PortaPack.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#include <cstdint>
#include <string>
#include "string_format.hpp"
namespace ui::external_app::morseradiotx {
class MorseRingBuffer {
public:
MorseRingBuffer()
: head_(0), tail_(0), count_(0) {}
void push_back(const uint32_t& value) {
data_[head_] = value;
head_ = (head_ + 1) % 40;
if (count_ < 40) {
count_++;
} else {
// overwrite oldest element
tail_ = (tail_ + 1) % 40;
}
}
void pop_front() {
if (count_ > 0) {
tail_ = (tail_ + 1) % 40;
count_--;
}
}
size_t size() const { return count_; }
bool empty() const { return count_ == 0; }
const uint32_t& front() const { return data_[tail_]; }
// Access by index (0 = oldest)
uint32_t operator[](size_t idx) const {
return data_[(tail_ + idx) % 40];
}
// Convert to vector-like access for sorting etc.
void copy_to_array(uint32_t* out) const {
for (size_t i = 0; i < count_; ++i)
out[i] = (*this)[i];
}
void clear() {
head_ = 0;
tail_ = 0;
count_ = 0;
}
private:
uint32_t data_[40];
size_t head_;
size_t tail_;
size_t count_;
};
class MorseDecoder {
public:
struct DecodeResult {
std::string text = "";
double confidence = 0.0;
bool isValid() const {
return !text.empty();
}
};
struct MorseEntry {
std::string code;
std::string letter;
};
MorseDecoder() {}
void resetLearning() {
time_unit_ms_ = 119.0;
current_sequence_ = "";
last_sequence_ = "";
last_confidence_ = 0.0;
pulse_history_.clear();
pulse_gaps_.clear();
}
const char* get_morse_pattern(char c) {
char upper_c = (c >= 'a' && c <= 'z') ? c - 32 : c;
for (size_t i = 0; i < morse_table_size_; ++i) {
if (morse_table_[i].letter[0] == upper_c) {
return morse_table_[i].code.c_str();
}
}
return nullptr;
}
DecodeResult
handleInput(int32_t duration_ms) {
DecodeResult result = {"", 0.0};
if (duration_ms < 5 && duration_ms > -5) return result;
if (duration_ms > 0) {
pulse_history_.push_back(duration_ms);
double dah_prob = getDahProbability(duration_ms);
current_sequence_ += (dah_prob > 0.5) ? '-' : '.';
last_confidence_ = (dah_prob > 0.5) ? dah_prob : (1.0 - dah_prob);
last_sequence_ = current_sequence_;
} else {
uint32_t gap_duration = -duration_ms;
pulse_gaps_.push_back(gap_duration);
if (gap_duration >= getInterCharThreshold() && !current_sequence_.empty()) {
result.text = lookupMorse(current_sequence_);
result.confidence = (result.text[0] != '{') ? last_confidence_ : 0.0;
if (gap_duration >= getInterWordThreshold()) {
result.text += " ";
}
current_sequence_ = "";
}
}
updateLearning();
return result;
}
inline double getInterElementThreshold() { return time_unit_ms_ * 0.8; }
inline double getInterCharThreshold() { return time_unit_ms_ * 2.5; }
inline double getInterWordThreshold() { return time_unit_ms_ * 6.0; }
inline double getCurrentTimeUnit() { return time_unit_ms_; }
inline std::string getLastSequence() { return last_sequence_; }
private:
std::string current_sequence_ = "";
std::string last_sequence_ = "";
double time_unit_ms_ = 119.0;
double last_confidence_ = 0.0;
MorseRingBuffer pulse_history_{};
MorseRingBuffer pulse_gaps_{};
std::string lookupMorse(const std::string& seq) {
for (size_t i = 0; i < morse_table_size_; i++) {
if (seq == morse_table_[i].code)
return morse_table_[i].letter;
}
return "{" + seq + "}"; // not found
}
double getDahProbability(uint32_t duration_ms) {
double start_interp = 1.5 * time_unit_ms_;
double end_interp = 2.5 * time_unit_ms_;
if (duration_ms <= start_interp) return 0.0;
if (duration_ms >= end_interp) return 1.0;
return ((double)(duration_ms)-start_interp) / (end_interp - start_interp);
}
size_t findDecisionBoundary(uint32_t* sorted_data, size_t sorted_data_size) {
if (sorted_data_size < 4) return 0;
size_t best_split_index = 0;
uint32_t max_diff = 0;
for (size_t i = 1; i < sorted_data_size; ++i) {
uint32_t diff = sorted_data[i] - sorted_data[i - 1];
if (diff > sorted_data[i - 1] * 0.5 && diff > max_diff) {
max_diff = diff;
best_split_index = i;
}
}
return best_split_index;
}
bool calculatePulseUnit(double& unit, double& confidence) {
if (pulse_history_.size() < 10) return false;
uint32_t sorted_pulses[pulse_history_.size()];
pulse_history_.copy_to_array(sorted_pulses);
sort_uint32(sorted_pulses, pulse_history_.size());
size_t split_index = findDecisionBoundary(sorted_pulses, pulse_history_.size());
if (split_index == 0 || split_index < 3 || (pulse_history_.size() - split_index) < 2) {
return false;
}
double dit_sum = sum_uint32_range(sorted_pulses, 0, split_index);
double dah_sum = sum_uint32_range(sorted_pulses, split_index, pulse_history_.size());
double avg_dit = dit_sum / split_index;
double avg_dah = dah_sum / (pulse_history_.size() - split_index);
if (avg_dah <= avg_dit) return false;
double ratio = avg_dah / avg_dit;
if (ratio > 1.5 && ratio < 5.0) {
unit = avg_dit;
double tmpabs = ratio - 3.0;
if (tmpabs < 0) tmpabs *= -1;
tmpabs /= 3.0;
tmpabs = 1.0 - tmpabs;
if (tmpabs < 0) tmpabs = 0;
confidence = tmpabs; // 0..1
return true;
}
return false;
}
bool calculateGapUnit(double& unit, double& confidence) {
if (pulse_gaps_.size() < 10) return false;
double threshold = getInterElementThreshold();
double valid_gaps[pulse_gaps_.size()];
size_t valid_count = 0;
for (size_t i = 0; i < pulse_gaps_.size(); i++) {
double gap = pulse_gaps_[i];
if (gap <= threshold) {
valid_gaps[valid_count++] = gap;
}
}
if (valid_count < 2) {
return false;
}
double sum = sum_double_range(valid_gaps, 0, valid_count);
size_t count_to_average = valid_count;
if (count_to_average > 0) {
unit = sum / count_to_average;
confidence = 0.8;
return true;
}
return false;
}
double sum_uint32_range(const uint32_t* data, size_t start, size_t end) {
double sum = 0.0;
for (size_t i = start; i < end; i++) {
sum += data[i];
}
return sum;
}
double sum_double_range(const double* data, size_t start, size_t end) {
double sum = 0.0;
for (size_t i = start; i < end; i++) {
sum += data[i];
}
return sum;
}
void sort_uint32(uint32_t* data, size_t size) {
if (size < 2)
return;
for (size_t i = 1; i < size; i++) {
uint32_t key = data[i];
size_t j = i;
while (j > 0 && data[j - 1] > key) {
data[j] = data[j - 1];
j--;
}
data[j] = key;
}
}
double clamp_double(double value, double min_val, double max_val) {
if (value < min_val)
return min_val;
else if (value > max_val)
return max_val;
else
return value;
}
void updateLearning() {
double pulse_unit = -1.0, pulse_confidence = 0.0;
double gap_unit = -1.0, gap_confidence = 0.0;
bool pulse_success = calculatePulseUnit(pulse_unit, pulse_confidence);
bool gap_success = calculateGapUnit(gap_unit, gap_confidence);
double new_time_unit = -1.0;
if (pulse_success && pulse_confidence > 0.5) {
new_time_unit = pulse_unit;
} else if (pulse_success && gap_success) {
gap_confidence = 0.2;
double total_confidence = pulse_confidence + gap_confidence;
new_time_unit = (pulse_unit * pulse_confidence + gap_unit * gap_confidence) / total_confidence;
} else if (gap_success) {
new_time_unit = gap_unit;
} else {
return;
}
double max_change = time_unit_ms_ * 0.25;
new_time_unit = clamp_double(new_time_unit, time_unit_ms_ - max_change, time_unit_ms_ + max_change);
double DEFAULT_TIME_UNIT = 160.0;
double BASE_LEARNING_RATE = 0.05;
double MAX_LEARNING_RATE = 0.25;
double tudeltaabs = new_time_unit - DEFAULT_TIME_UNIT;
if (tudeltaabs < 0) tudeltaabs *= -1;
double deviation_from_default = tudeltaabs / DEFAULT_TIME_UNIT;
double tpp = deviation_from_default * 2.0;
if (tpp > 1) tpp = 1;
double learning_factor = BASE_LEARNING_RATE + (MAX_LEARNING_RATE - BASE_LEARNING_RATE) * tpp;
time_unit_ms_ = (time_unit_ms_ * (1.0 - learning_factor)) + (new_time_unit * learning_factor);
}
size_t morse_table_size_ = 50;
MorseEntry morse_table_[50] = {
{".-", "A"},
{"-...", "B"},
{"-.-.", "C"},
{"-..", "D"},
{".", "E"},
{"..-.", "F"},
{"--.", "G"},
{"....", "H"},
{"..", "I"},
{".---", "J"},
{"-.-", "K"},
{".-..", "L"},
{"--", "M"},
{"-.", "N"},
{"---", "O"},
{".--.", "P"},
{"--.-", "Q"},
{".-.", "R"},
{"...", "S"},
{"-", "T"},
{"..-", "U"},
{"...-", "V"},
{".--", "W"},
{"-..-", "X"},
{"-.--", "Y"},
{"--..", "Z"},
{".----", "1"},
{"..---", "2"},
{"...--", "3"},
{"....-", "4"},
{".....", "5"},
{"-....", "6"},
{"--...", "7"},
{"---..", "8"},
{"----.", "9"},
{"-----", "0"},
{".-.-.-", "."},
{"..--..", "?"},
{"-.-.--", "!"},
{"--..--", ","},
{"-...-", "="},
{"-..-.", "/"},
{".--.-.", "@"},
{"---...", ":"},
{"-....-", "-"},
{".----.", "'"},
{".-..-.", "\""},
{"-.--.", "("},
{"-.--.-", ")"},
{".-.-.", "+"}};
};
} // namespace ui::external_app::morseradiotx
#endif // __MORSEDECODER_HPP__
@@ -0,0 +1,437 @@
#include "ui_morse_radiotx.hpp"
using namespace portapack;
namespace ui::external_app::morseradiotx {
static msg_t tx_thread_fn(void* arg) {
auto view = reinterpret_cast<MorseRadiotxView*>(arg);
chRegSetThreadName("morse_tx_thread");
view->transmit_morse_message();
return 0;
}
MorseRadiotxView::MorseRadiotxView(ui::NavigationView& nav)
: current_timings(calculate_morse_timings(20)),
nav_(nav) {
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
add_children({&tx_view,
&field_volume,
&labels,
&options_mode,
&tone_,
&wpm_,
&txt_msg,
&btn_message,
&btn_calls,
&chk_trans,
&bandwidth,
&chk_callsgn,
&txt_last,
&console_text,
&btn_clear,
&btn_ptt});
initial_switch_config_ = get_switches_repeat_config();
SwitchesState config = initial_switch_config_;
config[toUType(Switch::Sel)] = false;
set_switches_repeat_config(config);
audio::set_rate(audio::Rate::Hz_24000);
btn_clear.on_select = [this](Button&) {
console_text.clear(true);
txt_last.set("");
};
options_mode.on_change = [this](size_t, int32_t value) {
current_mode = (uint8_t)value;
baseband::set_morsetx_config(current_mode, tone, band);
ui_toggle();
};
tone_.on_change = [this](int32_t v) {
tone = static_cast<uint32_t>(v);
baseband::set_morsetx_config(current_mode, tone, band);
};
wpm_.on_change = [this](int16_t v) {
wpm = v;
current_timings = calculate_morse_timings(wpm);
};
bandwidth.on_change = [this](float v) {
band = v;
baseband::set_morsetx_config(current_mode, tone, band);
};
options_mode.set_selected_index(current_mode, true);
tone_.set_value(tone, true);
wpm_.set_value(wpm, true);
bandwidth.set_value(band, true);
btn_ptt.on_select = [this](Button&) {
if (button_touch) {
button_touch = false;
return;
}
button_was_selected = true;
onPress();
};
btn_ptt.on_touch_press = [this](Button&) {
button_touch = true;
button_was_selected = false;
onPress();
};
btn_ptt.on_touch_release = [this](Button&) {
if (chk_trans.value() && transmit) {
button_touch = true;
button_was_selected = false;
onRelease();
}
};
btn_message.on_select = [this, &nav](Button&) {
if (!transmit)
text_prompt(nav, msg_buffer, 27, ENTER_KEYBOARD_MODE_ALPHA, [this](std::string& buffer) {
msg_buffer = buffer;
txt_msg.set("[" + msg_buffer + "] ");
});
};
btn_calls.on_select = [this, &nav](Button&) {
if (!transmit) {
text_prompt(nav, call_sign, 10, ENTER_KEYBOARD_MODE_ALPHA, [this](std::string& buffer) {
call_sign = buffer;
if (call_sign.empty())
btn_calls.set_text("call sign?");
else
btn_calls.set_text(call_sign);
});
}
};
audio::output::start();
auto vol = field_volume.value();
field_volume.set_value(0);
field_volume.set_value(vol);
tx_view.on_start = [this]() {
if (!chk_trans.value() && msg_buffer.empty()) {
tx_view.set_transmitting(false);
return;
}
tx_view.focus();
if (!tx_thread && !thread_running) {
thread_running = true;
tx_thread = chThdCreateFromHeap(NULL, 1024, NORMALPRIO + 5, tx_thread_fn, this);
tx_view.set_transmitting(true);
}
else
tx_view.set_transmitting(false);
};
tx_view.on_stop = [this]() {
baseband::set_morsetx_key(false);
transmitter_model.disable();
if (tx_thread) {
chThdTerminate(tx_thread);
chThdWait(tx_thread);
}
transmit = false;
transmit_time = 0;
tx_thread = nullptr;
thread_running = false;
tx_view.set_transmitting(false);
ui_toggle();
};
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);
};
};
}
MorseRadiotxView::~MorseRadiotxView() {
set_switches_repeat_config(initial_switch_config_);
if (tx_thread) {
chThdTerminate(tx_thread);
chThdWait(tx_thread);
if (!thread_running) tx_thread = nullptr;
}
transmitter_model.disable();
baseband::shutdown();
audio::output::stop();
}
void MorseRadiotxView::on_show() {
ptt_button_visibility(true);
start_time = 0;
end_time = 0;
transmit_time = 0;
}
void MorseRadiotxView::focus() {
options_mode.focus();
}
MorseRadiotxView::MorseTimings MorseRadiotxView::calculate_morse_timings(uint32_t wpm) {
MorseRadiotxView::MorseTimings t;
if (wpm < 10) wpm = 10;
if (wpm > 45) wpm = 45;
t.dot_ms = 1200 / wpm;
t.dash_ms = 3 * t.dot_ms;
t.symbol_gap = t.dot_ms;
t.char_gap = 3 * t.dot_ms;
t.word_gap = 7 * t.dot_ms;
return t;
}
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()) {
ptt_button_visibility(false);
return;
}
// enable transmit
if (!transmit) {
transmit = true;
transmitter_model.enable();
ui_toggle();
}
for (size_t i = 0; i < full_message.length(); i++) {
if (chThdShouldTerminate()) break;
char c = full_message[i];
std::string s_char(1, c);
// space
if (c == ' ') {
console_text.write(" ");
chThdSleepMilliseconds(current_timings.word_gap);
continue;
}
const char* pattern = morse_decoder_.get_morse_pattern(c);
if (pattern != nullptr) {
txt_last.set(pattern);
// 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;
if (current_timings.char_gap > current_timings.symbol_gap) {
chThdSleepMilliseconds(current_timings.char_gap - current_timings.symbol_gap);
}
}
}
if (chk_trans.value()) ptt_button_visibility(false);
baseband::set_morsetx_key(false);
transmit_time = chTimeNow();
decode_timeout_calc = false;
thread_running = false;
}
void MorseRadiotxView::onPress() {
start_time = chTimeNow();
if (!transmit) {
transmit = true;
transmitter_model.enable();
}
baseband::set_morsetx_key(true);
if (end_time != 0) {
int64_t gap_delta = (chTimeNow() - end_time);
auto result = morse_decoder_.handleInput(-gap_delta);
if (result.isValid()) {
writeCharToConsole(result.text, result.confidence);
}
}
end_time = 0;
transmit_time = 0;
decode_timeout_calc = false;
}
void MorseRadiotxView::onRelease() {
end_time = chTimeNow();
transmit_time = end_time;
baseband::set_morsetx_key(false);
if (start_time != 0) {
int32_t press_delta = (end_time - start_time);
auto result = morse_decoder_.handleInput(press_delta);
if (result.isValid()) {
writeCharToConsole(result.text, result.confidence);
}
}
start_time = 0;
decode_timeout_calc = true;
baseband::request_beep_stop();
}
void MorseRadiotxView::writeCharToConsole(const std::string& ch, double confidence) {
if (ch.empty()) {
return;
}
txt_last.set(morse_decoder_.getLastSequence().c_str());
last_color_id = color_id;
std::string color = "";
if (ch == " ") {
color_id = 0;
} else if (ch[0] == '{') { // no match
color_id = 0;
} else {
if (confidence == 1.5)
color_id = 4;
else if (confidence < 0.8)
color_id = 1;
else if (confidence < 0.9)
color_id = 2;
else
color_id = 3;
}
color = arr_color[color_id];
last_color_id = color_id;
console_text.write(color + ch);
}
void MorseRadiotxView::ptt_button_visibility(bool hidden) {
bool hiddenorig = btn_ptt.hidden();
if (hiddenorig != hidden) {
btn_ptt.hidden(hidden);
if (!hidden) btn_ptt.focus();
if (hidden) {
// hack fix until widget hidig problem is not solved.
auto r = btn_ptt.screen_rect();
Painter p;
p.fill_rectangle_unrolled8(r, Theme::getInstance()->fg_light->background);
}
}
}
void MorseRadiotxView::ui_toggle() {
// 0=AM, 1=FM, 2=DSB, 3=USB, 4=LSB
if (transmit) {
options_mode.set_style(Theme::getInstance()->fg_dark);
options_mode.set_focusable(false);
tone_.set_style(Theme::getInstance()->fg_dark);
tone_.set_focusable(false);
wpm_.set_style(Theme::getInstance()->fg_dark);
wpm_.set_focusable(false);
btn_message.set_style(Theme::getInstance()->fg_dark);
btn_calls.set_style(Theme::getInstance()->fg_dark);
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);
} else {
options_mode.set_style(Theme::getInstance()->bg_darker);
options_mode.set_focusable(true);
wpm_.set_style(Theme::getInstance()->bg_darker);
wpm_.set_focusable(true);
btn_message.set_style(Theme::getInstance()->bg_darker);
btn_calls.set_style(Theme::getInstance()->bg_darker);
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);
ptt_button_visibility(true);
tone_.set_style(Theme::getInstance()->bg_darker);
tone_.set_focusable(true);
if (current_mode == 1) { // FM mode
bandwidth.set_style(Theme::getInstance()->bg_darker);
bandwidth.set_focusable(true);
} else {
bandwidth.set_style(Theme::getInstance()->fg_dark);
bandwidth.set_focusable(false);
}
} // transmit false
}
inline bool MorseRadiotxView::tx_button_held() {
const auto switches_state = get_switches_state();
return switches_state[(size_t)ui::KeyEvent::Select];
}
void MorseRadiotxView::on_framesync() {
if (button_was_selected && !button_touch && !tx_button_held()) {
button_was_selected = false;
onRelease();
}
if (end_time != 0 && decode_timeout_calc) {
int64_t gap_delta = (chTimeNow() - end_time);
if (gap_delta >= morse_decoder_.getInterCharThreshold()) {
auto result = morse_decoder_.handleInput(-(int32_t)gap_delta);
if (result.isValid()) {
writeCharToConsole(result.text, result.confidence);
}
}
if (gap_delta >= morse_decoder_.getInterWordThreshold()) {
writeCharToConsole(" ", 1.0);
end_time = 0;
decode_timeout_calc = false;
}
}
if (transmit_time != 0 && transmit) { // Tx disable if time is up
int64_t gap_delta = (chTimeNow() - transmit_time);
if (gap_delta >= ((morse_decoder_.getInterWordThreshold() * ((chk_trans.value()) ? 10 : 1)))) {
if (tx_thread) {
chThdTerminate(tx_thread);
chThdWait(tx_thread);
}
transmit = false;
tx_view.set_transmitting(false);
transmitter_model.disable();
thread_running = false;
tx_thread = nullptr;
transmit_time = 0;
if (!chk_trans.value()) writeCharToConsole(" ", 1.0);
ui_toggle();
}
}
}
} // namespace ui::external_app::morseradiotx
@@ -0,0 +1,171 @@
/*
* Copyright (C) 2026 Pezsma
*
* This file is part of PortaPack.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef __MORSE_RADIOTX_H__
#define __MORSE_RADIOTX_H__
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_language.hpp"
#include "ui_painter.hpp"
#include "ui_freq_field.hpp"
#include "ui_transmitter.hpp"
#include "ui_textentry.hpp"
#include "string_format.hpp"
#include "morsedecoder.hpp"
#include "irq_controls.hpp"
#include "radio_state.hpp"
#include "portapack.hpp"
#include "message.hpp"
#include "volume.hpp"
#include "audio.hpp"
#include "baseband_api.hpp"
#include "external_app.hpp"
#include "string_format.hpp"
#include <ch.h>
#include <hal.h>
namespace ui::external_app::morseradiotx {
class MorseRadiotxView : public ui::View {
public:
MorseRadiotxView(ui::NavigationView& nav);
~MorseRadiotxView();
MorseRadiotxView(const MorseRadiotxView&) = delete;
MorseRadiotxView(MorseRadiotxView&&) = delete;
MorseRadiotxView& operator=(const MorseRadiotxView&) = delete;
MorseRadiotxView& operator=(MorseRadiotxView&&) = delete;
std::string title() const override { return "Morse Tx"; }
void focus() override;
void on_show() override;
void transmit_morse_message();
private:
struct MorseTimings {
uint32_t dot_ms;
uint32_t dash_ms;
uint32_t symbol_gap;
uint32_t char_gap;
uint32_t word_gap;
};
MorseTimings current_timings{};
std::string msg_indicator{""};
MorseTimings calculate_morse_timings(uint32_t wpm);
void onPress();
void onRelease();
void on_framesync();
void writeCharToConsole(const std::string& ch, double confidence);
void ui_toggle();
bool tx_button_held();
void ptt_button_visibility(bool hidden);
ui::NavigationView& nav_;
MorseDecoder morse_decoder_{};
TxRadioState radio_state_{};
Thread* tx_thread{nullptr};
std::string msg_buffer{"PORTAPACK"};
uint8_t current_mode{0}; // 0=AM, 1=FM, 2=DSB, 3=USB, 4=LSB
uint8_t wpm{20};
uint32_t tone{700};
float band{5.8};
std::string call_sign{""};
app_settings::SettingsManager settings_{
"tx_morseradio",
app_settings::Mode::TX,
{
{"cmode"sv, &current_mode},
{"audtone"sv, &tone},
{"wpm"sv, &wpm},
{"message"sv, &msg_buffer},
{"bandwith"sv, &band},
{"call_sign"sv, &call_sign},
}};
TransmitterView tx_view{
(int16_t)UI_POS_Y_BOTTOM(4),
10000,
0, false};
AudioVolumeField field_volume{{UI_POS_X_RIGHT(2), UI_POS_Y_BOTTOM(5)}};
ui::OptionsField options_mode{
{UI_POS_X(5), UI_POS_Y(0)},
3,
{{"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};
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};
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)}};
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"};
ui::Labels labels{
{{UI_POS_X(0), UI_POS_Y(0)}, "Mode:", Theme::getInstance()->fg_light->foreground},
{{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_RIGHT(7), UI_POS_Y_BOTTOM(5)}, "Vol.:", Theme::getInstance()->fg_light->foreground},
};
uint8_t last_color_id{255};
uint8_t color_id{255};
std::string arr_color[4] = {STR_COLOR_WHITE, STR_COLOR_RED, STR_COLOR_YELLOW, STR_COLOR_GREEN};
bool button_touch{false};
bool button_was_selected{false};
bool decode_timeout_calc{false};
bool transmit{false};
bool thread_running = false;
uint8_t send_indicator{5};
int64_t start_time{0};
int64_t end_time{0};
int64_t transmit_time{0};
SwitchesState initial_switch_config_{};
MessageHandlerRegistration message_handler_framesync{
Message::ID::DisplayFrameSync,
[this](const Message* const p) {
(void)p;
this->on_framesync();
}};
};
} // namespace ui::external_app::morseradiotx
#endif // __MORSE_RADIOTX_H__
+18 -2
View File
@@ -91,6 +91,7 @@ SubCarView::SubCarView(NavigationView& nav)
&button_clear_list,
&check_log,
&labels,
&options_mode,
&recent_entries_view});
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
@@ -114,11 +115,17 @@ SubCarView::SubCarView(NavigationView& nav)
recent_entries_view.on_select = [this](const SubCarRecentEntry& entry) {
nav_.push<SubCarRecentEntryDetailView>(entry);
};
baseband::set_subghzd_config(0, receiver_model.sampling_rate()); // 0=am
receiver_model.enable();
options_mode.on_change = [this](size_t, int32_t v) {
modulation = v;
chThdSleepMilliseconds(100); // wait for the baseband thread to process the previous config, to avoid glitchy output when switching modes
baseband::set_subghzd_config(modulation, receiver_model.sampling_rate());
};
signal_token_tick_second = rtc_time::signal_tick_second += [this]() {
on_tick_second();
};
options_mode.set_selected_index(modulation, true);
receiver_model.enable();
}
void SubCarView::on_tick_second() {
@@ -176,6 +183,8 @@ const char* SubCarView::getSensorTypeName(FPROTO_SUBCAR_SENSOR type) {
return "Fiat V0";
case FPC_BMWV0:
return "BMW V0";
/* case FPC_KIAV6:
return "Kia V6";*/
case FPC_Invalid:
default:
@@ -491,6 +500,13 @@ void SubCarRecentEntryDetailView::parseProtocol() {
btn = to_string_dec_uint(button);
}
/*if (entry_.sensorType == FPC_KIAV6) {
// not decrypted!
serial = 0;
btn = "?";
cnt = 0;
}*/
return;
}
+19 -13
View File
@@ -116,25 +116,27 @@ class SubCarView : public View {
4'000'000 /* sampling rate */,
ReceiverModel::Mode::AMAudio};
bool logging = false;
uint8_t modulation = 0;
app_settings::SettingsManager settings_{
"rx_subcar",
app_settings::Mode::RX,
{
{"log"sv, &logging},
{"modulationmode"sv, &modulation},
}};
SubCarRecentEntries recent{};
RFAmpField field_rf_amp{
{13 * 8, UI_POS_Y(0)}};
{UI_POS_X(13), UI_POS_Y(0)}};
LNAGainField field_lna{
{15 * 8, UI_POS_Y(0)}};
{UI_POS_X(15), UI_POS_Y(0)}};
VGAGainField field_vga{
{18 * 8, UI_POS_Y(0)}};
{UI_POS_X(18), UI_POS_Y(0)}};
RSSI rssi{
{21 * 8, 0, UI_POS_WIDTH_REMAINING(24), 4}};
{UI_POS_X(21), 0, UI_POS_WIDTH_REMAINING(24), 4}};
Channel channel{
{21 * 8, 5, UI_POS_WIDTH_REMAINING(24), 4},
{UI_POS_X(21), 5, UI_POS_WIDTH_REMAINING(24), 4},
};
RxFrequencyField field_frequency{
{UI_POS_X(0), UI_POS_Y(0)},
@@ -143,18 +145,22 @@ class SubCarView : public View {
SignalToken signal_token_tick_second{};
Button button_clear_list{
{0, 16, 7 * 8, 32},
{UI_POS_X(0), UI_POS_Y(1), UI_POS_WIDTH(7), UI_POS_HEIGHT(2)},
"Clear"};
Checkbox check_log{
{10 * 8, 18},
{UI_POS_X(8), UI_POS_Y(1)},
3,
"Log",
true};
Labels labels{
{{UI_POS_X_RIGHT(14), UI_POS_Y(1)}, "no fm yet :(", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(15), UI_POS_Y(1)}, "Mode:", Theme::getInstance()->fg_light->foreground},
};
ui::OptionsField options_mode{
{UI_POS_X(22), UI_POS_Y(1)},
3,
{{"AM", 0}, {"FM", 1}}};
static constexpr auto header_height = 3 * 16;
@@ -198,16 +204,16 @@ class SubCarRecentEntryDetailView : public View {
std::string btn = "";
uint32_t cnt = SD_NO_CNT;
Text text_type{{UI_POS_X(0), 1 * 16, 15 * 8, 16}, "?"};
Text text_id{{6 * 8, 2 * 16, 10 * 8, 16}, "?"};
Text text_type{{UI_POS_X(0), UI_POS_Y(1), UI_POS_WIDTH(15), UI_POS_HEIGHT(1)}, "?"};
Text text_id{{UI_POS_X(6), UI_POS_Y(2), UI_POS_WIDTH(10), UI_POS_HEIGHT(1)}, "?"};
Console console{
{0, 4 * 16, screen_width, screen_height - (4 * 16) - 36}};
{UI_POS_X(0), UI_POS_Y(4), UI_POS_MAXWIDTH, screen_height - (4 * 16) - 36}};
Labels labels{
{{UI_POS_X(0), UI_POS_Y(0)}, "Type:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), 2 * 16}, "Serial: ", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), 3 * 16}, "Data:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(2)}, "Serial: ", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(3)}, "Data:", Theme::getInstance()->fg_light->foreground},
};
Button button_done{
+2
View File
@@ -53,3 +53,5 @@ const std::filesystem::path hopper_dir = u"HOPPER";
const std::filesystem::path subghz_dir = u"SUBGHZ";
const std::filesystem::path waterfalls_dir = u"WATERFALLS";
const std::filesystem::path macaddress_dir = u"MACADDRESS";
const std::filesystem::path keeloq_keys_dir = u"KEELOQKEYS";
const std::filesystem::path keeloq_remotes_dir = u"KEELOQREMOTES";
+2
View File
@@ -55,5 +55,7 @@ extern const std::filesystem::path hopper_dir;
extern const std::filesystem::path subghz_dir;
extern const std::filesystem::path waterfalls_dir;
extern const std::filesystem::path macaddress_dir;
extern const std::filesystem::path keeloq_keys_dir;
extern const std::filesystem::path keeloq_remotes_dir;
#endif /* __FILE_PATH_H__ */
+2 -2
View File
@@ -122,7 +122,7 @@ options_t freqman_steps = {
{"1kHz ", 1000},
{"5kHz (SA AM)", 5000},
{"6.25kHz(NFM)", 6250},
{"8.33kHz(AIR)", 8330},
{"8.33kHz(AIR)", 8333},
{"9kHz (EU AM)", 9000},
{"10kHz(US AM)", 10000},
{"12.5kHz(NFM)", 12500},
@@ -144,7 +144,7 @@ options_t freqman_steps_short = {
{"1kHz", 1000},
{"5kHz", 5000},
{"6.25kHz", 6250},
{"8.33kHz", 8330},
{"8.33kHz", 8333},
{"9kHz", 9000},
{"10kHz", 10000},
{"12.5kHz", 12500},
+56
View File
@@ -0,0 +1,56 @@
#include "gpio_lpc.h"
typedef enum {
LED1 = 0,
LED2 = 1,
LED3 = 2,
LED4 = 3,
} led_t;
/* GPIO Output PinMux */
static struct gpio_t gpio_led[] = {
GPIO(2, 1),
GPIO(2, 2),
GPIO(2, 8),
#ifdef RAD1O
GPIO(5, 26),
#endif
};
void delay(uint32_t duration) {
while (duration--) {
/* cannot be optimized out */
__asm__ volatile("nop");
}
}
void delay_us_at_mhz(uint32_t us, uint32_t mhz) {
/* overflow-safe multiply */
uint64_t cycles64 = (uint64_t)us * (uint64_t)mhz;
if (cycles64 > UINT32_MAX) {
cycles64 = UINT32_MAX;
}
delay((uint32_t)cycles64);
}
void led_on(const led_t led) {
gpio_set(&gpio_led[led]);
}
void led_off(const led_t led) {
gpio_clear(&gpio_led[led]);
}
void halt_and_flash(const uint32_t duration) {
/* blink LED1, LED2, and LED3 */
while (1) {
led_on(LED1);
led_on(LED2);
led_on(LED3);
delay(duration);
led_off(LED1);
led_off(LED2);
led_off(LED3);
delay(duration);
}
}
+8
View File
@@ -37,6 +37,14 @@ void Debounce::enable_repeat() {
repeat_enabled_ = true;
}
void Debounce::set_enable_repeat(bool enabled) {
repeat_enabled_ = enabled;
}
bool Debounce::get_repeat_enabled() {
return repeat_enabled_;
}
bool Debounce::get_long_press_enabled() const {
return long_press_enabled_;
}
+2
View File
@@ -43,6 +43,8 @@ class Debounce {
bool feed(const uint8_t bit);
uint8_t state();
void enable_repeat();
void set_enable_repeat(bool enabled);
bool get_repeat_enabled();
bool get_long_press_enabled() const;
void set_long_press_enabled(bool v);
bool long_press_occurred();
+441
View File
@@ -0,0 +1,441 @@
/*
* Copyright (C) 2025 Great Scott Gadgets
*
* 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.
*/
/*
* MAX2831 driver ported from GSG HackRF reference implementation (max2831.c).
* Adapted to work with Mayhem's MAX283x abstraction layer.
*/
#ifdef PRALINE
#include "max2831.hpp"
#include "hackrf_hal.hpp"
#include "hackrf_gpio.hpp"
using namespace hackrf::one;
#include "ch.h"
#include "hal.h"
#include <algorithm>
#include <cstring>
namespace max2831 {
using namespace max283x;
/*
* MAX2831 uses 9-bit SPI transfers.
* An 18-bit word is sent as two 9-bit transfers:
* Word format: [VALUE:14][REG:4]
* First transfer: bits 17:9 (high 9 bits)
* Second transfer: bits 8:0 (low 9 bits)
*
* This matches the GSG reference implementation exactly.
*/
void MAX2831::write_reg(const uint8_t reg, const uint16_t value) {
uint32_t word = (((uint32_t)value & 0x3fff) << 4) | (reg & 0xf);
uint16_t values[2] = {
static_cast<uint16_t>(word >> 9),
static_cast<uint16_t>(word & 0x1ff)};
_target.transfer(values, 2);
}
void MAX2831::set_reg_field(const uint8_t reg, const uint16_t mask, const uint16_t value) {
_regs[reg] = (_regs[reg] & ~mask) | (value & mask);
mark_dirty(reg);
}
uint16_t MAX2831::get_reg_field(const uint8_t reg, const uint16_t mask, const uint8_t shift) {
return (_regs[reg] & mask) >> shift;
}
void MAX2831::mark_dirty(const uint8_t reg) {
_regs_dirty |= (1 << reg);
}
void MAX2831::mark_clean(const uint8_t reg) {
_regs_dirty &= ~(1 << reg);
}
void MAX2831::flush_reg(const uint8_t reg) {
write_reg(reg, _regs[reg]);
mark_clean(reg);
}
void MAX2831::flush_dirty() {
for (size_t r = 0; r < reg_count; r++) {
if ((_regs_dirty >> r) & 0x1) {
flush_reg(r);
}
}
}
void MAX2831::init() {
set_mode(Mode::Shutdown);
/* Configure GPIO pins for MAX2831 control */
gpio_max283x_enable.output();
gpio_max2831_rx_enable.output();
gpio_max2831_rxhp.output();
gpio_max2831_rxhp.write(0); /* RXHP low = 100 Hz HPF (default) */
/* Reset to default register values */
std::memcpy(_regs.data(), default_regs.data(), sizeof(_regs));
_regs_dirty = 0xFFFF;
/* Write default register values to chip */
flush_dirty();
/* Use SPI control instead of B1-B7 pins for gain settings.
* This matches the GSG reference: max2831_setup() */
set_reg_field(8, REG8_RXVGA_GAIN_SPI_EN, REG8_RXVGA_GAIN_SPI_EN);
set_reg_field(9, REG9_TXVGA_GAIN_SPI_EN, REG9_TXVGA_GAIN_SPI_EN);
/* Set initial gains - matches GSG reference */
set_reg_field(12, REG12_TXVGA_GAIN_MASK, 0x00); /* Minimum TX gain */
set_reg_field(7, REG7_RX_HPF_SEL_MASK, REG7_RX_HPF_30KHZ);
set_reg_field(11, REG11_LNA_GAIN_MASK, REG11_LNA_GAIN_MAX);
set_reg_field(11, REG11_RXVGA_GAIN_MASK, 0x18); // Moderate RX VGA gain
/* FORCE MAXIMUM GAIN FOR TESTING */
// set_reg_field(11, REG11_RXVGA_GAIN_MASK, 0x1F); // 62 dB VGA = MAX
/* Configure baseband filter for 8 MHz TX - matches GSG reference */
set_reg_field(8, REG8_LPF_COARSE_MASK, REG8_RX_LPF_7_5M);
set_reg_field(7, REG7_RX_LPF_FINE_MASK, REG7_RX_LPF_FINE_100);
set_reg_field(7, REG7_TX_LPF_FINE_MASK, REG7_TX_LPF_FINE_100);
/* Disable clock output */
set_reg_field(14, REG14_CLKOUT_PIN_EN, 0);
/* Write all modified registers */
flush_dirty();
set_mode(Mode::Standby);
}
void MAX2831::set_mode(const Mode mode) {
_mode = mode;
/*
* MAX2831 mode control via ENABLE and RXTX pins.
* From GSG hackrf max2831_target.c:
*
* Shutdown: ENABLE=0, RXTX=0
* Standby: ENABLE=0, RXTX=1 (PLL/VCO/LO on, ready for quick TX/RX)
* RX: ENABLE=1, RXTX=0
* TX: ENABLE=1, RXTX=1
*
* Note: gpio_max2831_rx_enable is the RXTX mode select pin.
* RXTX=0 selects RX, RXTX=1 selects TX.
*/
/* Handle calibration mode bits if needed */
bool tx_cal = (mode == Mode::Tx_Calibration);
bool rx_cal = (mode == Mode::Rx_Calibration);
uint16_t current_tx_cal = get_reg_field(6, REG6_TX_CAL_MODE_EN, REG6_TX_CAL_MODE_EN_SHIFT);
uint16_t current_rx_cal = get_reg_field(6, REG6_RX_CAL_MODE_EN, REG6_RX_CAL_MODE_EN_SHIFT);
if (current_tx_cal != (tx_cal ? 1 : 0)) {
set_reg_field(6, REG6_TX_CAL_MODE_EN, tx_cal ? REG6_TX_CAL_MODE_EN : 0);
flush_dirty();
}
if (current_rx_cal != (rx_cal ? 1 : 0)) {
set_reg_field(6, REG6_RX_CAL_MODE_EN, rx_cal ? REG6_RX_CAL_MODE_EN : 0);
flush_dirty();
}
switch (mode) {
default:
case Mode::Shutdown:
gpio_max2831_rx_enable.write(0); /* RXTX=0 */
gpio_max283x_enable.write(0); /* ENABLE=0 */
break;
case Mode::Standby:
gpio_max2831_rx_enable.write(1); /* RXTX=1 */
gpio_max283x_enable.write(0); /* ENABLE=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 */
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 */
break;
}
/* Update LPF bandwidth for current mode */
if (_desired_lpf_bw > 0) {
set_lpf_bandwidth_internal(_desired_lpf_bw);
}
}
void MAX2831::set_tx_vga_gain(const int_fast8_t db) {
/* TX VGA gain: 0-31 dB in ~1 dB steps
* Register value: gain * 2 | 1, max 0x3F
* This matches GSG reference: max2831_set_txvga_gain() */
int_fast8_t db_clipped = std::max(0, std::min(31, (int)db));
uint16_t value = std::min((db_clipped << 1) | 1, 0x3f);
set_reg_field(12, REG12_TXVGA_GAIN_MASK, value);
flush_reg(12);
}
void MAX2831::set_lna_gain(const int_fast8_t db) {
/*
* LNA gain has 3 settings (from GSG reference):
* MAX (33 dB), -16 dB from max (17 dB), -33 dB from max (0 dB)
* Map from MAX2837 8 dB steps for compatibility
*/
uint16_t gain_val;
if (db >= 32) {
gain_val = REG11_LNA_GAIN_MAX;
} else if (db >= 16) {
gain_val = REG11_LNA_GAIN_M16;
} else {
gain_val = REG11_LNA_GAIN_M33;
}
set_reg_field(11, REG11_LNA_GAIN_MASK, gain_val);
flush_reg(11);
}
void MAX2831::set_vga_gain(const int_fast8_t db) {
/* VGA gain: 0-62 dB in 2 dB steps
* This matches GSG reference: max2831_set_vga_gain() */
if ((db & 0x1) || db > 62) {
return; /* Invalid: must be even and <= 62 */
}
int_fast8_t db_clipped = std::max(0, std::min(62, (int)db));
uint16_t value = (db_clipped >> 1) & 0x1f;
set_reg_field(11, REG11_RXVGA_GAIN_MASK, value);
flush_reg(11);
}
/*
* LPF bandwidth tables from GSG reference max2831.c
*/
struct lpf_ft_t {
uint32_t bandwidth_hz;
uint8_t ft;
};
struct lpf_ft_fine_t {
uint8_t percent;
uint8_t ft_fine;
};
/* Measured -0.5 dB complex baseband bandwidth for each register setting */
static constexpr lpf_ft_t rx_lpf_ft[] = {
{11600000, REG8_RX_LPF_7_5M},
{15100000, REG8_RX_LPF_8_5M},
{22600000, REG8_RX_LPF_15M},
{28300000, REG8_RX_LPF_18M},
{0, 0},
};
static constexpr lpf_ft_fine_t rx_lpf_ft_fine[] = {
{90, REG7_RX_LPF_FINE_90},
{95, REG7_RX_LPF_FINE_95},
{100, REG7_RX_LPF_FINE_100},
{105, REG7_RX_LPF_FINE_105},
{110, REG7_RX_LPF_FINE_110},
{0, 0},
};
static constexpr lpf_ft_t tx_lpf_ft[] = {
{11900000, REG8_TX_LPF_8M},
{15800000, REG8_TX_LPF_11M},
{23600000, REG8_TX_LPF_16_5M},
{31300000, REG8_TX_LPF_22_5M},
{0, 0},
};
static constexpr lpf_ft_fine_t tx_lpf_ft_fine[] = {
{90, REG7_TX_LPF_FINE_90},
{95, REG7_TX_LPF_FINE_95},
{100, REG7_TX_LPF_FINE_100},
{105, REG7_TX_LPF_FINE_105},
{110, REG7_TX_LPF_FINE_110},
{115, REG7_TX_LPF_FINE_115},
{0, 0},
};
uint32_t MAX2831::set_lpf_bandwidth_internal(const uint32_t bandwidth_hz) {
const lpf_ft_t* coarse;
const lpf_ft_fine_t* fine;
if (_mode == Mode::Receive || _mode == Mode::Rx_Calibration) {
coarse = rx_lpf_ft;
fine = rx_lpf_ft_fine;
} else {
coarse = tx_lpf_ft;
fine = tx_lpf_ft_fine;
}
/* Find coarse and fine settings for LPF - matches GSG reference */
bool found = false;
const lpf_ft_fine_t* f = fine;
for (; coarse->bandwidth_hz != 0; coarse++) {
uint32_t coarse_aux = coarse->bandwidth_hz / 100;
for (f = fine; f->percent != 0; f++) {
if ((coarse_aux * f->percent) >= bandwidth_hz) {
found = true;
break;
}
}
if (found) break;
}
/* Use the widest setting if a wider bandwidth than our maximum is requested */
if (!found) {
coarse--;
f--;
}
/* Program found settings */
set_reg_field(8, REG8_LPF_COARSE_MASK, coarse->ft);
if (_mode == Mode::Receive || _mode == Mode::Rx_Calibration) {
set_reg_field(7, REG7_RX_LPF_FINE_MASK, f->ft_fine);
} else {
/* TX fine values are already shifted in the constants (REG7_TX_LPF_FINE_*) */
set_reg_field(7, REG7_TX_LPF_FINE_MASK, f->ft_fine);
}
flush_dirty();
return coarse->bandwidth_hz * f->percent / 100;
}
void MAX2831::set_lpf_rf_bandwidth_rx(const uint32_t bandwidth_minimum) {
_desired_lpf_bw = bandwidth_minimum;
if (_mode == Mode::Receive || _mode == Mode::Rx_Calibration) {
set_lpf_bandwidth_internal(bandwidth_minimum);
}
}
void MAX2831::set_lpf_rf_bandwidth_tx(const uint32_t bandwidth_minimum) {
_desired_lpf_bw = bandwidth_minimum;
if (_mode == Mode::Transmit || _mode == Mode::Tx_Calibration) {
set_lpf_bandwidth_internal(bandwidth_minimum);
}
}
bool MAX2831::set_frequency(const rf::Frequency lo_frequency) {
/*
* MAX2831 frequency synthesis from GSG reference max2831_set_frequency():
* F_LO = F_REF * (N + F/2^20) / R
* Where:
* F_REF = 40 MHz reference
* R = reference divider (1 or 2), we use R=2
* N = integer divider (8 bits)
* F = fractional divider (20 bits)
*
* Using R=2: F_LO = 40M * (N + F/2^20) / 2 = 20M * (N + F/2^20)
*/
/* MAX2831 supports 2.3-2.6 GHz */
if (lo_frequency < 2300000000ULL || lo_frequency > 2600000000ULL) {
return false;
}
/* From GSG reference: ASSUME 40MHz PLL. Ratio = F*R/40,000,000.
* TODO: fixed to R=2. Check if it's worth exploring R=1. */
uint32_t freq = lo_frequency;
freq += (20000000 >> 21); /* Round to nearest frequency */
uint32_t div_int = freq / 20000000;
uint32_t div_rem = freq % 20000000;
uint32_t div_frac = 0;
uint32_t div_cmp = 20000000;
for (int i = 0; i < 20; i++) {
div_frac <<= 1;
div_rem <<= 1;
if (div_rem >= div_cmp) {
div_frac |= 0x1;
div_rem -= div_cmp;
}
}
/* Write order matters - matches GSG reference */
/* REG 3: SYN_INT (bits 7:0) and SYN_FRAC_LO (bits 13:8) */
uint16_t reg3_val = (div_int & 0xFF) | ((div_frac & 0x3F) << 8);
_regs[3] = reg3_val;
mark_dirty(3);
/* REG 4: SYN_FRAC_HI (bits 13:0) - upper 14 bits of 20-bit fractional */
uint16_t reg4_val = (div_frac >> 6) & 0x3FFF;
_regs[4] = reg4_val;
mark_dirty(4);
flush_dirty();
return true;
}
void MAX2831::set_rx_LO_iq_phase_calibration(const size_t v) {
/* MAX2831 doesn't have the same IQ calibration as MAX2837 */
(void)v;
}
void MAX2831::set_tx_LO_iq_phase_calibration(const size_t v) {
/* MAX2831 doesn't have the same IQ calibration as MAX2837 */
(void)v;
}
void MAX2831::set_rx_buff_vcm(const size_t v) {
/* MAX2831 RX IQ common mode voltage is in register 15
* Values: 0=1.1V, 1=1.2V, 2=1.3V, 3=1.45V */
uint16_t vcm = std::min(v, (size_t)3) << REG15_RXIQ_VCM_SHIFT;
set_reg_field(15, REG15_RXIQ_VCM_MASK, vcm);
flush_reg(15);
}
int8_t MAX2831::temp_sense() {
/* MAX2831 temperature sensor can be read via RSSI MUX.
* This would require:
* 1. Switch RSSI_MUX to temperature mode
* 2. Read the ADC
* 3. Switch back to RSSI mode
* For now, return a placeholder value. */
return 25; /* Room temperature placeholder */
}
reg_t MAX2831::read(const address_t reg_num) {
/* MAX2831 doesn't support SPI read, return cached value */
if (reg_num < reg_count) {
return _regs[reg_num];
}
return 0;
}
void MAX2831::write(const address_t reg_num, const reg_t value) {
if (reg_num < reg_count) {
_regs[reg_num] = value & 0x3FFF; /* 14-bit registers */
write_reg(reg_num, _regs[reg_num]);
mark_clean(reg_num);
}
}
} // namespace max2831
#endif
+220
View File
@@ -0,0 +1,220 @@
/*
* Copyright (C) 2025 Great Scott Gadgets
*
* 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.
*/
/*
* MAX2831 driver ported from GSG HackRF reference implementation.
* Register definitions match max2831_regs.def from hackrf firmware.
*/
#ifndef __MAX2831_H__
#define __MAX2831_H__
#include "max283x.hpp"
#include "gpio.hpp"
#include "spi_arbiter.hpp"
#include <cstdint>
#include <array>
namespace max2831 {
using namespace max283x;
/* MAX2831 has 16 registers, each containing 14 bits of data */
constexpr size_t reg_count = 16;
/* Default register values from GSG HackRF reference (max2831.c) */
constexpr std::array<uint16_t, reg_count> default_regs = {
0x1740, /* 0: enable fractional mode (Table 16 recommends 0x0740, clearing unknown bit) */
0x119a, /* 1 */
0x1003, /* 2 */
0x0079, /* 3: PLL divider settings for 2437 MHz */
0x3666, /* 4: PLL divider settings for 2437 MHz */
0x00a4, /* 5: divide reference frequency by 2 */
0x0060, /* 6: enable TX power detector */
0x1022, /* 7: 110% TX LPF bandwidth */
0x2021, /* 8: pin control of RX gain, 11 MHz LPF bandwidth */
0x03b5, /* 9: pin control of TX gain */
0x1d80, /* 10: 3.5 us PA enable delay, zero PA bias */
0x0074, /* 11: LNA high gain, RX VGA moderate gain (Table 27 recommends 0x007f, maximum gain) */
0x0140, /* 12: TX VGA minimum */
0x0e92, /* 13 */
0x0100, /* 14: reference clock output disabled */
0x0145, /* 15: RX IQ common mode 1.1 V */
};
/*
* Register bit field definitions from max2831_regs.def
* Format: REG<num>_<field>_<info>
*/
/* REG 0: PLL Mode */
constexpr uint16_t REG0_PLL_MODE_SHIFT = 10;
constexpr uint16_t REG0_PLL_MODE_MASK = (1 << REG0_PLL_MODE_SHIFT);
constexpr uint16_t REG0_PLL_MODE_INTEGER = 0;
constexpr uint16_t REG0_PLL_MODE_FRACTIONAL = 1;
/* REG 3: Synthesizer Integer and Fractional Low */
constexpr uint16_t REG3_SYN_INT_SHIFT = 0;
constexpr uint16_t REG3_SYN_INT_MASK = 0x00FF; /* D7:D0 - Integer divider (8 bits) */
constexpr uint16_t REG3_SYN_FRAC_LO_SHIFT = 8;
constexpr uint16_t REG3_SYN_FRAC_LO_MASK = 0x3F00; /* D13:D8 - Low 6 bits of fractional divider */
/* REG 4: Synthesizer Fractional High */
constexpr uint16_t REG4_SYN_FRAC_HI_MASK = 0x3FFF; /* D13:D0 - High 14 bits of fractional divider */
/* REG 5: Reference Divider and Lock Detect */
constexpr uint16_t REG5_SYN_REF_DIV_SHIFT = 2;
constexpr uint16_t REG5_SYN_REF_DIV_1 = (0 << REG5_SYN_REF_DIV_SHIFT);
constexpr uint16_t REG5_SYN_REF_DIV_2 = (1 << REG5_SYN_REF_DIV_SHIFT);
/* REG 6: Calibration Mode */
constexpr uint16_t REG6_RX_CAL_MODE_EN_SHIFT = 0;
constexpr uint16_t REG6_RX_CAL_MODE_EN = (1 << REG6_RX_CAL_MODE_EN_SHIFT);
constexpr uint16_t REG6_TX_CAL_MODE_EN_SHIFT = 1;
constexpr uint16_t REG6_TX_CAL_MODE_EN = (1 << REG6_TX_CAL_MODE_EN_SHIFT);
constexpr uint16_t REG6_TX_POWER_DETECT_EN_SHIFT = 6;
constexpr uint16_t REG6_TX_POWER_DETECT_EN = (1 << REG6_TX_POWER_DETECT_EN_SHIFT);
/* REG 7: LPF Fine Adjustment and RX HPF */
constexpr uint16_t REG7_RX_LPF_FINE_SHIFT = 0;
constexpr uint16_t REG7_RX_LPF_FINE_MASK = 0x0007; /* D2:D0 */
constexpr uint16_t REG7_RX_LPF_FINE_90 = 0;
constexpr uint16_t REG7_RX_LPF_FINE_95 = 1;
constexpr uint16_t REG7_RX_LPF_FINE_100 = 2;
constexpr uint16_t REG7_RX_LPF_FINE_105 = 3;
constexpr uint16_t REG7_RX_LPF_FINE_110 = 4;
constexpr uint16_t REG7_TX_LPF_FINE_SHIFT = 3;
constexpr uint16_t REG7_TX_LPF_FINE_MASK = 0x0038; /* D5:D3 */
constexpr uint16_t REG7_TX_LPF_FINE_90 = (0 << REG7_TX_LPF_FINE_SHIFT);
constexpr uint16_t REG7_TX_LPF_FINE_95 = (1 << REG7_TX_LPF_FINE_SHIFT);
constexpr uint16_t REG7_TX_LPF_FINE_100 = (2 << REG7_TX_LPF_FINE_SHIFT);
constexpr uint16_t REG7_TX_LPF_FINE_105 = (3 << REG7_TX_LPF_FINE_SHIFT);
constexpr uint16_t REG7_TX_LPF_FINE_110 = (4 << REG7_TX_LPF_FINE_SHIFT);
constexpr uint16_t REG7_TX_LPF_FINE_115 = (5 << REG7_TX_LPF_FINE_SHIFT);
constexpr uint16_t REG7_RX_HPF_SEL_SHIFT = 12;
constexpr uint16_t REG7_RX_HPF_SEL_MASK = 0x3000; /* D13:D12 */
constexpr uint16_t REG7_RX_HPF_100HZ = (0 << REG7_RX_HPF_SEL_SHIFT);
constexpr uint16_t REG7_RX_HPF_4KHZ = (1 << REG7_RX_HPF_SEL_SHIFT);
constexpr uint16_t REG7_RX_HPF_30KHZ = (2 << REG7_RX_HPF_SEL_SHIFT);
/* REG 8: LPF Coarse, RSSI MUX, and RX VGA SPI Enable */
constexpr uint16_t REG8_LPF_COARSE_SHIFT = 0;
constexpr uint16_t REG8_LPF_COARSE_MASK = 0x0003; /* D1:D0 */
/* RX and TX share the same coarse LPF setting bits */
constexpr uint16_t REG8_RX_LPF_7_5M = 0;
constexpr uint16_t REG8_RX_LPF_8_5M = 1;
constexpr uint16_t REG8_RX_LPF_15M = 2;
constexpr uint16_t REG8_RX_LPF_18M = 3;
constexpr uint16_t REG8_TX_LPF_8M = 0;
constexpr uint16_t REG8_TX_LPF_11M = 1;
constexpr uint16_t REG8_TX_LPF_16_5M = 2;
constexpr uint16_t REG8_TX_LPF_22_5M = 3;
constexpr uint16_t REG8_RSSI_MUX_SHIFT = 8;
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_RXVGA_GAIN_SPI_EN_SHIFT = 12;
constexpr uint16_t REG8_RXVGA_GAIN_SPI_EN = (1 << REG8_RXVGA_GAIN_SPI_EN_SHIFT);
/* REG 9: TX VGA SPI Enable */
constexpr uint16_t REG9_TXVGA_GAIN_SPI_EN_SHIFT = 10;
constexpr uint16_t REG9_TXVGA_GAIN_SPI_EN = (1 << REG9_TXVGA_GAIN_SPI_EN_SHIFT);
/* REG 11: RX Gain */
constexpr uint16_t REG11_RXVGA_GAIN_SHIFT = 0;
constexpr uint16_t REG11_RXVGA_GAIN_MASK = 0x001F; /* D4:D0 - 5 bits */
constexpr uint16_t REG11_LNA_GAIN_SHIFT = 5;
constexpr uint16_t REG11_LNA_GAIN_MASK = 0x0060; /* D6:D5 - 2 bits */
constexpr uint16_t REG11_LNA_GAIN_M33 = (0 << REG11_LNA_GAIN_SHIFT); /* -33 dB from max (min) */
constexpr uint16_t REG11_LNA_GAIN_M16 = (2 << REG11_LNA_GAIN_SHIFT); /* -16 dB from max */
constexpr uint16_t REG11_LNA_GAIN_MAX = (3 << REG11_LNA_GAIN_SHIFT); /* Maximum LNA gain */
/* REG 12: TX VGA Gain */
constexpr uint16_t REG12_TXVGA_GAIN_SHIFT = 0;
constexpr uint16_t REG12_TXVGA_GAIN_MASK = 0x003F; /* D5:D0 - 6 bits */
/* REG 14: Clock Output */
constexpr uint16_t REG14_CLKOUT_PIN_EN_SHIFT = 9;
constexpr uint16_t REG14_CLKOUT_PIN_EN = (1 << REG14_CLKOUT_PIN_EN_SHIFT);
/* REG 15: RX IQ Common Mode */
constexpr uint16_t REG15_RXIQ_VCM_SHIFT = 10;
constexpr uint16_t REG15_RXIQ_VCM_MASK = 0x0C00; /* D11:D10 - 2 bits */
constexpr uint16_t REG15_RXIQ_VCM_1_1 = (0 << REG15_RXIQ_VCM_SHIFT); /* 1.1V */
constexpr uint16_t REG15_RXIQ_VCM_1_2 = (1 << REG15_RXIQ_VCM_SHIFT); /* 1.2V */
constexpr uint16_t REG15_RXIQ_VCM_1_3 = (2 << REG15_RXIQ_VCM_SHIFT); /* 1.3V */
constexpr uint16_t REG15_RXIQ_VCM_1_45 = (3 << REG15_RXIQ_VCM_SHIFT); /* 1.45V */
class MAX2831 : public MAX283x {
public:
constexpr MAX2831(
spi::arbiter::Target& target)
: _target(target) {
}
void init() override;
void set_mode(const Mode mode) override;
void set_tx_vga_gain(const int_fast8_t db) override;
void set_lna_gain(const int_fast8_t db) override;
void set_vga_gain(const int_fast8_t db) override;
void set_lpf_rf_bandwidth_rx(const uint32_t bandwidth_minimum) override;
void set_lpf_rf_bandwidth_tx(const uint32_t bandwidth_minimum) override;
bool set_frequency(const rf::Frequency lo_frequency) override;
void set_rx_LO_iq_phase_calibration(const size_t v) override;
void set_tx_LO_iq_phase_calibration(const size_t v) override;
void set_rx_buff_vcm(const size_t v) override;
int8_t temp_sense() override;
reg_t read(const address_t reg_num) override;
void write(const address_t reg_num, const reg_t value) override;
private:
spi::arbiter::Target& _target;
Mode _mode{Mode::Standby};
std::array<uint16_t, reg_count> _regs{default_regs};
uint16_t _regs_dirty{0xFFFF}; /* Track which registers need to be written */
uint32_t _desired_lpf_bw{0}; /* Desired LPF bandwidth in Hz */
void write_reg(const uint8_t reg, const uint16_t value);
void set_reg_field(const uint8_t reg, const uint16_t mask, const uint16_t value);
uint16_t get_reg_field(const uint8_t reg, const uint16_t mask, const uint8_t shift);
void mark_dirty(const uint8_t reg);
void mark_clean(const uint8_t reg);
void flush_reg(const uint8_t reg);
void flush_dirty();
uint32_t set_lpf_bandwidth_internal(const uint32_t bandwidth_hz);
};
} // namespace max2831
#endif /*__MAX2831_H__*/
+67
View File
@@ -31,6 +31,24 @@ using namespace hackrf::one;
#include "hal.h"
#ifdef PRALINE
// Global debug tracking - visible to other files
struct rffc507x_debug_t {
uint32_t requested_freq_mhz;
uint32_t calculated_vco_mhz;
uint32_t expected_n;
uint8_t expected_lodiv;
uint8_t expected_presc;
bool was_called;
uint32_t calc_lo_freq_mhz; // Input to calculate()
uint32_t calc_vco_inside_mhz; // VCO calculated inside calculate()
uint8_t calc_lodiv_log2; // LO divider log2
uint8_t calc_presc_log2; // Prescaler log2
uint64_t calc_n_q24; // N in Q24 format before shift
};
rffc507x_debug_t rffc507x_debug_info = {0, 0, 0, 0, 0, false, 0, 0, 0, 0, 0};
#endif
namespace rffc507x {
/* Empirical tests indicate no minimum reset pulse width, but the speed
@@ -96,9 +114,31 @@ constexpr size_t divider_min = 1U << divider_log2_min;
constexpr size_t divider_max = 1U << divider_log2_max;
constexpr size_t divider_log2(const rf::Frequency vco_frequency) {
#ifdef PRALINE
// PRALINE FIX: Avoid N register overflow (9-bit max = 511)
// With 40 MHz reference:
// - For VCO=5400 MHz, presc=÷2: N = (5400×2)/40 = 270 ✓
// - For VCO=5400 MHz, presc=÷4: N = (5400×4)/40 = 540 ✗ OVERFLOW!
//
// Maximum safe VCO for ÷4 prescaler:
// N_max = 511, so VCO_max = (511 × 40) / 4 = 5110 MHz
//
// Use ÷4 only if VCO < 5110 MHz AND VCO > 3200 MHz
// Use ÷2 for VCO >= 5110 MHz to avoid overflow
constexpr rf::Frequency overflow_threshold = 5110000000ULL; // Max VCO for ÷4
constexpr rf::Frequency min_presc4_freq = 3200000000ULL; // Min VCO for ÷4
if ((vco_frequency > min_presc4_freq) && (vco_frequency < overflow_threshold)) {
return divider_log2_max; // ÷4 prescaler
} else {
return divider_log2_min; // ÷2 prescaler
}
#else
return (vco_frequency > (prescaler::divider_min * prescaler::max_frequency))
? prescaler::divider_log2_max
: prescaler::divider_log2_min;
#endif
}
} /* namespace prescaler */
@@ -121,9 +161,22 @@ struct SynthConfig {
const size_t prescaler_divider_log2 = prescaler::divider_log2(vco_frequency);
#ifndef PRALINE
const uint64_t prescaled_lo_q24 = vco_frequency << (24 - prescaler_divider_log2);
#else
const uint64_t prescaled_lo_q24 = vco_frequency << (24 + prescaler_divider_log2);
#endif
const uint64_t n_divider_q24 = prescaled_lo_q24 / reference_frequency;
#ifdef PRALINE
// DEBUG: Track everything
rffc507x_debug_info.calc_lo_freq_mhz = lo_frequency / 1000000;
rffc507x_debug_info.calc_vco_inside_mhz = vco_frequency / 1000000;
rffc507x_debug_info.calc_lodiv_log2 = lo_divider_log2;
rffc507x_debug_info.calc_presc_log2 = prescaler_divider_log2;
rffc507x_debug_info.calc_n_q24 = n_divider_q24;
#endif
return {
lo_divider_log2,
prescaler_divider_log2,
@@ -233,6 +286,20 @@ void RFFC507x::set_mixer_current(const uint8_t value) {
void RFFC507x::set_frequency(const rf::Frequency lo_frequency) {
const SynthConfig synth_config = SynthConfig::calculate(lo_frequency);
#ifdef PRALINE
// Calculate VCO frequency from LO frequency and divider
const size_t lo_divider = 1U << synth_config.lo_divider_log2; // 2^lodiv_log2
const rf::Frequency vco_freq = lo_frequency * lo_divider;
// Track what we calculated
rffc507x_debug_info.requested_freq_mhz = lo_frequency / 1000000;
rffc507x_debug_info.calculated_vco_mhz = vco_freq / 1000000;
rffc507x_debug_info.expected_n = synth_config.n_divider_q24 >> 24;
rffc507x_debug_info.expected_lodiv = synth_config.lo_divider_log2;
rffc507x_debug_info.expected_presc = synth_config.prescaler_divider_log2;
rffc507x_debug_info.was_called = true;
#endif
/* Boost charge pump leakage if VCO frequency > 3.2GHz, indicated by
* prescaler divider set to 4 (log2=2) instead of 2 (log2=1).
*/
+17
View File
@@ -57,7 +57,15 @@ void Si5351::reset() {
write_register(Register::CrystalInternalLoadCapacitance, 0b11010010);
write_register(Register::FanoutEnable, 0x00);
#ifndef PRALINE
reset_plls();
#endif
// NOTE: Do NOT call reset_plls() here!
// Multisynth registers are not yet configured at this point.
// Resetting PLLs with power-on default multisynth values (divider=6)
// causes Si5351 to output wrong frequencies (66.666 MHz instead of 8 MHz).
// The PLL reset should happen in init_clock_generator() AFTER multisynths
// are properly configured. This matches HackRF reference firmware.
}
Si5351::regvalue_t Si5351::read_register(const uint8_t reg) {
@@ -93,7 +101,16 @@ void Si5351::set_ms_frequency(
.r_div = r_div,
};
const auto regs = ms.reg(ms_number);
#ifdef PRALINE
/* PRALINE: Use single-byte writes - multi-byte I2C writes seem to fail */
const uint8_t base_reg = regs[0];
for (size_t i = 1; i < regs.size(); i++) {
write_register(base_reg + i - 1, regs[i]);
}
#else
write(regs);
#endif
}
} /* namespace si5351 */
+27 -2
View File
@@ -361,7 +361,16 @@ class Si5351 {
}
void wait_for_device_ready() {
#ifndef PRALINE
while (device_status() & 0x80);
#else
// Add timeout to prevent infinite loop if I2C communication fails
// (e.g., on PRALINE hardware with different configuration)
uint32_t timeout = 100000;
while ((device_status() & 0x80) && (timeout > 0)) {
timeout--;
}
#endif
}
bool plla_loss_of_signal() {
@@ -377,10 +386,15 @@ class Si5351 {
}
void reset_plls() {
#ifndef PRALINE
// Datasheet recommends value 0xac, though the low nibble bits are not defined in AN619.
write_register(Register::PLLReset, 0xac);
#else
// Reset both PLLA and PLLB. Use 0xA0 to match HackRF reference firmware.
// The low nibble bits are reserved/undefined in AN619.
write_register(Register::PLLReset, 0xa0);
#endif
}
regvalue_t read_register(const uint8_t reg);
template <size_t N>
@@ -397,6 +411,18 @@ class Si5351 {
write(config.reg(ms_number));
}
#ifdef PRALINE
/* Write multisynth config using single-byte writes for debugging */
void write_ms_single_byte(const size_t ms_number, const MultisynthFractional& config) {
const auto regs = config.reg(ms_number);
// regs[0] is the base register address, regs[1-8] are the data bytes
const uint8_t base_reg = regs[0];
for (size_t i = 1; i < regs.size(); i++) {
write_register(base_reg + i - 1, regs[i]);
}
}
#endif
void set_ms_frequency(
const size_t ms_number,
const uint32_t frequency,
@@ -480,7 +506,6 @@ class Si5351 {
}});
}
};
} // namespace si5351
#endif /*__SI5351_H__*/
+8
View File
@@ -46,6 +46,14 @@ class Arbiter {
_bus.transfer(data, count);
}
#ifdef PRALINE
/* Invalidate cached config - forces reconfiguration on next transfer.
* Call this after directly manipulating SSP registers (e.g., FPGA access). */
void invalidate() {
_config = nullptr;
}
#endif
private:
SPI& _bus;
const SPIConfig* _config;
+26 -1
View File
@@ -194,8 +194,12 @@ void timer0_callback(GPTDriver* const) {
if (encoder_update(switches_raw) || encoder_read())
event_mask |= EVT_MASK_ENCODER;
/* Signal event loop */
/* Signal event loop */
#ifdef PRALINE
if (event_mask && thread_controls_event) {
#else
if (event_mask) {
#endif
chSysLockFromIsr();
chEvtSignalI(thread_controls_event, event_mask);
chSysUnlockFromIsr();
@@ -227,8 +231,13 @@ void controls_init() {
gptStart(&GPTD1, &timer0_config);
gptStartContinuous(&GPTD1, timer0_match_count);
#ifdef PRALINE
// Enable repeat for directional switches only
for (auto i = Switch::Right; i <= Switch::Up; incr(i))
#else
// Enable repeat for directional and Select switches only
for (auto i = Switch::Right; i <= Switch::Sel; incr(i))
#endif
switch_debounce[toUType(i)].enable_repeat();
}
@@ -250,6 +259,22 @@ SwitchesState get_switches_state() {
return result;
}
/* Gets the repeat enabled state for all the switches. */
SwitchesState get_switches_repeat_config() {
SwitchesState result;
for (size_t i = 0; i < result.size(); i++)
result[i] = switch_debounce[i].get_repeat_enabled();
return result;
}
/* Configures which switches support repeat.*/
void set_switches_repeat_config(SwitchesState switch_config) {
for (size_t i = 0; i < switch_config.size(); i++)
switch_debounce[i].set_enable_repeat(switch_config[i]);
}
/* Gets the long press enabled state for all the switches. */
SwitchesState get_switches_long_press_config() {
SwitchesState result;
+2
View File
@@ -48,6 +48,8 @@ uint8_t swizzled_switches();
SwitchesState get_switches_state();
EncoderPosition get_encoder_position();
touch::Frame get_touch_frame();
SwitchesState get_switches_repeat_config();
void set_switches_repeat_config(SwitchesState switch_config);
SwitchesState get_switches_long_press_config();
void set_switches_long_press_config(SwitchesState switch_config);
+8 -1
View File
@@ -52,10 +52,17 @@ extern "C" {
CH_IRQ_HANDLER(PIN_INT4_IRQHandler) {
CH_IRQ_PROLOGUE();
#ifdef PRALINE
if (thread_lcd_frame_event) {
chSysLockFromIsr();
chEvtSignalI(thread_lcd_frame_event, EVT_MASK_LCD_FRAME_SYNC);
chSysUnlockFromIsr();
}
#else
chSysLockFromIsr();
chEvtSignalI(thread_lcd_frame_event, EVT_MASK_LCD_FRAME_SYNC);
chSysUnlockFromIsr();
#endif
LPC_GPIO_INT->IST = (1U << 4);
+8 -1
View File
@@ -40,10 +40,17 @@ extern "C" {
CH_IRQ_HANDLER(RTC_IRQHandler) {
CH_IRQ_PROLOGUE();
#ifdef PRALINE
if (thread_rtc_event) {
chSysLockFromIsr();
chEvtSignalI(thread_rtc_event, EVT_MASK_RTC_TICK);
chSysUnlockFromIsr();
}
#else
chSysLockFromIsr();
chEvtSignalI(thread_rtc_event, EVT_MASK_RTC_TICK);
chSysUnlockFromIsr();
#endif
rtc::interrupt::clear_all();
+69
View File
@@ -0,0 +1,69 @@
/*
* Copyright (C) 2026 lifegame1lu111
*
* 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 "keeloq_file.hpp"
namespace fs = std::filesystem;
bool read_keeloq_file(const fs::path& path, KeeloqData& data) {
File file{};
auto result = file.open(path);
if (result) {
return false;
}
FileLineReader reader{file};
std::string raw = *reader.begin();
auto chunks = split_string(raw, ';');
if (chunks.size() != 4) {
return false;
}
data.mf_name = std::string{chunks[0]};
data.serial = std::strtoul(chunks[1].data(), NULL, 16);
data.counter = std::atoi(chunks[2].data());
data.btn = (uint8_t)std::atoi(chunks[3].data());
return true;
}
bool write_keeloq_file(const fs::path& path, const KeeloqData& data) {
delete_file(path);
File file{};
auto result = file.open(path, false, true);
if (result) {
return false;
}
std::string formatted = data.mf_name + ";" + to_string_hex(data.serial) + ";" + to_string_dec_uint(data.counter) + ";" + to_string_dec_uint(data.btn);
file.write_line(formatted);
file.close();
return true;
}
+40
View File
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2026 lifegame1lu111
*
* 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 __KEELOQ_FILE__
#define __KEELOQ_FILE__
#include "portapack.hpp"
#include "file_reader.hpp"
#include "string_format.hpp"
#include <string_view>
struct KeeloqData {
std::string mf_name{};
uint32_t serial = 0;
uint32_t counter = 0;
uint8_t btn = 0;
};
bool read_keeloq_file(const std::filesystem::path&, KeeloqData&);
bool write_keeloq_file(const std::filesystem::path&, const KeeloqData&);
#endif
+53
View File
@@ -0,0 +1,53 @@
/*
* Copyright (C) 2026 lifegame1lu111
*
* 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 "keeloq_keystore.hpp"
KeeloqKeystore::KeeloqKeystore() {
ensure_directory(keeloq_keys_dir);
File keeloq_keys_file{};
if (keeloq_keys_file.open(keeloq_keys_dir / "MFCODES")) {
return;
}
FileLineReader reader{keeloq_keys_file};
for (const std::string& line : reader) {
auto cols = split_string(line, ';');
if (cols.size() != 3) {
return;
}
KeeloqKey key{
std::string{cols[0]},
std::strtoull(cols[1].data(), NULL, 16),
(uint8_t)std::atoi(cols[2].data())};
keys.push_back(key);
}
}
const std::vector<KeeloqKey>& KeeloqKeystore::get_keys() {
return keys;
}
+49
View File
@@ -0,0 +1,49 @@
/*
* Copyright (C) 2026 lifegame1lu111
*
* 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 __KEELOQ_KEYSTORE__
#define __KEELOQ_KEYSTORE__
#include "file_reader.hpp"
#include "file_path.hpp"
#include "string_format.hpp"
#include <string_view>
#define KEELOQ_SIMPLE_LEARNING 1
#define KEELOQ_NORMAL_LEARNING 2
struct KeeloqKey {
std::string mf_name{};
uint64_t key = 0;
uint8_t type = 0;
};
class KeeloqKeystore {
public:
KeeloqKeystore();
const std::vector<KeeloqKey>& get_keys();
private:
std::vector<KeeloqKey> keys{};
};
#endif
+1 -1
View File
@@ -187,7 +187,7 @@ int main(void) {
lcd_frame_sync_configure();
rtc_interrupt_enable();
Theme::SetTheme((Theme::ThemeId)portapack::persistent_memory::ui_theme_id()); // load theme
Theme::SetTheme((Theme::ThemeId)portapack::persistent_memory::ui_theme_id());
event_loop();
+75 -9
View File
@@ -56,6 +56,12 @@ using asahi_kasei::ak4951::AK4951;
#include "i2cdevmanager.hpp"
#include "battery.hpp"
#ifndef PRALINE
extern "C" {
#include "platform_detect.h"
}
#endif
namespace portapack {
const char* init_error = nullptr;
@@ -337,14 +343,37 @@ static void set_cpu_clock_speed() {
*/
/* Step into the 90-110MHz M4 clock range */
#ifdef PRALINE
/* PRALINE: Enable and use 12MHz XTAL directly (no GP_CLKIN from Si5351) */
/* Step 1: Enable the crystal oscillator */
LPC_CGU->XTAL_OSC_CTRL.ENABLE = 0; // 0 = enable (active low)
LPC_CGU->XTAL_OSC_CTRL.HF = 0; // 0 = low frequency mode (1-20MHz)
/* Step 2: Wait for oscillator to stabilize (~250us at IRC speed) */
volatile uint32_t delay = 3000; // ~250us at 12MHz IRC
while (delay--);
/* Step 3: Configure PLL1 from XTAL
* Fclkin = 12M, /N=1 = 12M, Fcco = 12M * 17 = 204M
* Fclk = Fcco / (2*(P=1)) = 102M
*/
cgu::pll1::ctrl({
.pd = 1,
.bypass = 0,
.fbsel = 0,
.direct = 0,
.psel = 0,
.autoblock = 1,
.nsel = 0, // N = 1
.msel = 16, // M = 17, so 12MHz * 17 = 204MHz
.clk_sel = cgu::CLK_SEL::XTAL,
});
#else
/* OG:
* Fclkin = 40M
* /N=2 = 20M = PFDin
* Fcco = PFDin * (M=10) = 200M
* Fclkin = 40M, /N=2 = 20M, Fcco = 20M * 10 = 200M
* r9:
* Fclkin = 10M
* /N=1 = 10M = PFDin
* Fcco = PFDin * (M=20) = 200M
* Fclkin = 10M, /N=1 = 10M, Fcco = 10M * 20 = 200M
* Fclk = Fcco / (2*(P=1)) = 100M
*/
cgu::pll1::ctrl({
@@ -358,20 +387,41 @@ static void set_cpu_clock_speed() {
.msel = hackrf_r9 ? 19UL : 9UL,
.clk_sel = cgu::CLK_SEL::GP_CLKIN,
});
#endif
cgu::pll1::enable();
#ifndef PRALINE
while (!cgu::pll1::is_locked());
set_clock_config(clock_config_pll1_step);
/* Delay >50us at 90-110MHz clock speed */
volatile uint32_t delay = 1400;
while (delay--);
set_clock_config(clock_config_pll1);
/* Remove /2P divider from PLL1 output to achieve full speed */
cgu::pll1::direct();
#else
// Wait for PLL1 to lock with timeout
{
uint32_t timeout = 100000;
while (!cgu::pll1::is_locked() && timeout > 0) {
timeout--;
}
}
if (cgu::pll1::is_locked()) {
set_clock_config(clock_config_pll1_step);
/* Delay >50us at 90-110MHz clock speed */
volatile uint32_t delay = 1400;
while (delay--);
set_clock_config(clock_config_pll1);
/* Remove /2P divider from PLL1 output to achieve full speed */
cgu::pll1::direct();
}
#endif
}
static void draw_splash_screen_icon(int16_t n, const ui::Bitmap& bitmap) {
@@ -505,6 +555,13 @@ init_status_t init() {
chThdSleepMilliseconds(100);
#ifndef PRALINE
detect_hardware_platform();
finalize_detect_hardware_platform();
chThdSleepMilliseconds(100);
#endif
configure_pins_portapack();
portapack::io.init();
@@ -534,11 +591,11 @@ init_status_t init() {
cgu::pll1::disable();
set_cpu_clock_speed();
/* sample max: 1023 sample_t AKA uint16_t
* touch_sensitivity: range: 1 to 128
* threshold range: 1023/1 to 1023/128 = 1023 to 8
*/
touch_threshold = portapack::persistent_memory::touchscreen_threshold();
if (lcd_fast_setup)
@@ -561,8 +618,10 @@ init_status_t init() {
chThdSleepMilliseconds(10);
clock_manager.set_reference_ppb(persistent_memory::correction_ppb());
clock_manager.enable_if_clocks();
clock_manager.enable_codec_clocks();
radio::init();
sdcStart(&SDCD1, nullptr);
@@ -574,12 +633,18 @@ init_status_t init() {
draw_splash_screen_icon(2, ui::bitmap_icon_sd);
init_status_t return_code = init_status_t::INIT_SUCCESS;
#ifndef PRALINE
// HackRF One uses CPLD - load it via JTAG
if (!hackrf::cpld::load_sram()) {
if (lcd_fast_setup)
chDbgPanic("HACKRF CPLD FAILED");
return_code = init_status_t::INIT_HACKRF_CPLD_FAILED;
}
#else
// HackRF Pro (PRALINE) uses FPGA - already loaded in board.cpp __early_init()
// via fpga_bridge_init(), so nothing to do here
#endif
if (lcd_fast_setup)
draw_splash_screen_icon(3, ui::bitmap_icon_hackrf);
@@ -592,6 +657,7 @@ init_status_t init() {
chThdSleepMilliseconds(10);
audio::init(portapack_audio_codec());
battery::BatteryManagement::set_calc_override(persistent_memory::ui_override_batt_calc());
i2cdev::I2CDevManager::init();
+232 -2
View File
@@ -26,6 +26,14 @@
#include "rffc507x.hpp"
#include "max2837.hpp"
#include "max2839.hpp"
#ifdef PRALINE
#include "max2831.hpp"
extern "C" {
#include "fpga_bridge.h"
}
#endif
#include "max5864.hpp"
#include "baseband_cpld.hpp"
@@ -42,6 +50,10 @@ using namespace hackrf::one;
#include "portapack.hpp"
#include "portapack_persistent_memory.hpp"
#include "hal.h" // For LPC_SGPIO
#include <array>
/* Direct access to the radio. Setting values incorrectly can damage
* the device. Applications should use ReceiverModel or TransmitterModel
* instead of calling these functions directly. */
@@ -56,6 +68,18 @@ static constexpr uint32_t ssp_scr(
return static_cast<uint8_t>(pclk_f / cpsr / spi_f - 1);
}
#ifdef PRALINE
/* MAX2831 uses 9-bit SPI transfers */
static constexpr SPIConfig ssp_config_max283x = {
.end_cb = NULL,
.ssport = gpio_max283x_select.port(),
.sspad = gpio_max283x_select.pad(),
.cr0 =
CR0_CLOCKRATE(ssp_scr(ssp1_pclk_f, ssp1_cpsr, max283x_spi_f) + 3) | CR0_FRFSPI | CR0_DSS9BIT,
.cpsr = ssp1_cpsr,
};
#else
/* MAX2837/MAX2839 use 16-bit SPI transfers */
static constexpr SPIConfig ssp_config_max283x = {
.end_cb = NULL,
.ssport = gpio_max283x_select.port(),
@@ -64,6 +88,7 @@ static constexpr SPIConfig ssp_config_max283x = {
CR0_CLOCKRATE(ssp_scr(ssp1_pclk_f, ssp1_cpsr, max283x_spi_f) + 3) | CR0_FRFSPI | CR0_DSS16BIT,
.cpsr = ssp1_cpsr,
};
#endif
static constexpr SPIConfig ssp_config_max5864 = {
.end_cb = NULL,
@@ -89,6 +114,9 @@ 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};
#endif
static max5864::MAX5864 baseband_codec{ssp1_target_max5864};
static baseband::CPLD baseband_cpld;
@@ -97,19 +125,46 @@ static rf::Direction direction{rf::Direction::Receive};
static bool baseband_invert = false;
static bool mixer_invert = false;
#ifdef PRALINE
static rf::Direction cached_direction = rf::Direction::Receive;
static bool cached_rf_amp = false;
static int_fast8_t cached_lna_gain = 0;
static int_fast8_t cached_vga_gain = 0;
#endif
void init() {
#ifdef PRALINE
/* PRALINE uses MAX2831 transceiver */
second_if = (max283x::MAX283x*)&second_if_max2831;
#else
if (hackrf_r9) {
gpio_r9_not_ant_pwr.write(1);
gpio_r9_not_ant_pwr.output();
}
rf_path.init();
first_if.init();
second_if = hackrf_r9
? (max283x::MAX283x*)&second_if_max2839
: (max283x::MAX283x*)&second_if_max2837;
#endif
rf_path.init();
first_if.init();
second_if->init();
baseband_codec.init();
#ifndef PRALINE
/* HackRF One uses CPLD for Q inversion control.
* PRALINE uses FPGA and the pin (P2_3) is used for LCD_TE on H4M. */
baseband_cpld.init();
#else
/* Initialize FPGA registers - DC_BLOCK must be enabled for RX */
// debug::fpga::init();
fpga_debug_register_write(1, 0x01); // DC_BLOCK=1, QUARTER_SHIFT=0, Q_INVERT=0
fpga_debug_register_write(2, 0x00); // RX_DECIM=0 (no decimation for testing)
fpga_debug_register_write(3, 0x00); // TX_CTRL=0
fpga_debug_register_write(4, 0x00); // TX_INTRP=0
fpga_debug_register_write(5, 0x00); // TX_PSTEP=0
ssp1_arbiter.invalidate();
chThdSleepMilliseconds(10); // Let FPGA registers settle
#endif
}
void set_direction(const rf::Direction new_direction) {
@@ -120,6 +175,10 @@ void set_direction(const rf::Direction new_direction) {
// Deleting that load_sram_no_verify() (or the original , load_sram() ), solves random TX swap I/Q problem in H1R1 , others OK- (and no side effects to all).
// hackrf::cpld::load_sram_no_verify(); // After commit "removed the use of the hackrf cpld eeprom #1732", in a H1R1, Mic App wrong SSB TX with random USB/LSB change.
#ifdef PRALINE
cached_direction = new_direction; // Track state for debug and potentially other purposes.
#endif
direction = new_direction;
if (hackrf_r9) {
@@ -143,7 +202,18 @@ void set_direction(const rf::Direction new_direction) {
*/
baseband_invert = false;
}
#ifndef PRALINE
baseband_cpld.set_invert(mixer_invert ^ baseband_invert);
#else
// Praline: Control Q inversion via FPGA register
// Assuming register 1 bit 1 controls Q inversion
uint8_t ctrl_reg = 0x01; // DC_BLOCK enabled
if (mixer_invert ^ baseband_invert) {
ctrl_reg |= 0x02; // Set Q_INVERT bit
}
fpga_debug_register_write(1, ctrl_reg);
ssp1_arbiter.invalidate();
#endif
second_if->set_mode((direction == rf::Direction::Transmit) ? max283x::Mode::Transmit : max283x::Mode::Receive);
rf_path.set_direction(direction);
@@ -154,6 +224,16 @@ void set_direction(const rf::Direction new_direction) {
led_rx.on();
else
led_tx.on();
// #ifdef PRALINE
// Try with Q inversion OFF
// fpga_debug_register_write(1, 0x01); // DC_BLOCK=1, Q_INVERT=0
// ssp1_arbiter.invalidate();
// If no signals, try with Q inversion ON
// fpga_debug_register_write(1, 0x03); // DC_BLOCK=1, Q_INVERT=1
// ssp1_arbiter.invalidate();
// #endif
}
bool set_tuning_frequency(const rf::Frequency frequency) {
@@ -196,7 +276,9 @@ bool set_tuning_frequency(const rf::Frequency frequency) {
rf_path.set_band(tuning_config.rf_path_band);
mixer_invert = tuning_config.mixer_invert;
#ifndef PRALINE
baseband_cpld.set_invert(mixer_invert ^ baseband_invert);
#endif
return result_second_if;
} else {
@@ -205,14 +287,23 @@ bool set_tuning_frequency(const rf::Frequency frequency) {
}
void set_rf_amp(const bool rf_amp) {
#ifdef PRALINE
cached_rf_amp = rf_amp; // Track state for debug and potentialy other purposes.
#endif
rf_path.set_rf_amp(rf_amp);
}
void set_lna_gain(const int_fast8_t db) {
#ifdef PRALINE
cached_lna_gain = db; // Track state for debug and potentially other purposes.
#endif
second_if->set_lna_gain(db);
}
void set_vga_gain(const int_fast8_t db) {
#ifdef PRALINE
cached_vga_gain = db; // Track state for debug and potentially other purposes.
#endif
second_if->set_vga_gain(db);
}
@@ -235,11 +326,17 @@ void set_baseband_rate(const uint32_t rate) {
void set_antenna_bias(const bool on) {
/* Pull MOSFET gate low to turn on antenna bias. */
#ifdef PRALINE
// Praline: P2_12 = GPIO1[12], ANT_BIAS_EN_N (active LOW)
LPC_GPIO->CLR[1] = on ? (1 << 12) : 0;
LPC_GPIO->SET[1] = on ? 0 : (1 << 12);
#else
if (hackrf_r9) {
gpio_r9_not_ant_pwr.write(on ? 0 : 1);
} else {
first_if.set_gpo1(on ? 0 : 1);
}
#endif
}
void set_tx_max283x_iq_phase_calibration(const size_t v) {
@@ -275,8 +372,32 @@ void disable() {
led_tx.off();
}
#ifdef PRALINE
void invalidate_spi_config() {
ssp1_arbiter.invalidate();
}
#endif
namespace debug {
#ifdef PRALINE
rf::Direction get_cached_direction() {
return cached_direction;
}
bool get_cached_rf_amp() {
return cached_rf_amp;
}
int_fast8_t get_cached_lna_gain() {
return cached_lna_gain;
}
int_fast8_t get_cached_vga_gain() {
return cached_vga_gain;
}
#endif
namespace first_if {
uint32_t register_read(const size_t register_number) {
@@ -287,6 +408,48 @@ void register_write(const size_t register_number, uint32_t value) {
radio::first_if.write(register_number, value);
}
#ifdef PRALINE
extern "C" {
extern struct rffc507x_debug_t {
uint32_t requested_freq_mhz;
uint32_t calculated_vco_mhz;
uint32_t expected_n;
uint8_t expected_lodiv;
uint8_t expected_presc;
bool was_called;
uint32_t calc_lo_freq_mhz;
uint32_t calc_vco_inside_mhz;
uint8_t calc_lodiv_log2;
uint8_t calc_presc_log2;
uint64_t calc_n_q24;
} rffc507x_debug_info;
}
/*struct TuningInfo {
uint32_t requested_freq_mhz;
uint32_t expected_n;
uint8_t expected_lodiv;
uint8_t expected_presc;
bool was_called;
};*/
TuningInfo get_tuning_info() {
return {
rffc507x_debug_info.requested_freq_mhz,
rffc507x_debug_info.calculated_vco_mhz,
rffc507x_debug_info.expected_n,
rffc507x_debug_info.expected_lodiv,
rffc507x_debug_info.expected_presc,
rffc507x_debug_info.was_called,
rffc507x_debug_info.calc_lo_freq_mhz,
rffc507x_debug_info.calc_vco_inside_mhz,
rffc507x_debug_info.calc_lodiv_log2,
rffc507x_debug_info.calc_presc_log2,
rffc507x_debug_info.calc_n_q24,
};
}
#endif
} /* namespace first_if */
namespace second_if {
@@ -305,6 +468,73 @@ int8_t temp_sense() {
} /* namespace second_if */
#ifdef PRALINE
namespace fpga {
/* Use fpga_bridge.c functions for FPGA register access.
* These properly switch SPI mode between iCE40 (Mode 3, 8-bit)
* and MAX2831 (Mode 0, 9-bit). After each access, we must
* invalidate the SPI arbiter's cached config since fpga_bridge.c
* modifies SSP1 registers directly. */
uint32_t register_read(const size_t register_number) {
uint32_t result = fpga_debug_register_read(static_cast<uint8_t>(register_number));
ssp1_arbiter.invalidate(); // Force arbiter to reconfigure on next transfer
return result;
}
void register_write(const size_t register_number, uint32_t value) {
fpga_debug_register_write(static_cast<uint8_t>(register_number), static_cast<uint8_t>(value));
ssp1_arbiter.invalidate(); // Force arbiter to reconfigure on next transfer
}
void init() {
// Initialize FPGA registers after bitstream load
// DC_BLOCK (bit 0) must be enabled for RX to work
fpga_debug_register_write(1, 0x01); // CTRL: DC_BLOCK=1
fpga_debug_register_write(2, 0x00); // RX_DECIM: no decimation
fpga_debug_register_write(3, 0x00); // TX_CTRL: NCO disabled
fpga_debug_register_write(4, 0x00); // TX_INTRP: no interpolation
fpga_debug_register_write(5, 0x00); // TX_PSTEP: zero phase step
ssp1_arbiter.invalidate(); // Force arbiter to reconfigure on next transfer
}
} /* namespace fpga */
#endif
namespace sgpio {
/* SGPIO register map for debug viewing
* We expose key registers for diagnosing data flow issues.
* Register numbers map to:
* 0: CTRL_ENABLE - Which slices are enabled
* 1: GPIO_INREG - GPIO input register (data pins state)
* 2: GPIO_OUTREG - GPIO output register (direction, disable, etc)
* 3: GPIO_OENREG - GPIO output enable register
* 4: STATUS_1 - Exchange interrupt status (slice A = bit 0)
* 5: REG_SS[0] - Shadow register slice A (current sample data)
*/
uint32_t register_read(const size_t register_number) {
switch (register_number) {
case 0:
return LPC_SGPIO->CTRL_ENABLE;
case 1:
return LPC_SGPIO->GPIO_INREG;
case 2:
return LPC_SGPIO->GPIO_OUTREG;
case 3:
return LPC_SGPIO->GPIO_OENREG;
case 4:
return LPC_SGPIO->STATUS_1;
case 5:
return LPC_SGPIO->REG_SS[0];
default:
return 0xFFFFFFFF;
}
}
} /* namespace sgpio */
} /* namespace debug */
} /* namespace radio */
+44
View File
@@ -62,6 +62,10 @@ void set_rx_max283x_iq_phase_calibration(const size_t v);
// void configure(Configuration configuration);
void disable();
#ifdef PRALINE
void invalidate_spi_config();
#endif
namespace debug {
namespace first_if {
@@ -69,6 +73,24 @@ namespace first_if {
uint32_t register_read(const size_t register_number);
void register_write(const size_t register_number, uint32_t value);
#ifdef PRALINE
struct TuningInfo {
uint32_t requested_freq_mhz;
uint32_t calculated_vco_mhz;
uint32_t expected_n;
uint8_t expected_lodiv;
uint8_t expected_presc;
bool was_called;
uint32_t calc_lo_freq_mhz;
uint32_t calc_vco_inside_mhz;
uint8_t calc_lodiv_log2;
uint8_t calc_presc_log2;
uint64_t calc_n_q24;
};
TuningInfo get_tuning_info();
#endif
} /* namespace first_if */
namespace second_if {
@@ -81,6 +103,28 @@ int8_t temp_sense();
} /* namespace second_if */
#ifdef PRALINE
namespace fpga {
uint32_t register_read(const size_t register_number);
void register_write(const size_t register_number, uint32_t value);
void init();
} /* namespace fpga */
/* State tracking - GPIO pins are write-only so we cache last known state */
rf::Direction get_cached_direction();
bool get_cached_rf_amp();
int_fast8_t get_cached_lna_gain();
int_fast8_t get_cached_vga_gain();
#endif
namespace sgpio {
uint32_t register_read(const size_t register_number);
} /* namespace sgpio */
} /* namespace debug */
} /* namespace radio */
+42 -4
View File
@@ -34,6 +34,12 @@
#include "dsp_iir_config.hpp"
#include "utility.hpp"
#ifdef PRALINE
extern "C" {
#include "fpga_bridge.h"
}
#endif
using namespace hackrf::one;
using namespace portapack;
@@ -303,8 +309,20 @@ int32_t ReceiverModel::tuning_offset() {
void ReceiverModel::update_tuning_frequency() {
// TODO: use positive offset if freq < offset.
if (enabled_)
if (enabled_) {
radio::set_tuning_frequency(target_frequency() + hidden_offset + tuning_offset());
#ifdef PRALINE
/* Praline: Must re-apply baseband filter after frequency change
* Reference: hackrf_usb radio.c radio_set_frequency()
*
* Different frequency ranges may use different quarter-shift modes,
* which affects the required LPF bandwidth. For now we just
* recalculate the filter to be safe.
*/
update_baseband_bandwidth();
#endif
}
}
void ReceiverModel::set_hidden_offset(rf::Frequency offset) {
@@ -313,8 +331,28 @@ void ReceiverModel::set_hidden_offset(rf::Frequency offset) {
}
void ReceiverModel::update_baseband_bandwidth() {
if (enabled_)
if (enabled_) {
#ifdef PRALINE
/* Praline: LPF bandwidth calculation
* Reference: hackrf_usb radio.c radio_set_filter()
*
* LPF = (sample_rate * 3) / 8
* Plus additional offset if quarter-shift is enabled (not implemented yet)
*/
uint32_t lpf_bandwidth = (sampling_rate() * 3) / 8;
// For now, quarter-shift is disabled, so no offset added
// When quarter-shift is implemented:
// if (quarter_shift_enabled) {
// uint32_t offset = (sampling_rate() << decimation_n) / 8;
// lpf_bandwidth += offset * 2;
// }
radio::set_baseband_filter_bandwidth_rx(lpf_bandwidth);
#else
radio::set_baseband_filter_bandwidth_rx(baseband_bandwidth());
#endif
}
}
void ReceiverModel::update_sampling_rate() {
@@ -323,9 +361,9 @@ void ReceiverModel::update_sampling_rate() {
// protocols that need quick RX/TX turn-around.
// Disabling baseband while changing sampling rates seems like a good idea...
if (enabled_)
if (enabled_) {
radio::set_baseband_rate(sampling_rate());
}
update_tuning_frequency();
}
+79 -1
View File
@@ -35,6 +35,36 @@ namespace path {
namespace {
#ifdef PRALINE
/* PRALINE uses a simplified RF path with only 5 control signals.
* The RF path architecture is completely different from HackRF One.
*/
struct PralineConfig {
bool tx_en;
bool mix_en_n; // Inverted: 0 = mixer enabled
bool lpf_en;
bool rf_amp_en;
bool ant_bias_en_n; // Inverted: 0 = bias enabled
static void gpio_init() {
gpio_tx_enable.output();
gpio_mix_enable_n.output();
gpio_lpf_enable.output();
gpio_rf_amp_enable.output();
gpio_ant_bias_disable.output();
}
void apply() const {
gpio_tx_enable.write(tx_en);
gpio_mix_enable_n.write(mix_en_n);
gpio_lpf_enable.write(lpf_en);
gpio_rf_amp_enable.write(rf_amp_en);
gpio_ant_bias_disable.write(ant_bias_en_n);
}
};
#else
/* HackRF One uses 11 GPIOs for RF path control */
using GPIOs = std::array<GPIO, 11>;
/* TODO: ARM GCC 4.8 2014q3 doesn't like this array inside struct Config.
@@ -53,7 +83,10 @@ constexpr GPIOs gpios{
gpio_rx_amp,
gpio_not_rx_amp_pwr,
};
#endif
#ifndef PRALINE
/* HackRF One Config struct - not used on PRALINE */
struct Config {
using base_type = uint16_t;
@@ -153,7 +186,10 @@ struct Config {
}
}
};
#endif /* !PRALINE */
#ifndef PRALINE
/* HackRF One config table - not used on PRALINE */
using ConfigAmp = std::array<Config, 2>;
using ConfigDirection = std::array<ConfigAmp, 2>;
using ConfigBand = std::array<ConfigDirection, 3>;
@@ -193,12 +229,26 @@ constexpr Config get_config(
const bool amplify) {
return config_table[toUType(band)][toUType(direction)][amplify ? 1 : 0];
}
#endif /* !PRALINE */
} /* namespace */
void Path::init() {
#ifdef PRALINE
PralineConfig::gpio_init();
/* Set safe initial state: RX mode, mixer enabled, LPF on, amp off, no bias */
PralineConfig config = {
.tx_en = false,
.mix_en_n = false, // Mixer enabled (inverted)
.lpf_en = true, // LPF on for low band
.rf_amp_en = false, // Amp off
.ant_bias_en_n = true // Bias off (inverted)
};
config.apply();
#else
update();
Config::gpio_init();
#endif
}
void Path::set_direction(const Direction new_direction) {
@@ -220,20 +270,48 @@ void Path::update() {
/* 0 ^ 0 => 0 & 0 = 0 ^ 0 = 0 (no change)
* 0 ^ 1 => 1 & 0 = 0 ^ 0 = 0 (ignore change to 1)
* 1 ^ 0 => 1 & 1 = 1 ^ 1 = 0 (allow change to 0)
* 1 ^ 1 => 0 & 1 = 0 ^ 1 = 1 (no change)
* 1 ^ 1 => 0 & 1 = 0 ^ 1 = 1 (no change) */
#ifdef PRALINE
/* PRALINE RF path control:
* - tx_en: 1 for TX, 0 for RX
* - mix_en_n: 0 to enable mixer (inverted), 1 to bypass
* - lpf_en: 1 for low band (< 2.4 GHz), 0 for high band
* - rf_amp_en: 1 to enable RF amplifier
* - ant_bias_en_n: 0 to enable antenna bias (inverted)
*/
// const Config changed = _config ^ config_next;
// const Config turned_off = _config & changed;
PralineConfig config;
/* In transition, ignore the bits that are turning on. So this transition phase
* only turns off signals. It doesn't turn on signals.
*/
// const Config transition_config = _config ^ turned_off;
// update_signals(transition_config);
config.tx_en = (direction == Direction::Transmit);
/* Mixer bypass for mid band (2.3-2.7 GHz direct to MAX2831) */
config.mix_en_n = (band == Band::Mid); // 1 = bypass (disabled)
/* Move to the final state by turning on required signals. */
/* LPF for low band */
config.lpf_en = (band == Band::Low);
/* RF amp when amplification requested */
config.rf_amp_en = rf_amp;
/* Antenna bias off by default */
config.ant_bias_en_n = true;
config.apply();
#else
/* HackRF One RF path control */
const auto config = get_config(direction, band, rf_amp);
config.apply();
#endif
}
} // namespace path
+42 -1
View File
@@ -32,6 +32,10 @@
#include "chprintf.h"
#include "portapack.hpp"
extern "C" {
#include "platform_detect.h"
}
/**
* @brief Shell termination event source.
*/
@@ -65,8 +69,42 @@ static void list_commands(BaseSequentialStream* chp, const ShellCommand* scp) {
}
}
static const char* get_board_revision_string(board_rev_t rev) {
switch (rev) {
case BOARD_REV_HACKRF1_OLD:
return "HackRF R1-R5";
case BOARD_REV_HACKRF1_R6:
return "HackRF R6";
case BOARD_REV_HACKRF1_R7:
return "HackRF R7";
case BOARD_REV_HACKRF1_R8:
return "HackRF R8";
case BOARD_REV_HACKRF1_R9:
return "HackRF R9";
case BOARD_REV_HACKRF1_R10:
return "HackRF R10";
case BOARD_REV_GSG_HACKRF1_R6:
return "GSG HackRF R6";
case BOARD_REV_GSG_HACKRF1_R7:
return "GSG HackRF R7";
case BOARD_REV_GSG_HACKRF1_R8:
return "GSG HackRF R8";
case BOARD_REV_GSG_HACKRF1_R9:
return "GSG HackRF R9";
case BOARD_REV_GSG_HACKRF1_R10:
return "GSG HackRF R10";
case BOARD_REV_UNRECOGNIZED:
return "Unrecognized";
case BOARD_REV_UNDETECTED:
return "Undetected";
default:
return "Unknown";
}
}
static void cmd_info(BaseSequentialStream* chp, int argc, char* argv[]) {
(void)argv;
if (argc > 0) {
usage(chp, const_cast<char*>("info"));
return;
@@ -92,7 +130,10 @@ static void cmd_info(BaseSequentialStream* chp, int argc, char* argv[]) {
#ifdef VERSION_STRING
chprintf(chp, "Mayhem Version: %s\r\n", VERSION_STRING);
#endif
chprintf(chp, "HackRF Board Rev: %s\r\n", hackrf_r9 ? "R9" : "R1-R8");
board_rev_t revision = detected_revision();
const char* revision_string = get_board_revision_string(revision);
chprintf(chp, "HackRF Board Rev: %s\r\n", revision_string);
chprintf(chp, "Reference Source: %s\r\n", portapack::clock_manager.get_source().c_str());
chprintf(chp, "Reference Freq: %s\r\n", portapack::clock_manager.get_freq().c_str());
#ifdef __DATE__
+49
View File
@@ -26,9 +26,26 @@
namespace tuning {
namespace config {
// Forward declarations
Config low_band(const rf::Frequency target_frequency);
Config mid_band(const rf::Frequency target_frequency);
Config high_band(const rf::Frequency target_frequency);
// Low band <2170 Mhz:
constexpr rf::Frequency low_band_second_lo_frequency(const rf::Frequency target_frequency) {
#ifdef PRALINE
// Praline-specific formula for MAX2831 (2.3-2.6 GHz range)
// Use a fixed second_lo that:
// 1. Falls in MAX2831's sweet spot (2.3-2.6 GHz)
// 2. Gives RFFC5072 a VCO frequency in its range (2700-5400 MHz)
// For most low-band frequencies, use 2500 MHz as second_lo
// This gives RFFC5072 plenty of headroom
(void)target_frequency; // Unused in fixed formula
return 2500'000'000;
#else
return 2650'000'000 - (target_frequency / 7);
#endif
}
Config low_band(const rf::Frequency target_frequency) {
@@ -40,20 +57,52 @@ Config low_band(const rf::Frequency target_frequency) {
// Mid band 2170-2740 Mhz:
Config mid_band(const rf::Frequency target_frequency) {
#ifdef PRALINE
// For Praline with MAX2831 (2.3-2.6 GHz range)
// Frequencies 2170-2300 MHz need upconversion since they're below MAX2831 minimum
if (target_frequency < 2300'000'000) {
// Treat as low band
return low_band(target_frequency);
}
// Frequencies 2300-2600 MHz can go direct (no RFFC5072)
else if (target_frequency <= 2600'000'000) {
const rf::Frequency second_lo_frequency = target_frequency;
const rf::Frequency first_lo_frequency = 0;
const bool mixer_invert = false;
return {first_lo_frequency, second_lo_frequency, rf::path::Band::Mid, mixer_invert};
}
// Frequencies 2600-2740 MHz need downconversion since they're above MAX2831 maximum
else {
// Treat as high band
return high_band(target_frequency);
}
#else
const rf::Frequency second_lo_frequency = target_frequency;
const rf::Frequency first_lo_frequency = 0;
const bool mixer_invert = false;
return {first_lo_frequency, second_lo_frequency, rf::path::Band::Mid, mixer_invert};
#endif
}
// High band >2740 Mhz:
constexpr rf::Frequency high_band_second_lo_frequency(const rf::Frequency target_frequency) {
#ifdef PRALINE
// Praline formula tuned for MAX2831 (2.3-2.6 GHz range)
// Keep second_lo in MAX2831's range while allowing RFFC5072 to work
if (target_frequency < 3600'000'000)
return 2400'000'000 + ((target_frequency - 2740'000'000) / 4);
else if (target_frequency < 5100'000'000)
return 2500'000'000 + ((target_frequency - 3600'000'000) / 6);
else
return 2550'000'000 + ((target_frequency - 5100'000'000) / 10);
#else
if (target_frequency < 3600'000'000)
return (2170'000'000 + (((target_frequency - 2740'000'000) * 57) / 86));
else if (target_frequency < 5100'000'000)
return (2350'000'000 + ((target_frequency - 3600'000'000) / 5));
else
return (2500'000'000 + ((target_frequency - 5100'000'000) / 9));
#endif
}
Config high_band(const rf::Frequency target_frequency) {
+7 -1
View File
@@ -657,7 +657,13 @@ void GeoMap::move(const float lon, const float lat) {
} else {
if (is_changed) {
set_osm_max_zoom();
redraw_map = true;
double global_center_px = lon_to_pixel_x_tile(lon_, map_osm_real_zoom);
double global_center_py = lat_to_pixel_y_tile(lat_, map_osm_real_zoom);
// Redraw if viewport moved by at least 1 pixel (includes zoom level changes)
if (abs(global_center_px - (r.width() / 2.0) - viewport_top_left_px) >= 1.0 ||
abs(global_center_py - (r.height() / 2.0) - viewport_top_left_py) >= 1.0) {
redraw_map = true;
}
}
}
}
+14
View File
@@ -27,6 +27,10 @@
#include "ui_receiver.hpp"
#include "ui_freqman.hpp"
#ifndef PRALINE
#include "audio.hpp"
#endif
using namespace portapack;
namespace ui {
@@ -591,8 +595,18 @@ AudioVolumeField::AudioVolumeField(
/* fill char */ ' '} {
set_value(receiver_model.normalized_headphone_volume());
#ifdef PRALINE
on_change = [](int32_t v) {
receiver_model.set_normalized_headphone_volume(v);
#else
on_change = [](int32_t vol) {
// don't call receiver model, because this widget shuld be able to handle volume settinsg from any app, regardless of the receiver model's enables state. like the tx apps should be able to set volume too.
// this is identical to the receiver model's method
uint8_t v = clip<uint8_t>(vol, 0, 99);
auto new_volume = volume_t::decibel(v - 99) + audio::headphone::volume_range().max;
persistent_memory::set_headphone_volume(new_volume);
audio::headphone::set_volume(new_volume);
#endif
};
}
+8
View File
@@ -37,9 +37,17 @@ CH_IRQ_HANDLER(USB0_IRQHandler) {
usb0_isr();
if (status & USB0_USBSTS_D_UI) {
#ifdef PRALINE
if (thread_usb_event) {
chSysLockFromIsr();
chEvtSignalI(thread_usb_event, EVT_MASK_USB);
chSysUnlockFromIsr();
}
#else
chSysLockFromIsr();
chEvtSignalI(thread_usb_event, EVT_MASK_USB);
chSysUnlockFromIsr();
#endif
}
if (status & USB0_USBSTS_D_SLI) {
+21 -5
View File
@@ -213,7 +213,11 @@ set(CPPWARN "-Wall -Wextra")
# List all default C defines here, like -D_DEBUG=1
# TODO: Switch -DCRT0_INIT_DATA depending on load from RAM or SPIFI?
# NOTE: _RANDOM_TCC to kill a GCC 4.9.3 error with std::max argument types
set(DDEFS "-DLPC43XX -DLPC43XX_M4 -D__NEWLIB__ -DHACKRF_ONE -DTOOLCHAIN_GCC -DTOOLCHAIN_GCC_ARM -D_RANDOM_TCC=0 -D'VERSION_STRING=\"${VERSION}\"'")
# Use BOARD variable if set, otherwise default to HACKRF_ONE
if(NOT DEFINED BOARD)
set(BOARD "HACKRF_ONE")
endif()
set(DDEFS "-DLPC43XX -DLPC43XX_M4 -D__NEWLIB__ -D${BOARD} -DTOOLCHAIN_GCC -DTOOLCHAIN_GCC_ARM -D_RANDOM_TCC=0 -D'VERSION_STRING=\"${VERSION}\"'")
# List all default ASM defines here, like -D_DEBUG=1
set(DADEFS)
@@ -618,12 +622,12 @@ set(MODE_CPPSRC
)
DeclareTargets(PADT adsbtx)
### OOKStream
### Binary Timed stream TX
set(MODE_CPPSRC
proc_ook_stream_tx.cpp
proc_bint_stream_tx.cpp
)
DeclareTargets(POSK ookstream)
DeclareTargets(POSK bintstream)
### Signal generator
@@ -663,9 +667,10 @@ set(MODE_CPPSRC
)
DeclareTargets(PSCD subcar)
### Morse RX Decoder
set(MODE_CPPSRC
proc_morse.cpp
)
DeclareTargets(PMRS morse)
@@ -676,6 +681,14 @@ set(MODE_INCDIR
${HACKRF_PATH}/firmware/common
${HACKRF_PATH}/firmware/libopencm3/include
)
### Morse TX
set(MODE_CPPSRC
proc_morsetx.cpp
)
DeclareTargets(PMRT morsetx)
set(MODE_CPPSRC
sd_over_usb/proc_sd_over_usb.cpp
@@ -716,7 +729,10 @@ set(MODE_CPPSRC
${HACKRF_PATH}/firmware/libopencm3/lib/lpc43xx/timer.c
${HACKRF_PATH}/firmware/libopencm3/lib/lpc43xx/i2c.c
)
# sd_over_usb has type conflicts with PRALINE (HackRF Pro) - disable for now
if(NOT BOARD STREQUAL "PRALINE")
DeclareTargets(PUSB sd_over_usb)
endif()
### HackRF "factory" firmware
+7
View File
@@ -110,6 +110,9 @@ volatile uint32_t buffer_handled = 0;
static void transfer_complete() {
const auto next_lli_index = gpdma_channel_sgpio.next_lli() - &lli_loop[0];
buffer_transfered++;
#ifdef PRALINE
shared_memory.m4_dma_xfr_count++; // Phase 0 instrumentation
#endif
thread_wait.wake_from_interrupt(next_lli_index);
}
@@ -161,6 +164,10 @@ void disable() {
}
baseband::buffer_t wait_for_buffer() {
#ifdef PRALINE
shared_memory.m4_dma_wait_count++; // Phase 0 instrumentation
#endif
const auto next_index = thread_wait.sleep();
buffer_handled++;
+7
View File
@@ -87,8 +87,15 @@ void BasebandThread::run() {
baseband_sgpio.configure(direction());
baseband::dma::enable(direction());
baseband_sgpio.streaming_enable();
#ifdef PRALINE
shared_memory.m4_streaming_marker = 0xAA; // Phase 0 instrumentation
#endif
while (!chThdShouldTerminate()) {
#ifdef PRALINE
shared_memory.m4_baseband_loops++; // Phase 0 instrumentation
#endif
// TODO: Place correct sampling rate into buffer returned here:
const auto buffer_tmp = baseband::dma::wait_for_buffer();
if (buffer_tmp) {
+3
View File
@@ -99,6 +99,9 @@ void EventDispatcher::on_message(const Message* const message) {
switch (message->id) {
case Message::ID::Shutdown:
on_message_shutdown(*reinterpret_cast<const ShutdownMessage*>(message));
#ifdef PRALINE
shared_memory.baseband_message = nullptr; // Must clear before M4 exits!
#endif
break;
default:
+6
View File
@@ -46,7 +46,13 @@ class EventDispatcher {
}
static inline void events_flag_isr(const eventmask_t events) {
#ifdef PRALINE
if (thread_event_loop) {
chEvtSignalI(thread_event_loop, events);
}
#else
chEvtSignalI(thread_event_loop, events);
#endif
}
private:
+204
View File
@@ -0,0 +1,204 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
KiaV6DecoderStepReset = 0,
KiaV6DecoderStepWaitFirstHigh,
KiaV6DecoderStepCountPreamble,
KiaV6DecoderStepWaitLongHigh,
KiaV6DecoderStepData,
} KiaV6DecoderStep;
#define KIA_V6_XOR_MASK_LOW 0x84AF25FB
#define KIA_V6_XOR_MASK_HIGH 0x638766AB
class FProtoSubCarKiaV6 : public FProtoSubCarBase {
public:
FProtoSubCarKiaV6() {
sensorType = FPC_KIAV6;
te_short = 200;
te_long = 400;
te_delta = 100;
min_count_bit_for_found = 144;
}
void feed(bool level, uint32_t duration) {
uint32_t uVar4, uVar5;
ManchesterEvent event;
bool data_bit;
uint8_t bit_count_inc;
uint32_t step_value;
switch (parser_step) {
case KiaV6DecoderStepReset: // case 0
if (level == 0) {
return;
}
if (DURATION_DIFF(duration, te_short) <
te_delta) {
parser_step = KiaV6DecoderStepWaitFirstHigh;
te_last = duration;
header_count = 0;
FProtoGeneral::manchester_advance(
manchester_state,
ManchesterEventReset,
&manchester_state,
NULL);
}
return;
case KiaV6DecoderStepWaitFirstHigh: { // case 1
if (level != 0) {
return;
}
uint32_t diff_short = DURATION_DIFF(duration, te_short);
uint32_t diff_long = DURATION_DIFF(duration, te_long);
uint32_t diff = (diff_long < diff_short) ? diff_long : diff_short;
if (diff_long < te_delta && diff_long < diff_short) {
if (header_count >= 0x259) { // 601 decimal
header_count = 0;
te_last = duration;
parser_step = KiaV6DecoderStepWaitLongHigh;
return;
}
}
if (diff >= te_delta) {
step_value = KiaV6DecoderStepReset;
goto LAB_reset;
}
if (DURATION_DIFF(te_last, te_short) <
te_delta) {
te_last = duration;
header_count++;
return;
} else {
step_value = KiaV6DecoderStepReset;
goto LAB_reset;
}
}
case KiaV6DecoderStepWaitLongHigh: { // case 2
if (level == 0) {
step_value = KiaV6DecoderStepReset;
goto LAB_reset;
}
uint32_t diff_long_check = DURATION_DIFF(duration, te_long);
uint32_t diff_short_check = DURATION_DIFF(duration, te_short);
if (diff_long_check >= te_delta) {
if (diff_short_check >= te_delta) {
step_value = KiaV6DecoderStepReset;
goto LAB_reset;
}
}
if (DURATION_DIFF(te_last, te_long) >=
te_delta) {
step_value = KiaV6DecoderStepReset;
goto LAB_reset;
}
decode_data = 0;
decode_count_bit = 0;
subghz_protocol_blocks_add_bit(1);
subghz_protocol_blocks_add_bit(1);
subghz_protocol_blocks_add_bit(0);
subghz_protocol_blocks_add_bit(1);
data_part1_low = (uint32_t)(decode_data & 0xFFFFFFFF);
data_part1_high = (uint32_t)((decode_data >> 32) & 0xFFFFFFFF);
bit_count = decode_count_bit;
parser_step = KiaV6DecoderStepData;
return;
}
case KiaV6DecoderStepData: // case 3
if (DURATION_DIFF(duration, te_short) <
te_delta) {
event = (ManchesterEvent)((level & 0x7F) << 1);
goto manchester_process;
} else if (
DURATION_DIFF(duration, te_long) <
te_delta) {
event = (ManchesterEvent)(level ? 6 : 4);
goto manchester_process;
}
step_value = KiaV6DecoderStepReset;
goto LAB_reset;
manchester_process:
if (FProtoGeneral::manchester_advance(
manchester_state, event, &manchester_state, &data_bit)) {
uVar4 = data_part1_low;
uVar5 = (uVar4 << 1) | (data_bit ? 1 : 0);
uint32_t carry = (uVar4 >> 31) & 1;
uVar4 = (data_part1_high << 1) | carry;
data_part1_low = uVar5;
data_part1_high = uVar4;
decode_data = ((uint64_t)uVar4 << 32) | uVar5;
bit_count_inc = bit_count + 1;
bit_count = bit_count_inc;
if (bit_count_inc == 0x40) {
// stored_part1_low = ~uVar5;
// stored_part1_high = ~uVar4;
data_part1_low = 0;
data_part1_high = 0;
} else if (bit_count_inc == 0x80) {
// stored_part2_low = ~uVar5;
// stored_part2_high = ~uVar4;
data_part1_low = 0;
data_part1_high = 0;
}
}
te_last = duration;
if (bit_count != min_count_bit_for_found) {
return;
}
data_count_bit = min_count_bit_for_found;
// data_part3 = ~((uint16_t)data_part1_low);
// kia_v6_decrypt(); --won't
decode_data = data_part1_low | ((uint64_t)data_part1_high << 32);
if (callback) {
callback(this);
}
data_part1_low = 0;
data_part1_high = 0;
bit_count = 0;
step_value = KiaV6DecoderStepReset;
goto LAB_reset;
default:
return;
}
LAB_reset:
parser_step = step_value;
return;
}
uint8_t bit_count = 0;
uint16_t header_count = 0;
ManchesterState manchester_state = ManchesterStateMid1;
uint32_t data_part1_low = 0;
uint32_t data_part1_high = 0;
// uint32_t stored_part1_low = 0;
// uint32_t stored_part1_high = 0;
// uint32_t stored_part2_low = 0;
// uint32_t stored_part2_high = 0;
// uint16_t data_part3 = 0;
};
+1 -1
View File
@@ -76,7 +76,7 @@ class FProtoSubGhzDSecPlusV1 : public FProtoSubGhzDBase {
packet_accepted |= SECPLUS_V1_PACKET_2_ACCEPTED;
if (packet_accepted == (SECPLUS_V1_PACKET_1_ACCEPTED | SECPLUS_V1_PACKET_2_ACCEPTED)) {
// subghz_protocol_secplus_v1_decode(); // disabled doe to lack of flash
// subghz_protocol_secplus_v1_decode(); // disabled due to lack of flash
// controller
// uint32_t fixed = (data >> 32) & 0xFFFFFFFF;
// cnt = data & 0xFFFFFFFF;
@@ -21,6 +21,7 @@ So include here the .hpp, and add a new element to the protos vector in the cons
#include "c-ford_v0.hpp"
#include "c-fiat_v0.hpp"
#include "c-bmw_v0.hpp"
// #include "c-kia_v6.hpp"
#ifndef __FPROTO_PROTOLISTCAR_H__
#define __FPROTO_PROTOLISTCAR_H__
@@ -42,6 +43,7 @@ class SubCarProtos : public FProtoListGeneral {
protos[FPC_FORDV0] = new FProtoSubCarFordV0();
protos[FPC_FIATV0] = new FProtoSubCarFiatV0();
protos[FPC_BMWV0] = new FProtoSubCarBMWV0();
// protos[FPC_KIAV6] = new FProtoSubCarKiaV6(); //-- disabled, due to whole encrypted.
for (uint8_t i = 0; i < FPC_COUNT; ++i) {
if (protos[i] != NULL) protos[i]->setCallback(callbackTarget);
+2 -3
View File
@@ -8,9 +8,6 @@ These values must be present on the protocol's constructor, like FProtoWeatherAc
Also it must have a switch-case element in the getSubGhzDSensorTypeName() function, to display it's name.
*/
#define FPM_AM 0
#define FPM_FM 1
enum FPROTO_SUBCAR_SENSOR : uint8_t {
FPC_Invalid = 0,
FPC_SUZUKI = 1,
@@ -24,6 +21,8 @@ enum FPROTO_SUBCAR_SENSOR : uint8_t {
FPC_FORDV0 = 9,
FPC_FIATV0 = 10,
FPC_BMWV0 = 11,
// FPC_KIAV6 = 12, //disabled, due to whole encrypted.
// FPC_PSA = 13, // IS whole encrypted
FPC_COUNT
};
+10
View File
@@ -29,6 +29,16 @@
#include <array>
#include "dsp_hilbert.hpp"
// Phase 2: Constructor to start threads AFTER object is fully initialized
NarrowbandAMAudio::NarrowbandAMAudio() {
// Initialize members that threads might access
channel_spectrum.set_decimation_factor(1);
// Start threads AFTER everything initialized
baseband_thread.start();
rssi_thread.start();
}
void NarrowbandAMAudio::execute(const buffer_c8_t& buffer) {
if (!configured) {
return;
+8
View File
@@ -37,6 +37,8 @@
class NarrowbandAMAudio : public BasebandProcessor {
public:
NarrowbandAMAudio(); // Phase 2: Explicit constructor for manual thread start
void execute(const buffer_c8_t& buffer) override;
void on_message(const Message* const message) override;
@@ -74,8 +76,14 @@ class NarrowbandAMAudio : public BasebandProcessor {
SpectrumCollector channel_spectrum{};
/* NB: Threads should be the last members in the class definition. */
#ifndef PRALINE
BasebandThread baseband_thread{baseband_fs, this, baseband::Direction::Receive};
RSSIThread rssi_thread{};
#else
BasebandThread baseband_thread{baseband_fs, this, baseband::Direction::Receive,
/*auto_start*/ false}; // Phase 2: Manual start
RSSIThread rssi_thread{/*auto_start*/ false}; // Phase 2: Manual start
#endif
void configure(const AMConfigureMessage& message);
void capture_config(const CaptureConfigMessage& message);
@@ -19,7 +19,7 @@
* Boston, MA 02110-1301, USA.
*/
#include "proc_ook_stream_tx.hpp"
#include "proc_bint_stream_tx.hpp"
#include "sine_table_int8.hpp"
#include "portapack_shared_memory.hpp"
@@ -27,27 +27,35 @@
#include "utility.hpp"
OOKProcessorStreamed::OOKProcessorStreamed() {
BinaryTimedProcessorStreamed::BinaryTimedProcessorStreamed() {
configured = false;
baseband_thread.start();
}
inline void OOKProcessorStreamed::write_sample(const buffer_c8_t& buffer, bool bit_value, size_t i) {
int8_t re, im;
if (bit_value) {
phase = (phase + 200); // What ?
inline void BinaryTimedProcessorStreamed::write_sample(const buffer_c8_t& buffer, bool bit_value, size_t i) {
int8_t re = 0, im = 0;
if (mode == 0) {
if (bit_value) {
phase = (phase + 200);
sphase = phase + (64 << 18);
re = (sine_table_i8[(sphase & 0x03FC0000) >> 18]);
im = (sine_table_i8[(phase & 0x03FC0000) >> 18]);
}
} else if (mode == 1) {
// calculate the re, im based on the deviation uint32_t variable to get the re, im, to send out 2fsk signal. based on the bit_value
if (bit_value) {
phase += deviation_delta;
} else {
phase -= deviation_delta;
}
sphase = phase + (64 << 18);
re = (sine_table_i8[(sphase & 0x03FC0000) >> 18]);
im = (sine_table_i8[(phase & 0x03FC0000) >> 18]);
} else {
re = 0;
im = 0;
}
buffer.p[i] = {re, im};
}
void OOKProcessorStreamed::execute(const buffer_c8_t& buffer) {
void BinaryTimedProcessorStreamed::execute(const buffer_c8_t& buffer) {
if (!configured || !stream) return;
for (size_t i = 0; i < buffer.count; i++) {
@@ -87,7 +95,7 @@ void OOKProcessorStreamed::execute(const buffer_c8_t& buffer) {
}
}
void OOKProcessorStreamed::on_message(const Message* const message) {
void BinaryTimedProcessorStreamed::on_message(const Message* const message) {
switch (message->id) {
case Message::ID::ReplayConfig:
configured = false;
@@ -100,12 +108,23 @@ void OOKProcessorStreamed::on_message(const Message* const message) {
shared_memory.application_queue.push(txprogress_message);
break;
case Message::ID::StreamTXConfiguration:
streamtx_config(*reinterpret_cast<const StreamTXConfigurationMessage*>(message));
break;
default:
break;
}
}
void OOKProcessorStreamed::replay_config(const ReplayConfigMessage& message) {
void BinaryTimedProcessorStreamed::streamtx_config(const StreamTXConfigurationMessage& message) {
mode = message.mode;
deviation = message.deviation;
uint64_t big_calc = (uint64_t)message.deviation << 26;
deviation_delta = (uint32_t)(big_calc / OOK_SAMPLERATE);
}
void BinaryTimedProcessorStreamed::replay_config(const ReplayConfigMessage& message) {
if (message.config) {
txprogress_message.progress = -2;
shared_memory.application_queue.push(txprogress_message);
@@ -121,7 +140,7 @@ void OOKProcessorStreamed::replay_config(const ReplayConfigMessage& message) {
}
int main() {
EventDispatcher event_dispatcher{std::make_unique<OOKProcessorStreamed>()};
EventDispatcher event_dispatcher{std::make_unique<BinaryTimedProcessorStreamed>()};
event_dispatcher.run();
return 0;
}
@@ -34,10 +34,11 @@
#include <memory>
#define OOK_SAMPLERATE 2280000U
#define FM_DEVIATION 60000U
class OOKProcessorStreamed : public BasebandProcessor {
class BinaryTimedProcessorStreamed : public BasebandProcessor {
public:
OOKProcessorStreamed();
BinaryTimedProcessorStreamed();
void execute(const buffer_c8_t& buffer) override;
void on_message(const Message* const message) override;
@@ -53,6 +54,11 @@ class OOKProcessorStreamed : public BasebandProcessor {
std::unique_ptr<StreamOutput> stream{};
bool configured{false};
void replay_config(const ReplayConfigMessage& message);
void streamtx_config(const StreamTXConfigurationMessage& message);
uint8_t mode = 0; // am = 0, 2fsk = 1
uint32_t deviation = FM_DEVIATION; // used in 2fsk
uint32_t deviation_delta = (FM_DEVIATION * 4294967296ULL) / OOK_SAMPLERATE;
int32_t endsignals[3] = {0, 42069, 613379}; // 0 is skipped, count from 1, don't ask...
uint8_t readerrs = 0; // to count in the array
+59 -34
View File
@@ -28,26 +28,32 @@
void MorseProcessor::configure(uint8_t mode) {
configured = false;
if (mode == 0) { // CW/FM
modulation = static_cast<ModulationMode>((uint8_t)mode);
if (modulation == ModulationMode::FM) { // FM
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_cw_fm.configure(24000, 5000);
} else { // USB, LSB
decim_0.configure(taps_6k0_decim_0.taps);
decim_1.configure(taps_6k0_decim_1.taps);
if (mode == 1) // USB
channel_filter.configure(taps_2k8_usb_channel.taps, 4);
else // LSB
channel_filter.configure(taps_2k8_lsb_channel.taps, 4);
} else {
decim_0.configure(taps_4k25_decim_0.taps);
decim_1.configure(taps_4k25_decim_1.taps);
if (modulation == ModulationMode::AM) { // AM
channel_filter.configure(taps_2k0_am_lpf_channel.taps, 4);
} else { // SSB, DSB
if (modulation == ModulationMode::DSB) // DSB
channel_filter.configure(taps_1k5_dsb_lpf.taps, 4);
else if (modulation == ModulationMode::USB) // USB
channel_filter.configure(taps_1k5_USB_channel.taps, 4);
else // LSB
channel_filter.configure(taps_1k5_LSB_channel.taps, 4);
}
}
modulation = mode;
if (mode > 0)
audio_output.configure(audio_12k_hpf_300hz_config);
else
if (modulation == ModulationMode::FM)
audio_output.configure(iir_config_passthrough, iir_config_passthrough, (float)user_squelch_level / 100.0f);
else
audio_output.configure(audio_12k_hpf_300hz_config);
meas_samples_in_period = 0;
meas_last_period_len = 0;
@@ -70,6 +76,8 @@ void MorseProcessor::configure(uint8_t mode) {
squelch_is_open = true;
squelch_hold = 0;
dc_average = 0.0f;
current_freq = 700.0f;
update_goertzel_coeff(current_freq);
@@ -77,10 +85,15 @@ void MorseProcessor::configure(uint8_t mode) {
}
inline buffer_f32_t MorseProcessor::demodulate(const buffer_c16_t& channel) {
if (modulation > 0) {
// SSB always keeps squelch "technically" open for the demodulator
// AM,SSB,DSB always keeps squelch "technically" open for the demodulator
if (modulation == ModulationMode::AM || modulation == ModulationMode::DSB) {
squelch_is_open = true;
return demod_ssb.execute(channel, audio_buffer);
return demod_AM.execute(channel, audio_buffer);
} else {
if (modulation == ModulationMode::USB || modulation == ModulationMode::LSB) {
squelch_is_open = true;
return demod_ssb.execute(channel, audio_buffer);
}
}
return demod_cw_fm.execute(channel, audio_buffer);
}
@@ -90,7 +103,7 @@ void MorseProcessor::update_goertzel_coeff(float freq) {
if (freq < 300.0f) freq = 300.0f;
if (freq > 2300.0f) freq = 2300.0f;
float sample_rate = (modulation == 0) ? 24000.0f : 12000.0f;
float sample_rate = (modulation == ModulationMode::FM) ? 24000.0f : 12000.0f;
float omega = 2.0f * M_PI * freq / sample_rate;
float omega_sq = omega * omega;
float cos_approx = 1.0f - (omega_sq * 0.5f);
@@ -100,7 +113,7 @@ void MorseProcessor::update_goertzel_coeff(float freq) {
void MorseProcessor::measure_frequency(int32_t sample) {
// Noise gate threshold
const int32_t gate_threshold = (modulation == 0) ? 4000 : 2000;
const int32_t gate_threshold = (modulation == ModulationMode::FM) ? 4000 : 2000;
if (sample > gate_threshold || sample < -gate_threshold) {
if (sample > 0 && !meas_signal_state_high) {
@@ -111,7 +124,7 @@ void MorseProcessor::measure_frequency(int32_t sample) {
bool period_is_stable = false;
if (meas_last_period_len > 0) {
int32_t diff = std::abs((int)meas_samples_in_period - (int)meas_last_period_len);
if (diff <= 1) {
if (diff <= 2) {
meas_consistency_count++;
period_is_stable = true;
} else {
@@ -121,10 +134,12 @@ void MorseProcessor::measure_frequency(int32_t sample) {
meas_last_period_len = meas_samples_in_period;
// Wait for AT LEAST 3 STABLE CYCLES
if (period_is_stable && meas_consistency_count > 3) {
float base_rate = (modulation == 0) ? 24000.0f : 12000.0f;
if (period_is_stable && meas_consistency_count > 5) {
float base_rate = (modulation == ModulationMode::FM) ? 24000.0f : 12000.0f;
float inst_freq = base_rate / (float)meas_samples_in_period;
if (modulation == ModulationMode::DSB) {
inst_freq /= 2.0f;
}
// Check for overflows
if (inst_freq > 250 && inst_freq < 3000) {
meas_freq_accumulator += inst_freq;
@@ -148,7 +163,7 @@ void MorseProcessor::measure_frequency(int32_t sample) {
meas_samples_in_period++;
ui_update_timer++;
uint32_t update_limit = (modulation == 0) ? 4800 : 2400; // ~200ms
uint32_t update_limit = (modulation == ModulationMode::FM) ? 4800 : 2400; // ~200ms
if (ui_update_timer > update_limit) {
if (meas_freq_count > 0) {
@@ -202,7 +217,7 @@ void MorseProcessor::process_decoding(int32_t sample) {
// Tone Detection
bool is_tone = squelch_is_open && (power > current_pwr_threshold) && (power > 150000);
int32_t time_base = modulation == 0 ? 125 : 250;
int32_t time_base = 250;
// State Change Logic
if (is_tone != was_signaling) {
int32_t duration_us = (int32_t)((int64_t)duration_samples * time_base / 3);
@@ -254,33 +269,43 @@ void MorseProcessor::execute(const buffer_c8_t& buffer) {
if (raw_int_abs > audio_threshold || user_squelch_level == 0) {
squelch_is_open = true;
squelch_hold = (modulation == 0) ? 2400 : 1200;
squelch_hold = (modulation == ModulationMode::FM) ? 2400 : 1200;
} else {
if (squelch_hold > 0)
squelch_hold--;
else if (modulation == 0)
else if (modulation == ModulationMode::FM)
squelch_is_open = false;
}
measure_frequency((int32_t)(raw_audio * 32768.0f));
float decode_audio = raw_audio;
if (modulation > 0) {
const float gain = 6.0f;
if (modulation != ModulationMode::FM) {
float gain = 16.0f;
if (modulation == ModulationMode::USB || modulation == ModulationMode::LSB)
gain = 5.0f;
decode_audio *= gain;
// Hard Limiting / Clipping
if (decode_audio > 1.0f)
message.clipped = false;
if (decode_audio > 1.0f) {
decode_audio = 1.0f;
else if (decode_audio < -1.0f)
message.clipped = true;
} else if (decode_audio < -1.0f) {
decode_audio = -1.0f;
}
audio_buf.p[i] = decode_audio;
}
// DC BLOCKING
if (modulation != ModulationMode::FM) {
dc_average = (dc_average * 0.95f) + (decode_audio * 0.05f);
measure_frequency((int32_t)((decode_audio - dc_average) * 32768.0f));
} else {
measure_frequency((int32_t)(raw_audio * 32768.0f));
}
process_decoding((int32_t)(decode_audio * 32768.0f));
if (modulation == 0 && !squelch_is_open) {
if (modulation == ModulationMode::FM && !squelch_is_open) {
audio_buf.p[i] = 0.0f; // mute nfm on squelch
}
}
+13 -2
View File
@@ -60,13 +60,22 @@ class MorseProcessor : public BasebandProcessor {
dsp::decimate::FIRC8xR16x24FS4Decim8 decim_0{};
dsp::decimate::FIRC16xR16x32Decim8 decim_1{};
dsp::decimate::FIRAndDecimateComplex channel_filter{};
dsp::demodulate::AM demod_AM{};
dsp::demodulate::FM demod_cw_fm{};
dsp::demodulate::SSB demod_ssb{};
AudioOutput audio_output{};
bool configured{false};
uint8_t modulation{0}; // 0=CW/FM, 1=USB, 2=LSB
enum class ModulationMode : uint8_t {
AM = 0,
FM = 1,
DSB = 2,
USB = 3,
LSB = 4
};
ModulationMode modulation = ModulationMode::AM;
int32_t user_squelch_level{0};
bool squelch_is_open{true};
int32_t squelch_hold{0};
@@ -79,7 +88,6 @@ class MorseProcessor : public BasebandProcessor {
float meas_freq_accumulator{0.0f};
uint32_t meas_freq_count{0};
uint32_t ui_update_timer{0};
float current_freq{700.0f};
// --- Decoding variables (Goertzel) ---
@@ -92,6 +100,9 @@ class MorseProcessor : public BasebandProcessor {
int64_t noise_floor{5000};
int32_t startup_delay{20};
float dc_average = 0.0f; // DC level tracking
int32_t dc_average_int = 0;
MorseRXDataMessage message{};
MorseRXfreqMessage freq_message{};
};
+97
View File
@@ -0,0 +1,97 @@
#include "proc_morsetx.hpp"
#include "portapack_shared_memory.hpp"
#include "sine_table_int8.hpp"
#include "event_m4.hpp"
#include <cstdint>
void MorseTXProcessor::execute(const buffer_c8_t& buffer) {
if (!configured) return;
for (size_t i = 0; i < buffer.count; i++) {
int8_t sample_sin;
int8_t sample_cos;
sample_sin = (sine_table_i8[(tone_phase & 0xFF000000) >> 24]);
tone_phase += tone_delta;
im = 0;
re = 0;
// modulation logic
if (modulation == 0) { // AM modulation
if (key_down) {
re = 64 + (sample_sin >> 2);
}
} else if (modulation == 1) { // FM modulation
if (key_down) {
delta = sample_sin * fm_delta;
} else {
delta = 0;
}
phase += delta;
sphase = phase + (64 << 24);
re = (sine_table_i8[(sphase & 0xFF000000) >> 24]);
im = (sine_table_i8[(phase & 0xFF000000) >> 24]);
} else if (modulation == 2) { // DSB
if (key_down) {
re = sample_sin;
}
} else if (modulation == 3) { // USB
if (key_down) {
sample_cos = (sine_table_i8[((tone_phase + 0x40000000) & 0xFF000000) >> 24]);
re = sample_cos;
im = sample_sin;
}
} else if (modulation == 4) { // LSB
if (key_down) {
sample_cos = (sine_table_i8[((tone_phase + 0x40000000) & 0xFF000000) >> 24]);
re = sample_cos;
im = (sine_table_i8[((tone_phase + 0x80000000) & 0xFF000000) >> 24]);
}
}
buffer.p[i] = {re, im};
}
}
void MorseTXProcessor::on_message(const Message* const p) {
switch (p->id) {
case Message::ID::MorseTXConfigure: {
auto message = *reinterpret_cast<const MorseTXConfigureMessage*>(p);
tone_delta = message.tone * 1398; // scale
tone = message.tone; // audio tone
modulation = message.modulation;
if (message.fm_delta == 0 && modulation == 1) {
fm_delta = 90000;
} else {
uint64_t scale = 0xFFFFFFFFULL; // 32-bit max
fm_delta = (uint32_t)((uint64_t)message.fm_delta * (scale / 1536000));
}
break;
}
case Message::ID::MorseTXkey: {
auto key = *reinterpret_cast<const MorseTXkeyMessage*>(p);
key_down = key.key_down;
configured = true;
if (key_down)
audio::dma::beep_start(tone, 24000, 0);
else
audio::dma::beep_stop();
break;
}
default:
break;
}
}
int main() {
audio::dma::init_audio_out();
EventDispatcher event_dispatcher{std::make_unique<MorseTXProcessor>()};
event_dispatcher.run();
return 0;
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef __PROC_MORSETX_H__
#define __PROC_MORSETX_H__
#include "baseband_processor.hpp"
#include "baseband_thread.hpp"
#include "portapack_shared_memory.hpp"
#include "audio_output.hpp"
#include "audio_dma.hpp"
#define AUDIO_OUTPUT_BUFFER_SIZE 32
#define AUDIO_SAMPLING_RATE 24000
class MorseTXProcessor : public BasebandProcessor {
public:
void execute(const buffer_c8_t& buffer) override;
void on_message(const Message* const msg) override;
private:
bool configured{false};
bool key_down{false}; // currently the virtual key is pressed or not.
int8_t sample{0}, re{0}, im{0};
uint8_t modulation{0}; // 0=AM, 1=FM, 2=DSB, 3=USB, 4=LSB
uint32_t tone_delta{0}; // shifting value by tone
uint32_t fm_delta{};
uint32_t tone_phase{0};
uint32_t tone{0}; // audio tone frequeny
int32_t phase{0}, sphase{0}, delta{0}; // sample generation.
BasebandThread baseband_thread{1536000, this, baseband::Direction::Transmit};
};
#endif
+12
View File
@@ -31,6 +31,18 @@
#include <cstdint>
#include <cstddef>
#ifdef PRALINE
// Phase 2: Constructor to start threads AFTER object is fully initialized
NarrowbandFMAudio::NarrowbandFMAudio() {
// Initialize members that threads might access
channel_spectrum.set_decimation_factor(1);
// Start threads AFTER everything initialized
baseband_thread.start();
rssi_thread.start();
}
#endif
void NarrowbandFMAudio::execute(const buffer_c8_t& buffer) {
// bool new_state;
+10
View File
@@ -41,6 +41,10 @@
class NarrowbandFMAudio : public BasebandProcessor {
public:
#ifdef PRALINE
NarrowbandFMAudio(); // Phase 2: Explicit constructor for manual thread start
#endif
void execute(const buffer_c8_t& buffer) override;
void on_message(const Message* const message) override;
@@ -97,8 +101,14 @@ class NarrowbandFMAudio : public BasebandProcessor {
CodedSquelchMessage ctcss_message{0};
/* NB: Threads should be the last members in the class definition. */
#ifdef PRALINE
BasebandThread baseband_thread{baseband_fs, this, baseband::Direction::Receive,
/*auto_start*/ false}; // Phase 2: Manual start
RSSIThread rssi_thread{/*auto_start*/ false}; // Phase 2: Manual start
#else
BasebandThread baseband_thread{baseband_fs, this, baseband::Direction::Receive};
RSSIThread rssi_thread{};
#endif
void pitch_rssi_config(const PitchRSSIConfigureMessage& message);
void configure(const NBFMConfigureMessage& message);
+99 -126
View File
@@ -25,14 +25,6 @@
#include "portapack_shared_memory.hpp"
#include "event_m4.hpp"
static inline int get_quadrant(int16_t i, int16_t q) {
if (i >= 0) {
return (q >= 0) ? 0 : 3;
} else {
return (q >= 0) ? 1 : 2;
}
}
void SubCarProcessor::execute(const buffer_c8_t& buffer) {
if (!configured) return;
@@ -46,10 +38,6 @@ void SubCarProcessor::execute(const buffer_c8_t& buffer) {
const auto decim_1_out = decim_1.execute(decim_0_out, dst_buffer); // Input:512 complex/2 (decim factor) = 256_output complex ( 512 I/Q samples)
feed_channel_stats(decim_1_out);
// for fm
const int32_t DC_ALPHA = 5; // Auto-centering speed
int32_t buffer_rotation_sum = 0;
for (size_t i = 0; i < decim_1_out.count; i++) {
// am
threshold = (low_estimate + high_estimate) / 2;
@@ -57,126 +45,103 @@ void SubCarProcessor::execute(const buffer_c8_t& buffer) {
int16_t re = decim_1_out.p[i].real();
int16_t im = decim_1_out.p[i].imag();
uint32_t mag = ((uint32_t)re * (uint32_t)re) + ((uint32_t)im * (uint32_t)im);
mag = (mag >> 10);
int32_t const ook_low_delta = mag - low_estimate;
bool meashl = currentHiLow;
if (sig_state == STATE_IDLE) {
if (mag > (threshold + hysteresis)) { // just become high
meashl = true;
sig_state = STATE_PULSE;
numg = 0;
} else {
meashl = false; // still low
low_estimate += ook_low_delta / OOK_EST_LOW_RATIO;
low_estimate += ((ook_low_delta > 0) ? 1 : -1); // Hack to compensate for lack of fixed-point scaling
// Calculate default OOK high level estimate
high_estimate = 1.35 * low_estimate; // Default is a ratio of low level
high_estimate = std::max(high_estimate, min_high_level);
high_estimate = std::min(high_estimate, (uint32_t)OOK_MAX_HIGH_LEVEL);
}
} else if (sig_state == STATE_PULSE) {
++numg;
if (numg > 100) numg = 100;
if (mag < (threshold - hysteresis)) {
// check if really a bad value
if (numg < 3) {
// susp
sig_state = STATE_GAP;
} else {
if (modulation == 0) {
int32_t const ook_low_delta = mag - low_estimate;
bool meashl = currentHiLow;
if (sig_state == STATE_IDLE) {
if (mag > (threshold + hysteresis)) { // just become high
meashl = true;
sig_state = STATE_PULSE;
numg = 0;
sig_state = STATE_GAP_START;
} else {
meashl = false; // still low
low_estimate += ook_low_delta / OOK_EST_LOW_RATIO;
low_estimate += ((ook_low_delta > 0) ? 1 : -1); // Hack to compensate for lack of fixed-point scaling
// Calculate default OOK high level estimate
high_estimate = 1.35 * low_estimate; // Default is a ratio of low level
high_estimate = std::max(high_estimate, min_high_level);
high_estimate = std::min(high_estimate, (uint32_t)OOK_MAX_HIGH_LEVEL);
}
} else if (sig_state == STATE_PULSE) {
++numg;
if (numg > 100) numg = 100;
if (mag < (threshold - hysteresis)) {
// check if really a bad value
if (numg < 3) {
// susp
sig_state = STATE_GAP;
} else {
numg = 0;
sig_state = STATE_GAP_START;
}
meashl = false; // low
} else {
high_estimate += mag / OOK_EST_HIGH_RATIO - high_estimate / OOK_EST_HIGH_RATIO;
high_estimate = std::max(high_estimate, min_high_level);
high_estimate = std::min(high_estimate, (uint32_t)OOK_MAX_HIGH_LEVEL);
meashl = true; // still high
}
} else if (sig_state == STATE_GAP_START) {
++numg;
if (mag > (threshold + hysteresis)) { // New pulse?
sig_state = STATE_PULSE;
meashl = true;
} else if (numg >= 3) {
sig_state = STATE_GAP;
meashl = false; // gap
}
} else if (sig_state == STATE_GAP) {
++numg;
if (mag > (threshold + hysteresis)) { // New pulse?
numg = 0;
sig_state = STATE_PULSE;
meashl = true;
} else {
meashl = false;
}
}
if (meashl == currentHiLow && currentDuration < 30'000'000) // allow pass 'end' signal
{
currentDuration += nsPerDecSamp;
} else { // called on change, so send the last duration and dir.
if (currentDuration >= 30'000'000) sig_state = STATE_IDLE;
if (protoList) protoList->feed(currentHiLow, currentDuration / 1000);
currentDuration = nsPerDecSamp;
currentHiLow = meashl;
}
}
if (modulation == 1) {
int32_t discrim = ((int32_t)im * fm_state.last_re) - ((int32_t)re * fm_state.last_im);
fm_state.last_re = re;
fm_state.last_im = im;
fm_state.smoothed_discrim += (discrim - fm_state.smoothed_discrim) >> 4;
// --- FM Part (Simple 2-FSK) ---
if (mag > (threshold / 2)) {
const int32_t fm_hysteresis = 2000;
bool new_level = fm_state.current_logic_level;
if (fm_state.smoothed_discrim > fm_hysteresis) {
new_level = true;
} else if (fm_state.smoothed_discrim < -fm_hysteresis) {
new_level = false;
}
if (new_level == fm_state.current_logic_level) {
fm_state.buffer_count++;
} else {
int32_t duration_us = (fm_state.buffer_count * nsPerDecSamp) / 1000;
if (duration_us > 15) {
if (protoList) protoList->feed(fm_state.current_logic_level, duration_us);
}
fm_state.current_logic_level = new_level;
fm_state.buffer_count = 1;
}
meashl = false; // low
} else {
high_estimate += mag / OOK_EST_HIGH_RATIO - high_estimate / OOK_EST_HIGH_RATIO;
high_estimate = std::max(high_estimate, min_high_level);
high_estimate = std::min(high_estimate, (uint32_t)OOK_MAX_HIGH_LEVEL);
meashl = true; // still high
}
} else if (sig_state == STATE_GAP_START) {
++numg;
if (mag > (threshold + hysteresis)) { // New pulse?
sig_state = STATE_PULSE;
meashl = true;
} else if (numg >= 3) {
sig_state = STATE_GAP;
meashl = false; // gap
}
} else if (sig_state == STATE_GAP) {
++numg;
if (mag > (threshold + hysteresis)) { // New pulse?
numg = 0;
sig_state = STATE_PULSE;
meashl = true;
} else {
meashl = false;
fm_state.buffer_count = 0;
}
}
if (meashl == currentHiLow && currentDuration < 30'000'000) // allow pass 'end' signal
{
currentDuration += nsPerDecSamp;
} else { // called on change, so send the last duration and dir.
if (currentDuration >= 30'000'000) sig_state = STATE_IDLE;
if (protoList) protoList->feed(currentHiLow, currentDuration / 1000);
currentDuration = nsPerDecSamp;
currentHiLow = meashl;
}
// fm part: -- NOT WORKING!!!! TODO FIX. AI code ;)
int current_quad = get_quadrant(re, im);
// Calculate Step (Current - Previous)
int diff = current_quad - fm_state.prev_quad;
// Handle Wrap-Around (crossing from Q3 to Q0 or Q0 to Q3)
// 3 -> 0 should be +1 (CCW)
// 0 -> 3 should be -1 (CW)
if (diff == -3)
diff = 1;
else if (diff == 3)
diff = -1;
// Update History
fm_state.prev_quad = current_quad;
// Accumulate Rotation
buffer_rotation_sum += diff;
}
// fm finish:
// 3. AUTO-CENTERING (DC BLOCKER)
// Even with quadrant counting, "drift" (hand effect) makes the wheel spin
// faster or slower. We need to subtract the average speed.
// Update our "Average Speed" estimate
// Note: buffer_rotation_sum is roughly proportional to frequency.
fm_state.dc_offset = (fm_state.dc_offset * ((1 << DC_ALPHA) - 1) + buffer_rotation_sum) >> DC_ALPHA;
// Remove the drift
int32_t centered_rotation = buffer_rotation_sum - fm_state.dc_offset;
// 4. LOW PASS FILTER
const int32_t LPF_ALPHA = 4;
fm_state.smoothed_error = (fm_state.smoothed_error * (LPF_ALPHA - 1) + centered_rotation) / LPF_ALPHA;
// 5. DECISION LOGIC
// Threshold is small now because we are counting quadrant steps.
// Max steps per buffer (256 samples) is 256.
// Typical FSK deviation might give you +/- 10 to 50 steps per buffer.
const int32_t THRESHOLD = 3;
bool new_level = fm_state.current_logic_level;
if (fm_state.smoothed_error > THRESHOLD) {
new_level = true;
} else if (fm_state.smoothed_error < -THRESHOLD) {
new_level = false;
}
// 6. TIMING OUTPUT
if (new_level == fm_state.current_logic_level) {
fm_state.buffer_count++;
} else {
// Output pulse duration
int32_t duration_us = fm_state.buffer_count * 512;
if (duration_us > 250) {
if (protoListFm) protoListFm->feed(fm_state.current_logic_level, duration_us);
}
fm_state.current_logic_level = new_level;
fm_state.buffer_count = 1;
}
}
@@ -189,6 +154,14 @@ void SubCarProcessor::configure(const SubGhzFPRxConfigureMessage& message) {
// constexpr size_t decim_0_output_fs = baseband_fs / decim_0.decimation_factor; //unused
// constexpr size_t decim_1_output_fs = decim_0_output_fs / decim_1.decimation_factor; //unused
if (modulation != message.modulation) {
// reload protos to reset them all
if (protoList) {
delete protoList;
}
protoList = new SubCarProtos();
}
modulation = message.modulation;
baseband_fs = message.sampling_rate;
baseband_thread.set_sampling_rate(baseband_fs);
nsPerDecSamp = 1'000'000'000 / baseband_fs * 8; // Scaled it due to less array buffer sampes due to /8 decimation. 250 nseg (4Mhz) * 8
+8 -8
View File
@@ -56,8 +56,8 @@ class SubCarProcessor : public BasebandProcessor {
uint32_t low_estimate = 100;
uint32_t high_estimate = 12000;
uint32_t min_high_level = 10;
uint8_t numg = 0; // count of matched signals to filter spikes
size_t baseband_fs = 0; // will be set later by configure message
uint8_t numg = 0; // count of matched signals to filter spikes
size_t baseband_fs = 4'000'000; // will be set later by configure message
uint32_t nsPerDecSamp = 0;
/* Array Buffer aux. used in decim0 and decim1 IQ c16 signed data ; (decim0 defines the max length of the array) */
@@ -74,20 +74,20 @@ class SubCarProcessor : public BasebandProcessor {
uint32_t threshold = 0x0630;
bool currentHiLow = false;
bool configured{false};
uint8_t mode = 0; // 0 = am, 1 = fm
// fm part:
struct DemodFMState {
int prev_quad = 0; // Stores 0, 1, 2, or 3
int32_t dc_offset = 0;
int32_t smoothed_error = 0;
bool current_logic_level = false;
uint32_t buffer_count = 0;
int16_t last_re = 0; // Store previous Real sample
int16_t last_im = 0;
int32_t smoothed_discrim = 0;
};
DemodFMState fm_state{};
FProtoListGeneral* protoList = new SubCarProtos(); // holds all the protocols we can parse
FProtoListGeneral* protoListFm = new SubCarProtos(); // holds all the protocols we can parse, but for fm (dupe, bc most of it is dual)
uint8_t modulation = 0; // 0 am, 1 fm
FProtoListGeneral* protoList = new SubCarProtos(); // holds all the protocols we can parse
void configure(const SubGhzFPRxConfigureMessage& message);
/* NB: Threads should be the last members in the class definition. */
+2 -1
View File
@@ -25,6 +25,7 @@
#include <libopencm3/lpc43xx/scu.h>
#include <libopencm3/lpc43xx/rgu.h>
#include <libopencm3/lpc43xx/wwdt.h>
#include "delay.h"
volatile bool usb_bulk_block_done = false;
@@ -296,4 +297,4 @@ void scsi_command(msd_cbw_t* msd_cbw_data) {
}
usb_send_csw(msd_cbw_data, status);
}
}
@@ -3,7 +3,20 @@ set(BOARDSRC
${CHIBIOS_PORTAPACK}/boards/PORTAPACK_APPLICATION/board.cpp
)
# Add FPGA bridge for PRALINE (HackRF Pro)
if(BOARD STREQUAL "PRALINE")
list(APPEND BOARDSRC
${CHIBIOS_PORTAPACK}/boards/PORTAPACK_APPLICATION/fpga_bridge.c
${CHIBIOS_PORTAPACK}/../../hackrf/firmware/common/lz4_blk.c
)
endif()
# Required include directories
set(BOARDINC
${CHIBIOS_PORTAPACK}/boards/PORTAPACK_APPLICATION
)
# Add hackrf common include for PRALINE (for lz4_blk.h)
if(BOARD STREQUAL "PRALINE")
list(APPEND BOARDINC ${CHIBIOS_PORTAPACK}/../../hackrf/firmware/common)
endif()
@@ -15,13 +15,22 @@
limitations under the License.
*/
#include "ch.h"
#include "hal.h"
#include <array>
// Declare wrapper function. board.cpp to avoid conflicting gpio_t definitions.
bool hackrf_r9;
// Declare the bridge function (no need to include HackRF headers here)
#ifdef PRALINE
extern "C" {
int fpga_bridge_init(void);
}
#endif
#if HAL_USE_PAL || defined(__DOXYGEN__)
/**
* @brief PAL setup.
@@ -262,9 +271,9 @@ const PALConfig pal_default_config = {
{ 4, 7, scu_config_normal_drive_t { .mode=1, .epd=0, .epun=0, .ehs=0, .ezi=1, .zif=1 } }, /* GP_CLKIN/P72/MCU_CLK: SI5351C.CLK7(O) */
/* HackRF: LEDs. Configured early so we can use them to indicate boot status. */
{ 4, 1, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } }, /* LED1: LED1.A(I) */
{ 4, 2, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } }, /* LED2: LED2.A(I) */
{ 6, 12, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } }, /* LED3: LED3.A(I) */
{ 4, 1, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=0, .ehs=0, .ezi=0, .zif=0 } }, /* LED1: LED1.A(I) */
{ 4, 2, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=0, .ehs=0, .ezi=0, .zif=0 } }, /* LED2: LED2.A(I) */
{ 6, 12, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=0, .ehs=0, .ezi=0, .zif=0 } }, /* LED3: LED3.A(I) */
/* Power control */
{ 6, 11, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } }, /* VREGMODE/P69: TPS62410.MODE/DATA(I) */
@@ -332,11 +341,12 @@ const PALConfig pal_default_config = {
{ 4, 9, scu_config_normal_drive_t { .mode=4, .epd=0, .epun=0, .ehs=0, .ezi=0, .zif=0 } }, /* SGPIO14/BANK2F3M4: CPLD.81/CPLD_P81 */
{ 4, 10, scu_config_normal_drive_t { .mode=4, .epd=0, .epun=0, .ehs=0, .ezi=0, .zif=0 } }, /* SGPIO15/BANK2F3M6: CPLD.78/CPLD_P78 */
/* HackRF: CPLD */
{ 6, 1, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } }, /* CPLD_TCK: CPLD.TCK(I), PortaPack CPLD.TCK(I) */
{ 6, 2, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=1, .zif=0 } }, /* CPLD_TDI: CPLD.TDI(I), PortaPack I2S0_RX_SDA(O), PortaPack CPLD.TDI(I) */
{ 6, 5, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } }, /* CPLD_TMS: CPLD.TMS(I) */
{ 9, 5, scu_config_normal_drive_t { .mode=4, .epd=0, .epun=0, .ehs=0, .ezi=1, .zif=0 } }, /* CPLD_TDO: CPLD.TDO(O) */
/* PortaPack CPLD JTAG pins - same for all builds including PRALINE
* (PRALINE FPGA uses P5_1/P5_2/P4_10, not these pins) */
{ 6, 1, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } }, /* CPLD_TCK: PortaPack CPLD.TCK(I) */
{ 6, 2, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=1, .zif=0 } }, /* CPLD_TDI: PortaPack CPLD.TDI(I), I2S0_RX_SDA(O) */
{ 6, 5, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } }, /* CPLD_TMS: HackRF CPLD.TMS(I) */
{ 9, 5, scu_config_normal_drive_t { .mode=4, .epd=0, .epun=0, .ehs=0, .ezi=1, .zif=0 } }, /* CPLD_TDO: HackRF CPLD.TDO(O) */
/* PortaPack CPLD */
{ 1, 5, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=0, .ehs=0, .ezi=1, .zif=0 } }, /* SD_POW: PortaPack CPLD.TDO(O) */
@@ -619,6 +629,10 @@ static const motocon_pwm_resources_t motocon_pwm_resources = {
static const scu_setup_t pin_setup_vaa_enablex_pwm = { 5, 0, scu_config_normal_drive_t { .mode=1, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } };
static const scu_setup_t pin_setup_vaa_enablex_gpio_og = { 5, 0, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } };
static const scu_setup_t pin_setup_vaa_enablex_gpio_r9 = { 6, 10, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } };
#ifdef PRALINE
/* PRALINE uses P8_1 (GPIO4[1]) for VAA_DISABLE (high = VAA off, low = VAA on) */
static const scu_setup_t pin_setup_vaa_disable_praline = { 8, 1, scu_config_normal_drive_t { .mode=0, .epd=0, .epun=1, .ehs=0, .ezi=0, .zif=0 } };
#endif
/* VAA powers:
* MAX5864 analog section.
@@ -824,7 +838,11 @@ extern "C" void __late_init(void) {
* @todo Add your board-specific code, if any.
*/
extern "C" void boardInit(void) {
#ifndef PRALINE
/* Detect HackRF variant */
/* 1. Perform Standard Initialization first */
/* This configures VAA power, LED pins, and detects board revision */
/* Let detect_hackrf_r9() run - don't force for PRALINE */
hackrf_r9 = detect_hackrf_r9();
/* Configure variant-dependent pins. */
if (hackrf_r9) {
@@ -834,12 +852,143 @@ extern "C" void boardInit(void) {
setup_gpios(gpio_setup_og);
setup_pins(pins_setup_og);
}
/* 2. Turn on VAA (Critical for Radio/Transceiver) */
vaa_power_on();
/* 3. Handle VAA Enable Pin Latching */
if (hackrf_r9) {
LPC_GPIO->W2[9] = 1;
} else {
LPC_GPIO->W3[6] = 1;
}
/* 4. HackRF Pro Specific: Initialize and Load FPGA */
#else
hackrf_r9 = false;
/* Enable 3.3V aux power - P6_7 = GPIO5[15], active LOW (clear to enable) */
LPC_SCU->SFSP[6][7] = 0xF4; /* SCU_GPIO_FAST | FUNCTION4 */
LPC_GPIO->DIR[5] |= (1 << 15);
LPC_GPIO->CLR[5] = (1 << 15); /* Clear = enable 3.3V aux */
{ volatile uint32_t delay = 100000; while(delay--); }
/* Enable 1.2V for FPGA - P8_7 = GPIO4[7], active high */
LPC_SCU->SFSP[8][7] = 0x10;
LPC_GPIO->DIR[4] |= (1 << 7);
LPC_GPIO->SET[4] = (1 << 7);
{ volatile uint32_t delay = 100000; while(delay--); }
/* Enable VAA for RF - P8_1 = GPIO4[1], active low */
LPC_SCU->SFSP[8][1] = 0x10;
LPC_GPIO->DIR[4] |= (1 << 1);
LPC_GPIO->CLR[4] = (1 << 1);
{ volatile uint32_t delay = 100000; while(delay--); }
/* Configure RFFC5072 pins for PRALINE */
/* P9_2 = GPIO4[14] RFFC5072 data (SCU_GPIO_FAST | FUNCTION0 = 0xF0) */
LPC_SCU->SFSP[9][2] = 0xF0;
/* P9_5 = GPIO5[18] RFFC5072 clock (SCU_GPIO_FAST | FUNCTION4 = 0xF4) */
LPC_SCU->SFSP[9][5] = 0xF4;
LPC_GPIO->DIR[5] |= (1 << 18); /* Clock as output */
/* Configure Port D pins for PRALINE (use SFSPD registers) */
/* PD_14 = GPIO6[28] MAX2831 chip select */
LPC_SCU->SFSPD[14] = 0xF4; /* SCU_GPIO_FAST | FUNCTION4 */
LPC_GPIO->SET[6] = (1 << 28); /* CS high (inactive) */
LPC_GPIO->DIR[6] |= (1 << 28); /* Output */
/* PD_15 = GPIO6[29] MAX2831 RXHP control */
LPC_SCU->SFSPD[15] = 0xF4; /* SCU_GPIO_FAST | FUNCTION4 */
LPC_GPIO->CLR[6] = (1 << 29); /* RXHP low = 100 Hz HPF */
LPC_GPIO->DIR[6] |= (1 << 29); /* Output */
/* PD_16 = GPIO6[30] MAX5864 chip select */
LPC_SCU->SFSPD[16] = 0xF4; /* SCU_GPIO_FAST | FUNCTION4 */
LPC_GPIO->SET[6] |= (1 << 30); /* CS high (inactive) */
LPC_GPIO->DIR[6] |= (1 << 30); /* Output */
/* Configure Port E pins for MAX2831 control (use SFSPE registers) */
/* PE_1 = GPIO7[1] MAX2831 ENABLE */
LPC_SCU->SFSPE[1] = 0xF4; /* SCU_GPIO_FAST | FUNCTION4 */
LPC_GPIO->CLR[7] = (1 << 1); /* Start disabled */
LPC_GPIO->DIR[7] |= (1 << 1); /* Output */
/* PE_2 = GPIO7[2] MAX2831 RXTX mode select */
LPC_SCU->SFSPE[2] = 0xF4; /* SCU_GPIO_FAST | FUNCTION4 */
LPC_GPIO->CLR[7] = (1 << 2); /* Start in shutdown mode */
LPC_GPIO->DIR[7] |= (1 << 2); /* Output */
/* Configure Port 6 pins for RF path control */
/* P6_3 = GPIO3[2] Mixer enable (inverted: 0 = mixer ON) */
LPC_SCU->SFSP[6][3] = 0xF0; /* SCU_GPIO_FAST | FUNCTION0 */
LPC_GPIO->CLR[3] = (1 << 2); /* Mixer enabled by default */
LPC_GPIO->DIR[3] |= (1 << 2); /* Output */
/* P6_5 = GPIO3[4] TX enable */
LPC_SCU->SFSP[6][5] = 0xF0; /* SCU_GPIO_FAST | FUNCTION0 */
LPC_GPIO->CLR[3] = (1 << 4); /* TX off by default (RX mode) */
LPC_GPIO->DIR[3] |= (1 << 4); /* Output */
/* Configure Port A pins for RF path control */
/* PA_1 = GPIO4[8] LPF enable */
LPC_SCU->SFSP[0xA][1] = 0xF4; /* SCU_GPIO_FAST | FUNCTION4 */
LPC_GPIO->SET[4] = (1 << 8); /* LPF enabled by default (low band) */
LPC_GPIO->DIR[4] |= (1 << 8); /* Output */
/* PA_2 = GPIO4[9] RF amp enable */
LPC_SCU->SFSP[0xA][2] = 0xF4; /* SCU_GPIO_FAST | FUNCTION4 */
LPC_GPIO->CLR[4] = (1 << 9); /* RF amp off by default */
LPC_GPIO->DIR[4] |= (1 << 9); /* Output */
/* Configure PRALINE-specific SGPIO pins for FPGA sample interface.
* These override the HackRF One pin config from pins_setup.
* PRALINE uses different pins than HackRF One for SGPIO4/8/9/10.
* SCU_GPIO_FAST = 0xF0 (EPUN + EHS + EZI + ZIF)
*/
/* CRITICAL: Disable HackRF One SGPIO8 pin (P9_6) - PRALINE uses P8_0 instead */
LPC_SCU->SFSP[9][6] = 0x00; /* P9_6 = GPIO mode 0, disable SGPIO function */
/* SGPIO4 = P9_4 function 6 (HOST_DATA4) */
LPC_SCU->SFSP[9][4] = 0xF6; /* SCU_GPIO_FAST | func 6 */
/* SGPIO8 = P8_0 function 4 (SGPIO_CLK - clock from FPGA) */
LPC_SCU->SFSP[8][0] = 0xF4; /* SCU_GPIO_FAST | func 4 */
/* SGPIO9 = P9_3 function 6 (HOST_CAPTURE) */
LPC_SCU->SFSP[9][3] = 0xF6; /* SCU_GPIO_FAST | func 6 */
/* SGPIO10 = P8_2 function 4 (HOST_DISABLE - output to FPGA) */
LPC_SCU->SFSP[8][2] = 0xF4; /* SCU_GPIO_FAST | func 4 */
/* SGPIO11 = P1_17 function 6 (HOST_DIRECTION - output to FPGA, tells FPGA TX vs RX) */
LPC_SCU->SFSP[1][17] = 0xF6; /* SCU_GPIO_FAST | func 6 */
/* SGPIO data pins (SGPIO0-7) - all 8 bits required for sample data */
LPC_SCU->SFSP[0][0] = 0xF3; /* SGPIO0: P0_0 function 3, HOST_DATA0 */
LPC_SCU->SFSP[0][1] = 0xF3; /* SGPIO1: P0_1 function 3, HOST_DATA1 */
LPC_SCU->SFSP[1][15] = 0xF2; /* SGPIO2: P1_15 function 2, HOST_DATA2 */
LPC_SCU->SFSP[1][16] = 0xF2; /* SGPIO3: P1_16 function 2, HOST_DATA3 */
/* SGPIO4 already configured above at line 942 */
LPC_SCU->SFSP[6][6] = 0xF2; /* SGPIO5: P6_6 function 2, HOST_DATA5 */
LPC_SCU->SFSP[2][2] = 0xF0; /* SGPIO6: P2_2 function 0, HOST_DATA6 */
LPC_SCU->SFSP[1][0] = 0xF6; /* SGPIO7: P1_0 function 6, HOST_DATA7 */
/* NOTE: P9_5 is RFFC5072 mixer clock (SCU_MIXER_SCLK), NOT SGPIO!
* Do NOT override P9_5 here. */
// Trigger FPGA bitstream loading via fpga bridge
// Attempt to load the FPGA bitstream
// This function returns LD_SUCCESS (0) if the FPGA confirms the bitstream
// Use LEDs to check if initi is successful.
// Setup LED pin directions
// LED1 (USB) = GPIO2[1], LED2 (RX) = GPIO2[2], LED3 (TX) = GPIO2[8]
LPC_GPIO->DIR[2] |= (1 << 1) | (1 << 2) | (1 << 8);
// Turn off all LEDs to start
// PRALINE LEDs are active-low: SET (HIGH) = OFF, CLR (LOW) = ON
LPC_GPIO->SET[2] = (1 << 1) | (1 << 2) | (1 << 8);
// 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();
(void)load_result; // Ignore result for now, just let boot continue
// Keep LEDs off after FPGA load
LPC_GPIO->SET[2] = (1 << 1) | (1 << 2) | (1 << 8);
#endif
}
extern "C" void _default_exit(void) {
@@ -848,10 +997,10 @@ extern "C" void _default_exit(void) {
} else {
LPC_GPIO->W3[6] = 0;
}
vaa_power_off();
chSysDisable();
systick_stop();
/* Don't reset these peripherals, as they're operating during shutdown:
@@ -0,0 +1,472 @@
// This bridge allows calls for functions in their native C context
// HackRF headers here - C for use within the C++ board.cpp context
// Check if PRALINE was passed from CMake
#ifdef PRALINE
#warning "Building for HackRF_PRO with FPGA."
// Necessary headers
#include "lz4_blk.h"
// LIBOPENCM3 Headers (only CGU for clock setup)
#include <libopencm3/lpc43xx/cgu.h>
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>
// SPIFI memory-mapped base address
// Flash is mapped starting at 0x14000000
// FPGA bitstream at flash address 0x380000 = memory address 0x14380000
// PRALINE: Moved to 1.5MB offset to allow larger base firmware
#define SPIFI_DATA_BASE 0x14000000
#define FPGA_BITSTREAM_FLASH_ADDR 0x380000 // Was 0x100000 (1MB), then 0x180000 (1.5MB), now 0x380000 (3.5MB)
#define FPGA_BITSTREAM_MEM_ADDR (SPIFI_DATA_BASE + FPGA_BITSTREAM_FLASH_ADDR)
// MMIO32 direct register access
#define MMIO32_LOCAL(addr) (*(volatile uint32_t*)(addr))
// SSP1 base address
#define SSP1_BASE_LOCAL 0x400C5000
// SSP register offsets
#define SSP_CR0_OFF 0x000
#define SSP_CR1_OFF 0x004
#define SSP_DR_OFF 0x008
#define SSP_SR_OFF 0x00C
#define SSP_CPSR_OFF 0x010
// SSP register access
#define SSP1_CR0_LOCAL MMIO32_LOCAL(SSP1_BASE_LOCAL + SSP_CR0_OFF)
#define SSP1_CR1_LOCAL MMIO32_LOCAL(SSP1_BASE_LOCAL + SSP_CR1_OFF)
#define SSP1_DR_LOCAL MMIO32_LOCAL(SSP1_BASE_LOCAL + SSP_DR_OFF)
#define SSP1_SR_LOCAL MMIO32_LOCAL(SSP1_BASE_LOCAL + SSP_SR_OFF)
#define SSP1_CPSR_LOCAL MMIO32_LOCAL(SSP1_BASE_LOCAL + SSP_CPSR_OFF)
// SSP status bits
#define SSP_SR_TNF_LOCAL (1 << 1) // TX FIFO not full
#define SSP_SR_RNE_LOCAL (1 << 2) // RX FIFO not empty
#define SSP_SR_BSY_LOCAL (1 << 4) // Busy
// SSP CR0 bits
#define SSP_CR0_DSS_8BIT (0x7) // 8-bit data
#define SSP_CR0_FRF_SPI (0x0) // SPI frame format
#define SSP_CR0_CPOL (1 << 6) // Clock polarity
#define SSP_CR0_CPHA (1 << 7) // Clock phase
// SSP CR1 bits
#define SSP_CR1_SSE (1 << 1) // SSP enable
// SCU pin configuration registers
#define PERIPH_BASE_APB0_LOCAL 0x40080000
#define SCU_BASE_LOCAL (PERIPH_BASE_APB0_LOCAL + 0x06000)
#define PIN_GROUP1_LOCAL (SCU_BASE_LOCAL + 0x080)
#define PIN_GROUP4_LOCAL (SCU_BASE_LOCAL + 0x200)
#define PIN_GROUP5_LOCAL (SCU_BASE_LOCAL + 0x280)
#define PIN3_LOCAL 0x00C
#define PIN4_LOCAL 0x010
#define PIN1_LOCAL 0x004
#define PIN2_LOCAL 0x008
#define PIN10_LOCAL 0x028
#define PIN19_LOCAL 0x04C
// SCU configuration flags
#define SCU_CONF_EPUN_DIS_PULLUP_LOCAL (1 << 4)
#define SCU_CONF_EHS_FAST_LOCAL (1 << 5)
#define SCU_CONF_EZI_EN_IN_BUFFER_LOCAL (1 << 6)
#define SCU_CONF_ZIF_DIS_IN_GLITCH_FILT_LOCAL (1 << 7)
#define SCU_GPIO_FAST_LOCAL (SCU_CONF_EPUN_DIS_PULLUP_LOCAL | \
SCU_CONF_EHS_FAST_LOCAL | \
SCU_CONF_EZI_EN_IN_BUFFER_LOCAL | \
SCU_CONF_ZIF_DIS_IN_GLITCH_FILT_LOCAL)
#define SCU_SSP_IO_LOCAL SCU_GPIO_FAST_LOCAL
// Function select values
#define SCU_CONF_FUNCTION0_LOCAL (0x0)
#define SCU_CONF_FUNCTION1_LOCAL (0x1)
#define SCU_CONF_FUNCTION4_LOCAL (0x4)
#define SCU_CONF_FUNCTION5_LOCAL (0x5)
#define SCU_GPIO_NOPULL_LOCAL (SCU_CONF_EZI_EN_IN_BUFFER_LOCAL | SCU_CONF_ZIF_DIS_IN_GLITCH_FILT_LOCAL)
#define SCU_GPIO_PUP_LOCAL (SCU_CONF_EZI_EN_IN_BUFFER_LOCAL)
// SSP1 pins (for FPGA programming)
#define SCU_SSP1_CIPO_LOCAL (PIN_GROUP1_LOCAL + PIN3_LOCAL) // P1_3
#define SCU_SSP1_COPI_LOCAL (PIN_GROUP1_LOCAL + PIN4_LOCAL) // P1_4
#define SCU_SSP1_SCK_LOCAL (PIN_GROUP1_LOCAL + PIN19_LOCAL) // P1_19
// FPGA control pins
#define SCU_FPGA_CRESET_LOCAL (PIN_GROUP5_LOCAL + PIN2_LOCAL) // P5_2 GPIO2[11]
#define SCU_FPGA_CDONE_LOCAL (PIN_GROUP4_LOCAL + PIN10_LOCAL) // P4_10 GPIO5[14]
#define SCU_FPGA_SPI_CS_LOCAL (PIN_GROUP5_LOCAL + PIN1_LOCAL) // P5_1 GPIO2[10]
// GPIO register addresses for direct MMIO access
#define GPIO_LPC_BASE_LOCAL 0x400F4000
#define GPIO_DIR_BASE (GPIO_LPC_BASE_LOCAL + 0x2000) // Direction registers
#define GPIO_SET_BASE (GPIO_LPC_BASE_LOCAL + 0x2200) // Set registers
#define GPIO_CLR_BASE (GPIO_LPC_BASE_LOCAL + 0x2280) // Clear registers
#define GPIO_PIN_BASE (GPIO_LPC_BASE_LOCAL + 0x2100) // Pin read registers
// GPIO port access macros
#define GPIO_DIR(port) MMIO32_LOCAL(GPIO_DIR_BASE + (port)*4)
#define GPIO_SET(port) MMIO32_LOCAL(GPIO_SET_BASE + (port)*4)
#define GPIO_CLR(port) MMIO32_LOCAL(GPIO_CLR_BASE + (port)*4)
#define GPIO_PIN(port) MMIO32_LOCAL(GPIO_PIN_BASE + (port)*4)
// FPGA control GPIO pins
// GPIO2[11] = CRESET, GPIO5[14] = CDONE, GPIO2[10] = SPI_CS
#define FPGA_CRESET_PORT 2
#define FPGA_CRESET_PIN 11
#define FPGA_CDONE_PORT 5
#define FPGA_CDONE_PIN 14
#define FPGA_SPI_CS_PORT 2
#define FPGA_SPI_CS_PIN 10
// Context structure for SPIFI-based reading
struct spifi_fpga_read_ctx {
const uint8_t* mem_ptr; // Current read position in SPIFI memory
size_t next_block_sz;
uint8_t init_flag;
uint8_t buffer[4096 + 2]; // Compressed block + next size
};
// Simple delay loop
static void delay_cycles(volatile uint32_t count) {
while (count--) {
__asm__ volatile ("nop");
}
}
// Microsecond delay (approximate, assuming ~200MHz clock)
static void delay_us(uint32_t us) {
// ~50 cycles per microsecond at 200MHz
delay_cycles(us * 50);
}
// SSP1 transfer one byte
static uint8_t ssp1_transfer_byte(uint8_t data) {
// Wait for TX FIFO not full
while ((SSP1_SR_LOCAL & SSP_SR_TNF_LOCAL) == 0) {}
SSP1_DR_LOCAL = data;
// Wait for not busy
while (SSP1_SR_LOCAL & SSP_SR_BSY_LOCAL) {}
// Wait for RX FIFO not empty
while ((SSP1_SR_LOCAL & SSP_SR_RNE_LOCAL) == 0) {}
return SSP1_DR_LOCAL;
}
// Configure SSP1 for iCE40 programming (SPI mode 3: CPOL=1, CPHA=1)
static void ssp1_init_ice40(void) {
// Disable SSP1 first
SSP1_CR1_LOCAL = 0;
// Configure: 8-bit, SPI mode 3 (CPOL=1, CPHA=1), master mode
// SCR=21 for ~4MHz at 200MHz clock
SSP1_CR0_LOCAL = SSP_CR0_DSS_8BIT | SSP_CR0_FRF_SPI | SSP_CR0_CPOL | SSP_CR0_CPHA | (21 << 8);
// Clock prescaler = 2 (divide by 2)
SSP1_CPSR_LOCAL = 2;
// Enable SSP1
SSP1_CR1_LOCAL = SSP_CR1_SSE;
}
// Configure SSP1 pins via SCU
static void configure_ssp1_pins(void) {
// P1_3 = SSP1_MISO (function 5)
MMIO32_LOCAL(SCU_SSP1_CIPO_LOCAL) = SCU_SSP_IO_LOCAL | SCU_CONF_FUNCTION5_LOCAL;
// P1_4 = SSP1_MOSI (function 5)
MMIO32_LOCAL(SCU_SSP1_COPI_LOCAL) = SCU_SSP_IO_LOCAL | SCU_CONF_FUNCTION5_LOCAL;
// P1_19 = SSP1_SCK (function 1)
MMIO32_LOCAL(SCU_SSP1_SCK_LOCAL) = SCU_SSP_IO_LOCAL | SCU_CONF_FUNCTION1_LOCAL;
}
// Configure FPGA control pins via SCU and GPIO
static void configure_fpga_control_pins(void) {
// P5_2 = GPIO2[11] = CRESET (function 0, output)
MMIO32_LOCAL(SCU_FPGA_CRESET_LOCAL) = SCU_GPIO_NOPULL_LOCAL | SCU_CONF_FUNCTION0_LOCAL;
// P4_10 = GPIO5[14] = CDONE (function 4, input with pullup)
MMIO32_LOCAL(SCU_FPGA_CDONE_LOCAL) = SCU_GPIO_PUP_LOCAL | SCU_CONF_FUNCTION4_LOCAL;
// P5_1 = GPIO2[10] = SPI_CS (function 0, output)
MMIO32_LOCAL(SCU_FPGA_SPI_CS_LOCAL) = SCU_GPIO_NOPULL_LOCAL | SCU_CONF_FUNCTION0_LOCAL;
// Set CRESET and SPI_CS as outputs (GPIO2[11] and GPIO2[10])
GPIO_DIR(FPGA_CRESET_PORT) |= (1 << FPGA_CRESET_PIN) | (1 << FPGA_SPI_CS_PIN);
// Clear both initially
GPIO_CLR(FPGA_CRESET_PORT) = (1 << FPGA_CRESET_PIN) | (1 << FPGA_SPI_CS_PIN);
// CDONE is input (GPIO5[14])
GPIO_DIR(FPGA_CDONE_PORT) &= ~(1 << FPGA_CDONE_PIN);
}
// GPIO control helpers
static void fpga_creset_low(void) {
GPIO_CLR(FPGA_CRESET_PORT) = (1 << FPGA_CRESET_PIN);
}
static void fpga_creset_high(void) {
GPIO_SET(FPGA_CRESET_PORT) = (1 << FPGA_CRESET_PIN);
}
static void fpga_cs_low(void) {
GPIO_CLR(FPGA_SPI_CS_PORT) = (1 << FPGA_SPI_CS_PIN);
}
static void fpga_cs_high(void) {
GPIO_SET(FPGA_SPI_CS_PORT) = (1 << FPGA_SPI_CS_PIN);
}
static bool fpga_cdone_read(void) {
return (GPIO_PIN(FPGA_CDONE_PORT) & (1 << FPGA_CDONE_PIN)) != 0;
}
// ============================================================================
// FPGA Register Access via SPI (iCE40)
// ============================================================================
// These functions allow reading/writing FPGA internal registers via SPI.
// The FPGA bitstream implements a simple SPI register interface.
//
// FPGA Register Map:
// Reg 1 (CTRL): DC_BLOCK(b0), QUARTER_SHIFT_EN(b1), QUARTER_SHIFT_UP(b2), PRBS(b6), TRIGGER_EN(b7)
// Reg 2 (RX_DECIM): Decimation ratio [2:0]
// Reg 3 (TX_CTRL): NCO_EN(b0)
// Reg 4 (TX_INTRP): Interpolation ratio [2:0]
// Reg 5 (TX_PSTEP): NCO phase step [7:0]
//
// SPI Protocol:
// Read: Send [reg & 0x7F, 0x00, 0x00] -> value in byte 3
// Write: Send [(reg | 0x80), value, 0x00]
// Configure SSP1 for iCE40 FPGA register access (Mode 3, 8-bit)
static void ssp1_set_mode_ice40(void) {
SSP1_CR1_LOCAL = 0; // Disable SSP1
SSP1_CR0_LOCAL = SSP_CR0_DSS_8BIT | SSP_CR0_FRF_SPI | SSP_CR0_CPOL | SSP_CR0_CPHA | (21 << 8);
SSP1_CPSR_LOCAL = 2;
SSP1_CR1_LOCAL = SSP_CR1_SSE; // Enable SSP1
}
// Configure SSP1 back to MAX2831 mode (Mode 0, 9-bit)
static void ssp1_set_mode_max2831(void) {
SSP1_CR1_LOCAL = 0; // Disable SSP1
SSP1_CR0_LOCAL = (0x08) | // 9-bit data (DSS = 0x08)
(0x00) | // SPI frame format
(0 << 6) | // CPOL = 0 (Mode 0)
(0 << 7) | // CPHA = 0 (Mode 0)
(21 << 8); // SCR = 21
SSP1_CPSR_LOCAL = 2;
SSP1_CR1_LOCAL = SSP_CR1_SSE; // Enable SSP1
}
// Read an FPGA register via SPI
static uint8_t fpga_spi_read(uint8_t reg) {
uint8_t value;
fpga_cs_low();
ssp1_transfer_byte(reg & 0x7F); // Clear MSB for read
ssp1_transfer_byte(0x00); // Dummy byte
value = ssp1_transfer_byte(0x00); // Read value
fpga_cs_high();
return value;
}
// Write an FPGA register via SPI
static void fpga_spi_write(uint8_t reg, uint8_t value) {
fpga_cs_low();
ssp1_transfer_byte((reg & 0x7F) | 0x80); // Set MSB for write
ssp1_transfer_byte(value);
ssp1_transfer_byte(0x00); // Dummy byte
fpga_cs_high();
}
// Initialize FPGA registers after bitstream load
// This is equivalent to fpga_init() in the reference HackRF firmware
static void fpga_register_init(void) {
// Already in iCE40 mode after programming, so we can directly access registers
// Register 1 (CTRL): Enable DC block (bit 0), disable everything else
// DC_BLOCK is CRITICAL for RX to work!
fpga_spi_write(1, 0x01); // DC_BLOCK = 1
// Register 2 (RX_DECIM): No decimation
fpga_spi_write(2, 0x00);
// Register 3 (TX_CTRL): Disable NCO
fpga_spi_write(3, 0x00);
// Register 4 (TX_INTRP): No interpolation
fpga_spi_write(4, 0x00);
// Register 5 (TX_PSTEP): Zero phase step
fpga_spi_write(5, 0x00);
}
// Cached register values for debug reads (since reads may require mode switch)
static uint8_t fpga_reg_cache[6] = {0, 0x01, 0x00, 0x00, 0x00, 0x00};
static uint8_t fpga_reg_cache_valid = 0;
// Public function to read FPGA register (callable from C++ application code)
// Switches SPI mode, reads register, switches back
uint8_t fpga_debug_register_read(uint8_t reg) {
if (reg == 0 || reg > 5) return 0xFF;
uint8_t value;
ssp1_set_mode_ice40();
value = fpga_spi_read(reg);
ssp1_set_mode_max2831();
fpga_reg_cache[reg] = value;
return value;
}
// Public function to write FPGA register (callable from C++ application code)
void fpga_debug_register_write(uint8_t reg, uint8_t value) {
if (reg == 0 || reg > 5) return;
ssp1_set_mode_ice40();
fpga_spi_write(reg, value);
ssp1_set_mode_max2831();
fpga_reg_cache[reg] = value;
}
// SPIFI-based read callback for LZ4 decompression
// Reads from SPIFI memory-mapped address instead of using SPI flash driver
static size_t spifi_fpga_read_block_cb(void* _ctx, uint8_t* out_buffer) {
struct spifi_fpga_read_ctx* ctx = (struct spifi_fpga_read_ctx*)_ctx;
size_t block_sz = ctx->next_block_sz;
// First iteration: read first block size from SPIFI memory
if (ctx->init_flag == 0) {
block_sz = ctx->mem_ptr[0] | (ctx->mem_ptr[1] << 8);
ctx->mem_ptr += 2;
ctx->init_flag = 1;
}
// Finish at end marker (block_sz == 0)
if (block_sz == 0) return 0;
// Read compressed block from SPIFI memory
memcpy(ctx->buffer, ctx->mem_ptr, block_sz + 2);
ctx->mem_ptr += block_sz + 2;
// Extract next block size
ctx->next_block_sz = ctx->buffer[block_sz] | (ctx->buffer[block_sz + 1] << 8);
// Decompress block using LZ4
return lz4_blk_decompress(ctx->buffer, out_buffer, block_sz);
}
// Program iCE40 FPGA using SPIFI memory-mapped data
// Based on ice40_spi_syscfg_program() from ice40_spi.c
static bool program_fpga_from_spifi(const uint8_t* bitstream_start) {
// Drive CRESET_B = 0, SPI_SS = 0
fpga_creset_low();
fpga_cs_low();
// Wait minimum 200ns
delay_us(1);
// Release CRESET_B (drive high)
fpga_creset_high();
// Wait minimum 1200us (we wait 1800us to be safe)
delay_us(1800);
// Set SPI_SS = 1, send 8 dummy clocks
fpga_cs_high();
ssp1_transfer_byte(0);
// Send configuration image
// Use static buffers to avoid stack overflow (~8KB would be needed)
static uint8_t out_buffer[4096];
static struct spifi_fpga_read_ctx ctx;
ctx.mem_ptr = bitstream_start;
ctx.next_block_sz = 0;
ctx.init_flag = 0;
fpga_cs_low();
// Full LZ4 decompress and send all bytes
for (;;) {
size_t read_sz = spifi_fpga_read_block_cb(&ctx, out_buffer);
if (read_sz == 0) break;
for (size_t j = 0; j < read_sz; j++) {
ssp1_transfer_byte(out_buffer[j]);
}
}
// Wait for 100 clock cycles for CDONE to go high
fpga_cs_high();
for (size_t j = 0; j < 13; j++) {
ssp1_transfer_byte(0);
}
// Check CDONE status
bool success = fpga_cdone_read();
// NOTE: FPGA register initialization is done later in radio::init()
// The FPGA needs time to stabilize after configuration before accepting register writes
// CRITICAL: Reconfigure SSP1 for MAX2831 (PRALINE RF chip) after FPGA programming
// iCE40 uses Mode 3 (CPOL=1, CPHA=1), 8-bit
// MAX2831 (PRALINE) uses Mode 0 (CPOL=0, CPHA=0), 9-bit (vs 16-bit for MAX283x on HackRF One)
// Without this, RF communication will fail!
/*SSP1_CR1_LOCAL = 0; // Disable SSP1
SSP1_CR0_LOCAL = (0x08) | // 9-bit data (DSS = 0x08) for MAX2831/PRALINE
(0x00) | // SPI frame format
(0 << 6) | // CPOL = 0 (Mode 0)
(0 << 7) | // CPHA = 0 (Mode 0)
(21 << 8); // SCR = 21 (same as ssp_config_max283x for PRALINE)
SSP1_CPSR_LOCAL = 2; // Clock prescaler
SSP1_CR1_LOCAL = SSP_CR1_SSE; // Re-enable SSP1*/
return success;
}
int fpga_bridge_init(void) {
// Enable SSP1 clock for FPGA programming
// Use PLL1 (204MHz) to match original HackRF - IRC (12MHz) is 17x too slow
CGU_BASE_SSP1_CLK = CGU_BASE_SSP1_CLK_AUTOBLOCK(1) |
CGU_BASE_SSP1_CLK_CLK_SEL(CGU_SRC_PLL1);
// Configure SSP1 pins
configure_ssp1_pins();
// Configure FPGA control pins
configure_fpga_control_pins();
// Initialize SSP1 for iCE40 programming
ssp1_init_ice40();
// Read FPGA bitstream header from SPIFI memory
const uint8_t* fpga_header = (const uint8_t*)FPGA_BITSTREAM_MEM_ADDR;
uint32_t num_bitstreams = fpga_header[0] | (fpga_header[1] << 8) |
(fpga_header[2] << 16) | (fpga_header[3] << 24);
// Check if header looks valid
if (num_bitstreams == 0 || num_bitstreams > 16 || num_bitstreams == 0xFFFFFFFF) {
// No valid FPGA bitstream - skip programming but continue boot
return 1;
}
// Get offset of first bitstream (index 0 = standard_fpga)
uint32_t bitstream_offset = fpga_header[4] | (fpga_header[5] << 8) |
(fpga_header[6] << 16) | (fpga_header[7] << 24);
// Calculate start address of first bitstream in SPIFI memory
const uint8_t* bitstream_start = (const uint8_t*)(FPGA_BITSTREAM_MEM_ADDR + bitstream_offset);
// Full FPGA programming
bool success = program_fpga_from_spifi(bitstream_start);
// Initialize FPGA registers immediately after programming
if (success) {
// Give FPGA 100us to stabilize after configuration
delay_us(100);
// Initialize FPGA registers (DC_BLOCK, etc.)
fpga_register_init();
// Now switch to MAX2831 mode
ssp1_set_mode_max2831();
}
return success ? 0 : 2;
}
#else
#warning "Building for HackRF_One with CPLD."
#endif
@@ -0,0 +1,51 @@
/*
* FPGA Bridge Header - PRALINE iCE40 FPGA interface
*
* Provides functions for initializing and accessing the FPGA on HackRF Pro (PRALINE).
*/
#ifndef __FPGA_BRIDGE_H__
#define __FPGA_BRIDGE_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#ifdef PRALINE
/*
* Initialize the FPGA - loads bitstream from SPIFI flash
* Returns: 0 on success, non-zero on failure
*/
int fpga_bridge_init(void);
/*
* Read an FPGA register via SPI
* reg: Register number (1-5)
* Returns: Register value, or 0xFF if invalid register
*
* FPGA Register Map:
* Reg 1 (CTRL): DC_BLOCK(b0), QUARTER_SHIFT_EN(b1), QUARTER_SHIFT_UP(b2), PRBS(b6), TRIGGER_EN(b7)
* Reg 2 (RX_DECIM): Decimation ratio [2:0]
* Reg 3 (TX_CTRL): NCO_EN(b0)
* Reg 4 (TX_INTRP): Interpolation ratio [2:0]
* Reg 5 (TX_PSTEP): NCO phase step [7:0]
*/
uint8_t fpga_debug_register_read(uint8_t reg);
/*
* Write an FPGA register via SPI
* reg: Register number (1-5)
* value: Value to write
*/
void fpga_debug_register_write(uint8_t reg, uint8_t value);
#endif /* PRALINE */
#ifdef __cplusplus
}
#endif
#endif /* __FPGA_BRIDGE_H__ */
+55
View File
@@ -189,6 +189,7 @@ constexpr uint32_t gpio_outreg(const Direction direction) {
constexpr uint32_t gpio_oenreg(const Direction direction) {
return (0U << PIN_P78) | (0U << PIN_P81) | (0U << PIN_SYNC_EN) | (0U << PIN_INVERT) | (1U << PIN_DIRECTION) | (1U << PIN_DISABLE) | (0U << PIN_CAPTURE) | (0U << PIN_CLKIN) | ((direction == Direction::Transmit) ? 0xffU : 0x00U);
// ^^^^^^^^^^^^^ REVERTED: SGPIO14 must be DISABLED - enabling it blocks data capture!
}
constexpr uint32_t out_mux_cfg(const P_OUT_CFG out, const P_OE_CFG oe) {
@@ -198,13 +199,23 @@ constexpr uint32_t out_mux_cfg(const P_OUT_CFG out, const P_OE_CFG oe) {
constexpr uint32_t data_sgpio_mux_cfg(
const CONCAT_ENABLE concat_enable,
const CONCAT_ORDER concat_order) {
#ifndef PRALINE
return (1U << 0) | (0U << 1) | (0U << 3) | (3U << 5) | (1U << 7) | (0U << 9) | (toUType(concat_enable) << 11) | (toUType(concat_order) << 12);
#else
return (1U << 0) | (0U << 1) | (3U << 3) | (3U << 5) | (1U << 7) | (0U << 9) | (toUType(concat_enable) << 11) | (toUType(concat_order) << 12);
// Bits 3-4: CLK_SOURCE_SLICE_MODE = 3 (slice D as clock source for data slices)
#endif
}
constexpr uint32_t data_slice_mux_cfg(
const PARALLEL_MODE parallel_mode,
const CLK_CAPTURE_MODE clk_capture_mode) {
#ifndef PRALINE
return (0U << 0) | (toUType(clk_capture_mode) << 1) | (1U << 2) | (0U << 3) | (0U << 4) | (toUType(parallel_mode) << 6) | (0U << 8);
#else
return (0U << 0) | (toUType(clk_capture_mode) << 1) | (1U << 2) | (0U << 3) | (1U << 4) | (toUType(parallel_mode) << 6) | (0U << 8);
// Bit 4 CLKGEN_MODE: 0=internal counter, 1=external clock (REQUIRED for PRALINE!)
#endif
}
constexpr uint32_t pos(
@@ -264,28 +275,54 @@ void SGPIO::init() {
void SGPIO::configure(const Direction direction) {
disable_all_slice_counters();
#ifndef PRALINE
// Set data pins as input, temporarily.
LPC_SGPIO->GPIO_OENREG = gpio_oenreg(Direction::Receive);
// Now that data pins are inputs, safe to change CPLD direction.
#endif
// HackRF reference: Set GPIO_OUTREG first (DISABLE=HIGH during config)
LPC_SGPIO->GPIO_OUTREG = gpio_outreg(direction);
#ifdef PRALINE
// HackRF reference: Set GPIO_OENREG ONCE before OUT_MUX_CFG (not twice!)
LPC_SGPIO->GPIO_OENREG = gpio_oenreg(direction);
// Now configure OUT_MUX_CFG (HackRF order: control pins first, then data pins)
#endif
LPC_SGPIO->OUT_MUX_CFG[8] = out_mux_cfg(P_OUT_CFG::DOUT_DOUTM1, P_OE_CFG::GPIO_OE);
LPC_SGPIO->OUT_MUX_CFG[9] = out_mux_cfg(P_OUT_CFG::DOUT_DOUTM1, P_OE_CFG::GPIO_OE);
#ifndef PRALINE
// OUT_MUX_CFG[10] NOT configured for PRALINE - breaks PRALINE (HOST_DISABLE signal)
LPC_SGPIO->OUT_MUX_CFG[10] = out_mux_cfg(P_OUT_CFG::GPIO_OUT, P_OE_CFG::GPIO_OE);
#endif
LPC_SGPIO->OUT_MUX_CFG[11] = out_mux_cfg(P_OUT_CFG::GPIO_OUT, P_OE_CFG::GPIO_OE);
#ifndef PRALINE
// SGPIO 12 and 13 are NOT configured - not used per HackRF reference for PRALINE
LPC_SGPIO->OUT_MUX_CFG[12] = out_mux_cfg(P_OUT_CFG::GPIO_OUT, P_OE_CFG::GPIO_OE);
LPC_SGPIO->OUT_MUX_CFG[13] = out_mux_cfg(P_OUT_CFG::GPIO_OUT, P_OE_CFG::GPIO_OE);
#endif
LPC_SGPIO->OUT_MUX_CFG[14] = out_mux_cfg(P_OUT_CFG::DOUT_DOUTM1, P_OE_CFG::GPIO_OE);
#ifndef PRALINE
// SGPIO 15 is NOT configured - not used per HackRF reference for PRALINE
LPC_SGPIO->OUT_MUX_CFG[15] = out_mux_cfg(P_OUT_CFG::GPIO_OUT, P_OE_CFG::GPIO_OE);
#endif
const auto data_out_mux_cfg = out_mux_cfg(data_p_out_cfg(slice_mode_multislice), P_OE_CFG::GPIO_OE);
for (size_t i = 0; i < 8; i++) {
LPC_SGPIO->OUT_MUX_CFG[i] = data_out_mux_cfg;
}
#ifndef PRALINE
// Now that output enable sources are set, enable data bus in correct direction.
LPC_SGPIO->GPIO_OENREG = gpio_oenreg(direction);
#endif
const auto slice_gpdma = Slice::H;
@@ -293,7 +330,25 @@ void SGPIO::configure(const Direction direction) {
const auto clk_capture_mode = data_clk_capture_mode(direction);
const auto single_slice = !slice_mode_multislice;
#ifndef PRALINE
uint32_t slice_enable_mask = 0;
#endif
#ifdef PRALINE
// Configure slice D as clock generator (REQUIRED for PRALINE!)
// Reference: HackRF sgpio.c line 193
const auto slice_d = toUType(Slice::D);
LPC_SGPIO->SGPIO_MUX_CFG[slice_d] = (1U << 0) | (0U << 1) | (0U << 3) | (3U << 5) | (1U << 7) | (0U << 9) | (0U << 11) | (0U << 12);
LPC_SGPIO->SLICE_MUX_CFG[slice_d] = (0U << 0) | (0U << 1) | (0U << 2) | (0U << 3) | (1U << 4) | (0U << 6) | (0U << 8); // CLKGEN_MODE=1
LPC_SGPIO->PRESET[slice_d] = 0;
LPC_SGPIO->COUNT[slice_d] = 0;
LPC_SGPIO->POS[slice_d] = pos(0x1f, 0x1f);
LPC_SGPIO->REG[slice_d] = 0x11111111;
LPC_SGPIO->REG_SS[slice_d] = 0x11111111;
uint32_t slice_enable_mask = (1U << slice_d); // Start with slice D enabled
#endif
for (size_t i = 0; i < slice_count; i++) {
const auto slice = slice_order[i];
const auto slice_index = toUType(slice);
+358
View File
@@ -1681,4 +1681,362 @@ static constexpr fir_taps_real<24> taps_BTLE_Dual_PHY = {
3}},
};
static constexpr fir_taps_real<63> taps_2k0_am_lpf_channel = {
.low_frequency_normalized = -2000.0f / 48000.0f,
.high_frequency_normalized = 2000.0f / 48000.0f,
.transition_normalized = 1500.0f / 48000.0f,
.taps = {{
26,
29,
31,
33,
32,
28,
18,
0,
-26,
-61,
-104,
-152,
-202,
-246,
-279,
-292,
-277,
-227,
-136,
0,
182,
409,
673,
968,
1280,
1595,
1899,
2174,
2407,
2583,
2693,
2731,
2693,
2583,
2407,
2174,
1899,
1595,
1280,
968,
673,
409,
182,
0,
-136,
-227,
-277,
-292,
-279,
-246,
-202,
-152,
-104,
-61,
-26,
0,
18,
28,
32,
33,
31,
29,
26,
}},
};
static constexpr fir_taps_real<64> taps_1K5_FM_channel = {
.low_frequency_normalized = 300.0f / 48000.0f,
.high_frequency_normalized = 1800.0f / 48000.0f,
.transition_normalized = 1000.0f / 48000.0f,
.taps = {{
24,
22,
20,
15,
9,
-2,
-18,
-39,
-66,
-98,
-132,
-167,
-198,
-220,
-228,
-217,
-181,
-117,
-19,
112,
277,
474,
697,
941,
1197,
1454,
1702,
1930,
2128,
2285,
2394,
2451,
2451,
2394,
2285,
2128,
1930,
1702,
1454,
1197,
941,
697,
474,
277,
112,
-19,
-117,
-181,
-217,
-228,
-220,
-198,
-167,
-132,
-98,
-66,
-39,
-18,
-2,
9,
15,
20,
22,
24,
}},
};
static constexpr fir_taps_real<63> taps_1k5_dsb_lpf = {
.low_frequency_normalized = -1500.0f / 48000.0f,
.high_frequency_normalized = 1500.0f / 48000.0f,
.transition_normalized = 1000.0f / 48000.0f,
.taps = {{
0,
0,
-1,
-5,
-10,
-19,
-31,
-46,
-64,
-82,
-99,
-111,
-113,
-100,
-64,
0,
99,
239,
424,
655,
932,
1251,
1605,
1983,
2372,
2757,
3120,
3447,
3719,
3925,
4053,
4096,
4053,
3925,
3719,
3447,
3120,
2757,
2372,
1983,
1605,
1251,
932,
655,
424,
239,
99,
0,
-64,
-100,
-113,
-111,
-99,
-82,
-64,
-46,
-31,
-19,
-10,
-5,
-1,
0,
0,
}},
};
// GAIN: 4.0x
static constexpr fir_taps_complex<63> taps_1k5_USB_channel = {
.low_frequency_normalized = 300.0f / 48000.0f,
.high_frequency_normalized = 1800.0f / 48000.0f,
.transition_normalized = 300.0f / 48000.0f,
.taps = {{
{0, 0},
{0, 0},
{2, 0},
{4, 2},
{10, 6},
{17, 14},
{27, 29},
{37, 53},
{45, 89},
{49, 140},
{41, 207},
{17, 290},
{-31, 389},
{-109, 499},
{-227, 614},
{-387, 725},
{-595, 819},
{-850, 884},
{-1147, 904},
{-1477, 866},
{-1827, 757},
{-2179, 569},
{-2512, 297},
{-2804, -55},
{-3031, -480},
{-3173, -962},
{-3213, -1481},
{-3142, -2011},
{-2955, -2524},
{-2658, -2991},
{-2262, -3386},
{-1788, -3685},
{-1258, -3873},
{-703, -3939},
{-153, -3884},
{366, -3713},
{826, -3440},
{1208, -3087},
{1499, -2677},
{1693, -2236},
{1789, -1789},
{1796, -1359},
{1726, -966},
{1594, -624},
{1420, -341},
{1220, -120},
{1012, 40},
{809, 144},
{622, 202},
{460, 223},
{324, 217},
{217, 193},
{137, 160},
{80, 125},
{42, 91},
{19, 62},
{6, 39},
{0, 22},
{-1, 11},
{-1, 5},
{-1, 1},
{0, 0},
{0, 0},
}},
};
// GAIN: 4.0x
static constexpr fir_taps_complex<63> taps_1k5_LSB_channel = {
.low_frequency_normalized = 300.0f / 48000.0f,
.high_frequency_normalized = 1800.0f / 48000.0f,
.transition_normalized = 300.0f / 48000.0f,
.taps = {{
{0, 0},
{0, 0},
{2, 0},
{4, -2},
{10, -6},
{17, -14},
{27, -29},
{37, -53},
{45, -89},
{49, -140},
{41, -207},
{17, -290},
{-31, -389},
{-109, -499},
{-227, -614},
{-387, -725},
{-595, -819},
{-850, -884},
{-1147, -904},
{-1477, -866},
{-1827, -757},
{-2179, -569},
{-2512, -297},
{-2804, 55},
{-3031, 480},
{-3173, 962},
{-3213, 1481},
{-3142, 2011},
{-2955, 2524},
{-2658, 2991},
{-2262, 3386},
{-1788, 3685},
{-1258, 3873},
{-703, 3939},
{-153, 3884},
{366, 3713},
{826, 3440},
{1208, 3087},
{1499, 2677},
{1693, 2236},
{1789, 1789},
{1796, 1359},
{1726, 966},
{1594, 624},
{1420, 341},
{1220, 120},
{1012, -40},
{809, -144},
{622, -202},
{460, -223},
{324, -217},
{217, -193},
{137, -160},
{80, -125},
{42, -91},
{19, -62},
{6, -39},
{0, -22},
{-1, -11},
{-1, -5},
{-1, -1},
{0, 0},
{0, 0},
}},
};
#endif /*__DSP_FIR_TAPS_H__*/
+67
View File
@@ -41,8 +41,14 @@ constexpr GPIO gpio_led_tx = gpio[GPIO2_8];
constexpr GPIO gpio_og_1v8_enable = gpio[GPIO3_6];
constexpr GPIO gpio_r9_1v8_enable = gpio[GPIO2_9];
constexpr GPIO gpio_vregmode = gpio[GPIO3_7];
#ifdef PRALINE
// PRALINE uses different power control pins
constexpr GPIO gpio_og_vaa_disable = gpio[GPIO4_1]; // PRALINE VAA disable (P8_1)
constexpr GPIO gpio_r9_vaa_disable = gpio[GPIO4_1]; // PRALINE VAA disable (P8_1)
#else
constexpr GPIO gpio_og_vaa_disable = gpio[GPIO2_9];
constexpr GPIO gpio_r9_vaa_disable = gpio[GPIO3_6];
#endif
constexpr GPIO gpio_rx_mix_bp = gpio[GPIO2_12];
constexpr GPIO gpio_tx_mix_bp = gpio[GPIO2_11];
@@ -64,19 +70,80 @@ constexpr GPIO gpio_not_tx_amp_pwr = gpio[GPIO3_5];
constexpr GPIO gpio_rffc5072_resetx = gpio[GPIO2_14];
constexpr GPIO gpio_rffc5072_select = gpio[GPIO2_13];
#ifdef PRALINE
constexpr GPIO gpio_rffc5072_clock = gpio[GPIO5_18];
constexpr GPIO gpio_rffc5072_data = gpio[GPIO4_14];
#else
constexpr GPIO gpio_rffc5072_clock = gpio[GPIO5_6];
constexpr GPIO gpio_rffc5072_data = gpio[GPIO3_3];
#endif
#ifdef PRALINE
constexpr GPIO gpio_max283x_select = gpio[GPIO6_28];
#else
constexpr GPIO gpio_max283x_select = gpio[GPIO0_15];
#endif
#ifdef PRALINE
// PRALINE uses MAX2831 transceiver with different control pins
constexpr GPIO gpio_max283x_enable = gpio[GPIO7_1]; // MAX2831 ENABLE (PE_1)
constexpr GPIO gpio_max2831_enable = gpio[GPIO7_1]; // Alias
constexpr GPIO gpio_max2831_rx_enable = gpio[GPIO7_2]; // MAX2831 RX_ENABLE (PE_2)
constexpr GPIO gpio_max2831_rxhp = gpio[GPIO6_29]; // MAX2831 RXHP (PD_15)
constexpr GPIO gpio_max2831_ld = gpio[GPIO4_11]; // MAX2831 Lock Detect (P9_6)
// Legacy aliases for code compatibility
constexpr GPIO gpio_max2837_rxenable = gpio[GPIO7_2];
constexpr GPIO gpio_max2837_txenable = gpio[GPIO7_2]; // MAX2831 uses single RX/TX control
constexpr GPIO gpio_max2839_rxtx = gpio[GPIO7_2];
#else
constexpr GPIO gpio_max283x_enable = gpio[GPIO2_6];
constexpr GPIO gpio_max2837_rxenable = gpio[GPIO2_5];
constexpr GPIO gpio_max2837_txenable = gpio[GPIO2_4];
constexpr GPIO gpio_max2839_rxtx = gpio[GPIO2_5];
#endif
#ifdef PRALINE
constexpr GPIO gpio_max5864_select = gpio[GPIO6_30];
constexpr GPIO gpio_fpga_select = gpio[GPIO2_10]; // FPGA SPI CS (P5_1)
#else
constexpr GPIO gpio_max5864_select = gpio[GPIO2_7];
#endif
constexpr GPIO gpio_q_invert = gpio[GPIO0_13];
#ifdef PRALINE
// PRALINE power control
constexpr GPIO gpio_vaa_disable = gpio[GPIO4_1]; // VAA disable (P8_1)
constexpr GPIO gpio_1v2_enable = gpio[GPIO4_7]; // 1V2 enable (P8_7)
constexpr GPIO gpio_3v3aux_disable = gpio[GPIO5_15]; // 3V3 aux disable (P6_7)
// PRALINE RF path control
constexpr GPIO gpio_tx_enable = gpio[GPIO3_4]; // TX enable (P6_5)
constexpr GPIO gpio_mix_enable_n = gpio[GPIO3_2]; // Mixer enable inverted (P6_3)
constexpr GPIO gpio_lpf_enable = gpio[GPIO4_8]; // LPF enable (PA_1)
constexpr GPIO gpio_rf_amp_enable = gpio[GPIO4_9]; // RF amp enable (PA_2)
constexpr GPIO gpio_ant_bias_disable = gpio[GPIO1_12]; // Antenna bias disable (P2_12)
// PRALINE mixer lock detect (gpio_max2831_ld defined above at line 93)
constexpr GPIO gpio_rffc5072_ld = gpio[GPIO6_25]; // Mixer lock detect (PD_11)
// PRALINE LED4
constexpr GPIO gpio_led4 = gpio[GPIO4_6]; // LED4 (P8_6)
// PRALINE dual port control
constexpr GPIO gpio_p1_ctrl0 = gpio[GPIO0_14]; // P1 control 0 (P2_10)
constexpr GPIO gpio_p1_ctrl1 = gpio[GPIO5_16]; // P1 control 1 (P6_8)
constexpr GPIO gpio_p1_ctrl2 = gpio[GPIO3_5]; // P1 control 2 (P6_9)
constexpr GPIO gpio_p2_ctrl0 = gpio[GPIO7_3]; // P2 control 0 (PE_3)
constexpr GPIO gpio_p2_ctrl1 = gpio[GPIO7_4]; // P2 control 1 (PE_4)
constexpr GPIO gpio_clkin_ctrl = gpio[GPIO0_15]; // CLKIN control (P1_20)
// PRALINE trigger/sync I/O
constexpr GPIO gpio_trigger_in = gpio[GPIO6_26]; // Trigger input (PD_12)
constexpr GPIO gpio_trigger_out = gpio[GPIO5_6]; // Trigger output (P2_6)
constexpr GPIO gpio_pps_out = gpio[GPIO5_5]; // PPS output (P2_5)
#endif
constexpr GPIO gpio_cpld_tdo = gpio[GPIO5_18];
constexpr GPIO gpio_cpld_tck = gpio[GPIO3_0];
constexpr GPIO gpio_cpld_tms = gpio[GPIO3_4];
+8
View File
@@ -62,8 +62,16 @@ constexpr size_t clock_generator_output_og_codec = 0;
constexpr size_t clock_generator_output_og_cpld = 1;
constexpr size_t clock_generator_output_og_sgpio = 2;
constexpr size_t clock_generator_output_og_clkout = 3;
#ifdef PRALINE
/* PRALINE has swapped CLK4/CLK5 vs HackRF One OG:
* CLK4 = XCVR_CLK (MAX2831) = second IF
* CLK5 = MIX_CLK (RFFC5072) = first IF */
constexpr size_t clock_generator_output_og_first_if = 5; // RFFC5072 on CLK5
constexpr size_t clock_generator_output_og_second_if = 4; // MAX2831 on CLK4
#else
constexpr size_t clock_generator_output_og_first_if = 4;
constexpr size_t clock_generator_output_og_second_if = 5;
#endif
constexpr size_t clock_generator_output_og_mcu_clkin = 7;
constexpr size_t clock_generator_output_r9_if = 0;
+1 -1
View File
@@ -110,4 +110,4 @@ class I2CDevManager {
};
}; // namespace i2cdev
#endif
#endif
+17
View File
@@ -30,17 +30,30 @@ struct LED {
}
void setup() const {
#ifdef PRALINE
/* PRALINE LEDs are active-low (GPIO LOW = LED ON) */
_gpio.set(); /* Start with LED OFF (HIGH) */
#else
_gpio.clear();
#endif
_gpio.output();
_gpio.configure();
}
void on() const {
#ifdef PRALINE
_gpio.clear(); /* LOW = ON for PRALINE */
#else
_gpio.set();
#endif
}
void off() const {
#ifdef PRALINE
_gpio.set(); /* HIGH = OFF for PRALINE */
#else
_gpio.clear();
#endif
}
void toggle() const {
@@ -48,7 +61,11 @@ struct LED {
}
void write(const bool value) const {
#ifdef PRALINE
_gpio.write(!value); /* Invert for PRALINE */
#else
_gpio.write(value);
#endif
}
private:
+36
View File
@@ -150,6 +150,9 @@ class Message {
MorseRXfreq = 92,
MorseRXConfig = 93,
TXDisabled = 94,
MorseTXConfigure = 95,
MorseTXkey = 96,
StreamTXConfiguration = 97,
MAX
};
@@ -1709,6 +1712,7 @@ class MorseRXDataMessage : public Message {
: Message{ID::MorseRXData} {}
int32_t state_durations[5] = {0}; // positive: high, negative: low
uint8_t state_cnt = 0;
bool clipped = false;
const uint8_t maxptr = 4;
};
@@ -1734,4 +1738,36 @@ class TXDisabledMessage : public Message {
}
};
class MorseTXConfigureMessage : public Message {
public:
constexpr MorseTXConfigureMessage(uint8_t modulation, uint32_t tone, float fm_delta)
: Message{ID::MorseTXConfigure},
modulation{modulation},
tone{tone},
fm_delta{fm_delta} {}
uint8_t modulation = 0;
uint32_t tone = 0;
float fm_delta = 0;
};
class MorseTXkeyMessage : public Message {
public:
constexpr MorseTXkeyMessage(bool key_down)
: Message{ID::MorseTXkey},
key_down{key_down} {}
bool key_down = false;
};
class StreamTXConfigurationMessage : public Message {
public:
constexpr StreamTXConfigurationMessage(uint32_t deviation, uint8_t mode)
: Message{ID::StreamTXConfiguration},
deviation{deviation},
mode{mode} {}
uint32_t deviation = 60000; // used in 2fsk
uint8_t mode = 0; // am = 0, 2fsk = 1
};
#endif /*__MESSAGE_H__*/
+106 -2
View File
@@ -109,6 +109,29 @@ enum Pins {
P7_7,
P9_5,
P9_6,
#ifdef PRALINE
P9_2,
// Port A pins (PRALINE RF path control)
PA_1,
PA_2,
// Port 8 pins (PRALINE power control and LED4)
P8_1,
P8_6,
P8_7,
// Port E pins (PRALINE transceiver control)
PE_1,
PE_2,
PE_3,
PE_4,
// Port D pins (PRALINE - GPIO-only high-drive pins)
// These use SCU_SFSPD registers, not normal SFSP
// SCU configuration must be done separately in board.cpp
PD_11,
PD_12,
PD_14,
PD_15,
PD_16,
#endif
PF_4,
CLK0,
CLK2,
@@ -197,6 +220,28 @@ constexpr Pin pins[]{
[P7_7] = {7, 7},
[P9_5] = {9, 5},
[P9_6] = {9, 6},
#ifdef PRALINE
[P9_2] = {9, 2},
// Port A pins (function 0 = GPIO)
[PA_1] = {0xA, 1},
[PA_2] = {0xA, 2},
// Port 8 pins
[P8_1] = {8, 1},
[P8_6] = {8, 6},
[P8_7] = {8, 7},
// Port E pins (function 4 = GPIO)
[PE_1] = {0xE, 1},
[PE_2] = {0xE, 2},
[PE_3] = {0xE, 3},
[PE_4] = {0xE, 4},
// Port D pins - GPIO-only, no pin mux needed
// Using 0xD as marker for Port D (SCU_SFSPD registers)
[PD_11] = {0xD, 11},
[PD_12] = {0xD, 12},
[PD_14] = {0xD, 14},
[PD_15] = {0xD, 15},
[PD_16] = {0xD, 16},
#endif
[PF_4] = {15, 4},
[CLK0] = {24, 0},
[CLK2] = {24, 2},
@@ -209,7 +254,8 @@ enum GPIOs {
GPIO0_3,
GPIO0_4,
GPIO0_5,
/*GPIO0_6,*/ GPIO0_7,
/*GPIO0_6,*/
GPIO0_7,
GPIO0_8,
GPIO0_9,
GPIO0_10,
@@ -275,12 +321,35 @@ enum GPIOs {
GPIO5_7,
GPIO5_8,
GPIO5_9,
/*GPIO5_10, GPIO5_11,*/ GPIO5_12,
/*GPIO5_10, GPIO5_11,*/
GPIO5_12,
GPIO5_13,
GPIO5_14,
GPIO5_15,
GPIO5_16,
GPIO5_18,
// PRALINE-specific GPIOs (always defined to avoid compile-time array gaps)
// RFFC5072 mixer data
GPIO4_14,
// Power control and LED4
GPIO4_1,
GPIO4_6,
GPIO4_7,
// RF path control
GPIO4_8,
GPIO4_9,
// Transceiver (MAX2831) control
GPIO7_1,
GPIO7_2,
// Dual port control
GPIO7_3,
GPIO7_4,
// GPIO6 (Port D pins)
GPIO6_25,
GPIO6_26,
GPIO6_28,
GPIO6_29,
GPIO6_30,
};
constexpr GPIO gpio[] = {
@@ -372,6 +441,41 @@ constexpr GPIO gpio[] = {
[GPIO5_15] = {pins[P6_7], 5, 15, 4},
[GPIO5_16] = {pins[P6_8], 5, 16, 4},
[GPIO5_18] = {pins[P9_5], 5, 18, 4},
// PRALINE-specific GPIOs (use placeholder pins on non-PRALINE builds)
#ifdef PRALINE
[GPIO4_14] = {pins[P9_2], 4, 14, 0}, // RFFC5072 mixer data
[GPIO4_1] = {pins[P8_1], 4, 1, 0}, // VAA disable
[GPIO4_6] = {pins[P8_6], 4, 6, 0}, // LED4
[GPIO4_7] = {pins[P8_7], 4, 7, 0}, // 1V2 enable
[GPIO4_8] = {pins[PA_1], 4, 8, 0}, // LPF enable
[GPIO4_9] = {pins[PA_2], 4, 9, 0}, // RF amp enable
[GPIO7_1] = {pins[PE_1], 7, 1, 4}, // MAX2831 enable
[GPIO7_2] = {pins[PE_2], 7, 2, 4}, // MAX2831 RX enable
[GPIO7_3] = {pins[PE_3], 7, 3, 4}, // P2 port control 0
[GPIO7_4] = {pins[PE_4], 7, 4, 4}, // P2 port control 1
[GPIO6_25] = {pins[PD_11], 6, 25, 4}, // Mixer lock detect
[GPIO6_26] = {pins[PD_12], 6, 26, 4}, // Trigger input
[GPIO6_28] = {pins[PD_14], 6, 28, 4}, // MAX283x chip select
[GPIO6_29] = {pins[PD_15], 6, 29, 4}, // MAX2831 RXHP
[GPIO6_30] = {pins[PD_16], 6, 30, 4}, // MAX5864 chip select
#else
// Placeholder entries for non-PRALINE builds (use P0_0 as dummy)
[GPIO4_14] = {pins[P0_0], 4, 14, 0},
[GPIO4_1] = {pins[P0_0], 4, 1, 0},
[GPIO4_6] = {pins[P0_0], 4, 6, 0},
[GPIO4_7] = {pins[P0_0], 4, 7, 0},
[GPIO4_8] = {pins[P0_0], 4, 8, 0},
[GPIO4_9] = {pins[P0_0], 4, 9, 0},
[GPIO7_1] = {pins[P0_0], 7, 1, 0},
[GPIO7_2] = {pins[P0_0], 7, 2, 0},
[GPIO7_3] = {pins[P0_0], 7, 3, 0},
[GPIO7_4] = {pins[P0_0], 7, 4, 0},
[GPIO6_25] = {pins[P0_0], 6, 25, 0},
[GPIO6_26] = {pins[P0_0], 6, 26, 0},
[GPIO6_28] = {pins[P0_0], 6, 28, 0},
[GPIO6_29] = {pins[P0_0], 6, 29, 0},
[GPIO6_30] = {pins[P0_0], 6, 30, 0},
#endif
};
} // namespace lpc43xx
+11
View File
@@ -51,6 +51,17 @@ const Config config{block_0, block_1};
} /* namespace rev_20170522 */
#ifdef PRALINE
namespace rev_h4m {
extern const std::array<uint16_t, 3328> block_0;
extern const std::array<uint16_t, 512> block_1;
const Config config{block_0, block_1};
} /* namespace rev_h4m */
#endif
} /* namespace cpld */
} /* namespace portapack */
@@ -85,6 +85,14 @@ struct SharedMemory {
uint16_t volatile m4_stack_usage{0};
uint32_t volatile m4_heap_usage{0};
uint16_t volatile m4_buffer_missed{0};
#ifdef PRALINE
// Phase 0 instrumentation counters for PRALINE radio debugging
uint32_t volatile m4_dma_xfr_count{0}; // DMA transfer_complete() calls
uint32_t volatile m4_dma_wait_count{0}; // wait_for_buffer() calls
uint32_t volatile m4_baseband_loops{0}; // Main loop iterations
uint8_t volatile m4_streaming_marker{0}; // Proves streaming_enable() called
#endif
};
extern SharedMemory& shared_memory;
+1
View File
@@ -125,6 +125,7 @@ constexpr image_tag_t image_tag_wefaxrx{'P', 'W', 'F', 'X'};
constexpr image_tag_t image_tag_noaaapt_rx{'P', 'N', 'O', 'A'};
constexpr image_tag_t image_tag_sstv_rx{'P', 'S', 'R', 'X'};
constexpr image_tag_t image_tag_morse{'P', 'M', 'R', 'S'};
constexpr image_tag_t image_tag_morsetx{'P', 'M', 'R', 'T'};
constexpr image_tag_t image_tag_noop{'P', 'N', 'O', 'P'};
+131
View File
@@ -2410,6 +2410,137 @@ bool NumberField::on_touch(const TouchEvent event) {
return true;
}
/* FloatField ***********************************************************/
FloatField::FloatField(
Point parent_pos,
int length,
range_t range,
float step,
char fill_char,
bool can_loop,
uint8_t precision_)
: Widget{{parent_pos, {8 * length, 16}}},
range{range},
step{step},
length_{length},
fill_char{fill_char},
can_loop{can_loop},
precision{precision_} {
set_focusable(true);
}
float FloatField::value() const {
return value_;
}
void FloatField::getAccessibilityText(std::string& result) {
result = to_string_decimal(value_, precision);
}
void FloatField::getWidgetName(std::string& result) {
result = "FloatField";
}
void FloatField::set_value(float new_value, bool trigger_change) {
const float lo = range.first;
const float hi = range.second;
if (can_loop) {
if (new_value > hi)
new_value = lo;
else if (new_value < lo)
new_value = hi;
}
new_value = clip(new_value, lo, hi);
// set final value if needed
if (new_value != value_) {
value_ = new_value;
if (on_change && trigger_change) on_change(value_);
set_dirty();
}
}
void FloatField::set_range(const float min, const float max) {
range.first = min;
range.second = max;
set_value(value_, false);
}
void FloatField::set_step(const float new_step) {
step = new_step;
}
void FloatField::paint(Painter& painter) {
auto text = to_string_decimal(value_, precision);
const auto paint_style = has_focus() ? style().invert() : style();
// clip to widget size
const auto r = screen_rect();
auto label_r = style().font.size_of(text);
size_t max_chars = (r.width()) / style().font.char_width();
if (label_r.width() > r.width()) {
text = text.substr(0, max_chars);
}
size_t padneeded = max_chars - text.length();
if (padneeded > 0 && fill_char) {
std::string filler(padneeded, fill_char);
text = filler + text;
}
painter.fill_rectangle(r, style().background);
painter.draw_string(
screen_pos(),
paint_style,
text);
}
bool FloatField::on_key(const KeyEvent key) {
if (key == KeyEvent::Select) {
if (on_select) {
on_select(*this);
return true;
} else {
return on_encoder(1);
}
}
return false;
}
bool FloatField::on_encoder(const EncoderEvent delta) {
float old_value = value_;
set_value(value() + (delta * step));
if (on_wrap) {
if ((delta > 0) && (value_ < old_value))
on_wrap(1);
else if ((delta < 0) && (value_ > old_value))
on_wrap(-1);
}
return true;
}
bool FloatField::on_keyboard(const KeyboardEvent key) {
if (key == 10) {
if (on_select) {
on_select(*this);
return true;
}
}
if (key == '+' || key == ' ') {
return on_encoder(1);
}
if (key == '-' || key == 8) {
return on_encoder(-1);
}
return false;
}
bool FloatField::on_touch(const TouchEvent event) {
if (event.type == TouchEvent::Type::Start) {
focus();
}
return true;
}
/* SymField **************************************************************/
SymField::SymField(

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