Compare commits

..

39 Commits

Author SHA1 Message Date
gullradriel 70ac1a03a1 Make stable release (#2895)
* updated submodule
* updated versions
2025-12-21 11:39:47 +01:00
Totoo 2261e53981 fix bit counts (#2894) 2025-12-21 11:38:35 +01:00
Totoo f86d3e51f1 Subcar (#2893) 2025-12-21 11:21:55 +01:00
StarVore Labs f71f19e719 Addition of SSTV RX application (#2888) 2025-12-17 13:14:19 +01:00
RocketGod c53adfc765 Refactor FLEX RX UI to use console for messages (#2890) 2025-12-14 10:08:39 -08:00
gullradriel 7e8ad83537 Update clang format to 18 (#2891)
* move to clang-format-18
* clang-format-18 indendation
2025-12-14 11:26:21 +01:00
RocketGod 472571b1ed Refactor FLEX RX UI to add color cycling and message log (#2885)
Replaces the console with a scrollable menu view for displaying FLEX messages, adds support for cycling text colors, and implements message logging with line wrapping and persistence. Also refactors frequency handling for persistence and updates UI element layout and initialization.
2025-12-12 19:40:15 +01:00
Tim Elfelt 106e56abc3 FLEX pager app (#2883)
* Add FLEX pager support

- Introduced a new FLEX configuration function in baseband_api.
- Added FLEX application view and associated UI elements.
- Implemented FLEX processing logic in proc_flex, including demodulation and message handling.
- Updated CMakeLists to include new FLEX source files and headers.
- Enhanced message system to support FLEX-specific messages and statistics.

This commit lays the groundwork for FLEX pager functionality, allowing for the reception and processing of FLEX messages.

* Fixed baseband and moved app to external with some other fixes.

* Format code

---------

Co-authored-by: RocketGod <57732082+RocketGod-git@users.noreply.github.com>
2025-12-12 17:43:51 +01:00
zxkmm 4129d57c09 fix dead link (#2882)
* fix dead link

* submodule
2025-12-06 07:34:10 -08:00
Totoo caac5e1041 Sonde + map (#2879)
* Update geomap view position on GPS data reception

* Refactor timestamp and temperature/humidity display formatting in SondeView

* Implement battery voltage reading for Meteomodem M20

* Enhance GPS data validation and update OSM zoom handling

- Introduced a new method to validate GPS data in the Packet structure.
- Updated the SondeView to use the new GPS validation method.
- Modified GeoMap to improve handling of OSM zoom levels and ensure consistent usage of real zoom values.
- Adjusted battery voltage calculation for Meteomodem M20 to ensure correct scaling.

* Add serial number extraction for Meteomodem M20 support

* Add support for Meteomodem M20 temperature and humidity readings

* Update log file naming to include timestamp in SondeView

* Add pressure reading support for Meteomodem M20 and update UI

* Update SondeView UI layout and enhance Meteomodem M20 packet handling

* Add vertical speed calculation and display to SondeView

* Fix set_fsk function parameter type for samplesPerSymbol
2025-11-26 19:13:21 +01:00
Totoo 6b02ba6e5d Faster osm (#2874)
Much faster OSM map handler
2025-11-21 09:30:01 +01:00
Totoo c01597baf2 Pocsag manual baud option (#2870)
* baseband part of manual baud control of pocsag

* added manual pocsag baud to ui, to fix #2546

* fix adult toys settings filename
2025-11-18 14:05:27 +01:00
Totoo 43a5163b77 prevent sonde pos to change to 0 when the frame is invalid. fixes #2862 (#2869) 2025-11-18 19:07:40 +08:00
jLynx c46cc431c9 Revert "resolve conflicts merge" (#2860)
This reverts commit 344aa0c741.
2025-11-08 10:21:33 +13:00
jLynx a4d23768c1 Update version.txt (#2858) 2025-11-08 10:13:35 +13:00
gullradriel 344aa0c741 resolve conflicts merge 2025-11-07 21:36:41 +01:00
gullradriel fd7637187a updated version number (#2855)
Co-authored-by: gullradriel <gullradriel@no-mail.com>
2025-11-07 20:52:28 +01:00
Totoo 674b865ec0 Refactor OnTouchEvent functions to return boolean values for better event handling (#2854) 2025-11-05 20:53:23 +01:00
Totoo 00c9c6b40e Fix shift key position (#2850) 2025-10-31 18:25:23 +01:00
RocketGod 113cbc42c9 Add sound effects (#2849)
* Add sound effects

Adding sound effects and volume adjuster in start menu. Sounds are a little clicky but I tinkered a long time and couldn't solve that. Maybe someone else wants to tinker a bit with me.

* Format code
2025-10-30 07:38:45 +01:00
RocketGod 454b8776b6 Refactor gfxEQView UI layout for consistency (#2848)
* Refactor gfxEQView UI layout for consistency

Updated control and graph positioning in gfxEQView to use a standard layout approach, aligning with other applications. Screen dimensions are now used for dynamic placement, and hardcoded values have been replaced for improved maintainability and consistency.

Basically, centered for smaller and larger screens with other visual improvements.

* Fixed screen to Macros - looks good now

Better methods for dynamic screen size
2025-10-30 07:33:38 +01:00
Matej Sochan efdf043d62 fix typo: wps -> wpm in morse_tx (#2847) 2025-10-28 20:55:21 +01:00
gullradriel 0f9d9e589d Revert "Additional debounce control parameters for rotary encoder settings (f…" (#2846)
This reverts commit bf18851b6b.
2025-10-28 22:34:14 +13:00
Totoo 3b57672dda sht4x support,, typo fix (#2843) 2025-10-28 10:14:11 +08:00
Totoo b739dd883c Free up some fw space (#2844) 2025-10-28 08:10:09 +08:00
rmckay bf18851b6b Additional debounce control parameters for rotary encoder settings (for bad/noisy encoders) (#2841)
* Added debounce control options for rotary encoder settings

* ran format-code.sh to adjust whitespace

---------

Co-authored-by: Robert McKay <robert.mckay@ubermorgen.land>
2025-10-27 23:56:27 +01:00
Pezsma 81afec9ea4 Added Adult toy controller external app (#2840) 2025-10-23 13:09:48 +02:00
Totoo 60a5222058 Pacman update (#2837) 2025-10-21 07:37:26 +02:00
Totoo 7041d507ca gracefully handle i2c error (#2838) 2025-10-21 07:37:14 +02:00
Totoo d3373734e9 battleship resizes based on screen size (#2836) 2025-10-18 17:00:50 +02:00
Totoo 200831ad67 fix some bugs due to framesync not fired on stealth mode (#2834) 2025-10-18 13:13:51 +02:00
gullradriel dafe3b7641 update hackrf submodule (#2832) 2025-10-17 19:28:18 +02:00
gullradriel 63634407b6 fix ctrl click link (#2833) 2025-10-17 17:09:57 +00:00
Totoo 9f06ccf9ae Support some space chars in serial commands (fs) (#2828) 2025-10-17 17:05:27 +02:00
Totoo 6782e12a15 Fix morse tx cw+loop (#2827) 2025-10-17 17:03:34 +02:00
Totoo cbbd8103d3 Touch for MenuView and Freqlist (#2829)
* freqman add touch support. solves #1919

* menuview touch support
2025-10-17 21:59:35 +08:00
Pezsma e88ab44f49 Modify Morse code table (#2825)
Fixed morse code table
2025-10-17 10:32:01 +02:00
Pezsma 545dead1ca Added new game: Morse trainer (#2820)
* Added new game: Morse trainer

* code format error fix, and ui alignment
2025-10-16 13:01:28 +02:00
Totoo e3b2a65b39 Oregon fixes (#2822) 2025-10-16 13:00:40 +02:00
158 changed files with 9436 additions and 682 deletions
+1
View File
@@ -19,5 +19,6 @@ jobs:
- name: clang-format Check
uses: jidicula/clang-format-action@v4.11.0
with:
clang-format-version: '18'
check-path: ${{ matrix.path }}
fallback-style: Chromium
+1 -1
View File
@@ -1 +1 @@
v2.1.0
v2.3.1
+1 -1
View File
@@ -1 +1 @@
v2.2.0
v2.3.2
-2
View File
@@ -192,7 +192,6 @@ set(CPPSRC
core_control.cpp
database.cpp
gradient.cpp
rfm69.cpp
event_m0.cpp
file_reader.cpp
file.cpp
@@ -261,7 +260,6 @@ set(CPPSRC
ui/ui_receiver.cpp
ui/ui_rssi.cpp
ui/ui_freqlist.cpp
ui/ui_tv.cpp
ui/ui_spectrum.cpp
ui/ui_tabview.cpp
ui/ui_textentry.cpp
+1 -1
View File
@@ -159,7 +159,7 @@ class AISAppView : public View {
~AISAppView();
void set_parent_rect(const Rect new_parent_rect) override;
void paint(Painter&) override{};
void paint(Painter&) override {};
void focus() override;
+1 -1
View File
@@ -59,7 +59,7 @@ class BLECommView : public View {
~BLECommView();
void set_parent_rect(const Rect new_parent_rect) override;
void paint(Painter&) override{};
void paint(Painter&) override {};
void focus() override;
+1 -1
View File
@@ -209,7 +209,7 @@ class BLERxView : public View {
~BLERxView();
void set_parent_rect(const Rect new_parent_rect) override;
void paint(Painter&) override{};
void paint(Painter&) override {};
void focus() override;
+1 -1
View File
@@ -105,7 +105,7 @@ class BLETxView : public View {
~BLETxView();
void set_parent_rect(const Rect new_parent_rect) override;
void paint(Painter&) override{};
void paint(Painter&) override {};
void focus() override;
+5 -2
View File
@@ -56,6 +56,7 @@ POCSAGSettingsView::POCSAGSettingsView(
: settings_{settings} {
add_children(
{&labels,
&opt_baud_rate,
&check_log,
&check_log_raw,
&check_small_font,
@@ -65,6 +66,7 @@ POCSAGSettingsView::POCSAGSettingsView(
&field_filter_address,
&button_save});
opt_baud_rate.set_by_value(settings_.baud_rate);
check_log.set_value(settings_.enable_logging);
check_log_raw.set_value(settings_.enable_raw_log);
check_small_font.set_value(settings_.enable_small_font);
@@ -81,7 +83,7 @@ POCSAGSettingsView::POCSAGSettingsView(
settings_.hide_addr_only = check_hide_addr_only.value();
settings_.filter_mode = opt_filter_mode.selected_index_value();
settings_.filter_address = field_filter_address.to_integer();
settings_.baud_rate = opt_baud_rate.selected_index_value();
nav.pop();
};
}
@@ -142,7 +144,7 @@ POCSAGAppView::POCSAGAppView(NavigationView& nav)
audio::output::start();
receiver_model.enable();
baseband::set_pocsag();
baseband::set_pocsag((int8_t)settings_.baud_rate);
}
void POCSAGAppView::focus() {
@@ -182,6 +184,7 @@ void POCSAGAppView::refresh_ui() {
btn_text = "Filter Last";
break;
}
baseband::set_pocsag((int8_t)settings_.baud_rate);
button_filter_last.set_text(btn_text);
}
+11
View File
@@ -126,6 +126,7 @@ struct POCSAGSettings {
bool hide_bad_data = false;
bool hide_addr_only = false;
uint8_t filter_mode = false;
int32_t baud_rate = -1;
uint32_t filter_address = 0;
};
@@ -139,7 +140,16 @@ class POCSAGSettingsView : public View {
private:
POCSAGSettings& settings_;
OptionsField opt_baud_rate{
{8 * 8, 0 * 16},
4,
{{"Auto", -1},
{" 512", 0},
{"1200", 1},
{"2400", 2}}};
Labels labels{
{{2 * 8, 0 * 16}, "Baud:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 12 * 16}, "Filter Mode:", Theme::getInstance()->fg_light->foreground},
{{2 * 8, 13 * 16}, "Filter Addr:", Theme::getInstance()->fg_light->foreground},
};
@@ -221,6 +231,7 @@ class POCSAGAppView : public View {
{"filter_address"sv, &settings_.filter_address},
{"hide_bad_data"sv, &settings_.hide_bad_data},
{"hide_addr_only"sv, &settings_.hide_addr_only},
{"baud_rate"sv, &settings_.baud_rate},
}};
void refresh_ui();
@@ -10,7 +10,7 @@ namespace ui {
constexpr std::string_view mayhem_information_list[] = {
"#****** Mayhem Community ******",
" ",
" https://discord.mayhem.app",
" https://discord.hackrf.app",
" ",
"#**** List of contributors ****",
" ",
+1 -1
View File
@@ -65,7 +65,7 @@ class FreqManBaseView : public View {
OptionsField options_category{
{3 * 8, 2},
20 /* length */,
19 /* length */,
{}};
FreqManUIList freqlist_view{
+1 -1
View File
@@ -171,7 +171,7 @@ void IQTrimView::update_range_controls(iq::TrimRange trim_range) {
}
void IQTrimView::profile_capture() {
power_buckets_ = {};
power_buckets_.clear();
iq::PowerBuckets buckets{
.p = power_buckets_.data(),
.size = power_buckets_.size()};
+2 -2
View File
@@ -1086,8 +1086,8 @@ void ReconView::on_statistics_update(const ChannelStatistics& statistics) {
if (stepper < 0) stepper++;
if (stepper > 0) stepper--;
} // if( recon || stepper != 0 || index_stepper != 0 )
} // if (frequency_list.size() > 0 )
} /* on_statistics_updates */
} // if (frequency_list.size() > 0 )
} /* on_statistics_updates */
}
handle_retune();
recon_redraw();
+34 -12
View File
@@ -30,11 +30,10 @@
#include "portapack.hpp"
#include <cstring>
#include <stdio.h>
#include "rtc_time.hpp"
using namespace portapack;
namespace pmem = portapack::persistent_memory;
#include "string_format.hpp"
#include "complex.hpp"
void SondeLogger::on_packet(const sonde::Packet& packet) {
@@ -65,6 +64,8 @@ SondeView::SondeView(NavigationView& nav)
&text_frame,
&text_temp,
&text_humid,
&text_press,
&text_vspeed,
&geopos,
&button_see_qr,
&button_see_map});
@@ -107,7 +108,7 @@ SondeView::SondeView(NavigationView& nav)
logger = std::make_unique<SondeLogger>();
if (logger)
logger->append(logs_dir / u"SONDE.TXT");
logger->append(logs_dir / u"SONDE_" + to_string_timestamp(rtc_time::now()) + u".TXT");
if (pmem::beep_on_packets()) {
audio::set_rate(audio::Rate::Hz_24000);
@@ -155,7 +156,7 @@ void SondeView::on_packet(const sonde::Packet& packet) {
sonde_id = packet.serial_number(); // used also as tag on the geomap
text_serial.set(sonde_id);
text_timestamp.set(to_string_timestamp(packet.received_at()));
text_timestamp.set(to_string_datetime(packet.received_at(), TimeFormat::YMDHMS));
text_voltage.set(unit_auto_scale(packet.battery_voltage(), 2, 2) + "V");
@@ -163,21 +164,42 @@ void SondeView::on_packet(const sonde::Packet& packet) {
temp_humid_info = packet.get_temp_humid();
if (temp_humid_info.humid != 0) {
double decimals = abs(get_decimals(temp_humid_info.humid, 10, true));
text_humid.set(to_string_dec_int((int)temp_humid_info.humid) + "." + to_string_dec_uint(decimals, 1) + "%");
text_humid.set(to_string_decimal(temp_humid_info.humid, 1) + "%");
}
if (temp_humid_info.temp != 0) {
double decimals = abs(get_decimals(temp_humid_info.temp, 10, true));
text_temp.set(to_string_dec_int((int)temp_humid_info.temp) + "." + to_string_dec_uint(decimals, 1) + STR_DEGREES_C);
text_temp.set(to_string_decimal(temp_humid_info.temp, 1) + STR_DEGREES_C);
}
if (packet.get_pressure() != 0) {
text_press.set(to_string_decimal(packet.get_pressure(), 1) + " hPa");
}
gps_info = packet.get_GPS_data();
geopos.set_altitude(gps_info.alt);
geopos.set_lat(gps_info.lat);
geopos.set_lon(gps_info.lon);
if (last_timestamp_update_ != 0 && last_altitude_ != 0) {
// calculate speeds
float vspeed = 0;
time_t currpackettime = rtc_time::rtcToUnixUTC(packet.received_at());
int32_t time_diff = (currpackettime - last_timestamp_update_);
if (time_diff >= 10) { // update only every 10 seconds
vspeed = (static_cast<int>(gps_info.alt) - static_cast<int>(last_altitude_)) / (float)time_diff;
last_timestamp_update_ = currpackettime;
last_altitude_ = gps_info.alt;
text_vspeed.set(to_string_decimal(vspeed, 1) + " m/s");
}
} else { // save first valid packet time + altitude
last_timestamp_update_ = rtc_time::rtcToUnixUTC(packet.received_at());
last_altitude_ = geopos.altitude();
}
if (gps_info.is_valid()) { // only update when valid, to prevent flashing
geopos.set_altitude(gps_info.alt);
geopos.set_lat(gps_info.lat);
geopos.set_lon(gps_info.lon);
if (geomap_view_) {
geomap_view_->update_position(gps_info.lat, gps_info.lon, 400, gps_info.alt, 0);
}
}
if (logger && logging) {
logger->on_packet(packet);
}
+36 -24
View File
@@ -30,6 +30,7 @@
#include "ui_rssi.hpp"
#include "ui_qrcode.hpp"
#include "ui_geomap.hpp"
#include "string_format.hpp"
#include "event_m0.hpp"
@@ -94,32 +95,33 @@ class SondeView : public View {
// AudioOutput audio_output { };
Labels labels{
{{4 * 8, 2 * 16}, "Type:", Theme::getInstance()->fg_light->foreground},
{{6 * 8, 3 * 16}, "ID:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), 4 * 16}, "DateTime:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(4), UI_POS_Y(2)}, "Type:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(6), UI_POS_Y(3)}, "ID:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(4)}, "DateTime:", Theme::getInstance()->fg_light->foreground},
{{3 * 8, 5 * 16}, "Vbatt:", Theme::getInstance()->fg_light->foreground},
{{3 * 8, 6 * 16}, "Frame:", Theme::getInstance()->fg_light->foreground},
{{4 * 8, 7 * 16}, "Temp:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), 8 * 16}, "Humidity:", Theme::getInstance()->fg_light->foreground}};
{{UI_POS_X(3), UI_POS_Y(5)}, "Vbatt:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(3), UI_POS_Y(6)}, "Frame:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(4), UI_POS_Y(7)}, "Temp:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(8)}, "Humidity:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(0), UI_POS_Y(9)}, "Pressure:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(2), UI_POS_Y(10)}, "VSpeed:", Theme::getInstance()->fg_light->foreground}};
RxFrequencyField field_frequency{
{UI_POS_X(0), 0 * 8},
{UI_POS_X(0), UI_POS_Y(0)},
nav_};
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), UI_POS_Y(0), UI_POS_WIDTH_REMAINING(24), 4}};
Channel channel{
{21 * 8, 5, UI_POS_WIDTH_REMAINING(24), 4},
{UI_POS_X(21), UI_POS_Y(0) + 5, UI_POS_WIDTH_REMAINING(24), 4},
};
AudioVolumeField field_volume{
@@ -136,47 +138,57 @@ class SondeView : public View {
"CRC"};
Text text_signature{
{9 * 8, 2 * 16, 10 * 8, 16},
{UI_POS_X(9), UI_POS_Y(2), UI_POS_WIDTH_REMAINING(10), UI_POS_HEIGHT(1)},
"..."};
Text text_serial{
{9 * 8, 3 * 16, 11 * 8, 16},
{UI_POS_X(9), UI_POS_Y(3), UI_POS_WIDTH_REMAINING(10), UI_POS_HEIGHT(1)},
"..."};
Text text_timestamp{
{9 * 8, 4 * 16, 11 * 8, 16},
{UI_POS_X(9), UI_POS_Y(4), UI_POS_WIDTH_REMAINING(9), UI_POS_HEIGHT(1)},
"..."};
Text text_voltage{
{9 * 8, 5 * 16, 10 * 8, 16},
{UI_POS_X(9), UI_POS_Y(5), UI_POS_WIDTH(10), UI_POS_HEIGHT(1)},
"..."};
Text text_frame{
{9 * 8, 6 * 16, 10 * 8, 16},
{UI_POS_X(9), UI_POS_Y(6), UI_POS_WIDTH(10), UI_POS_HEIGHT(1)},
"..."};
Text text_temp{
{9 * 8, 7 * 16, 10 * 8, 16},
{UI_POS_X(9), UI_POS_Y(7), UI_POS_WIDTH(10), UI_POS_HEIGHT(1)},
"..."};
Text text_humid{
{9 * 8, 8 * 16, 10 * 8, 16},
{UI_POS_X(9), UI_POS_Y(8), UI_POS_WIDTH(10), UI_POS_HEIGHT(1)},
"..."};
Text text_press{
{UI_POS_X(9), UI_POS_Y(9), UI_POS_WIDTH(10), UI_POS_HEIGHT(1)},
"..."};
Text text_vspeed{
{UI_POS_X(9), UI_POS_Y(10), UI_POS_WIDTH(10), UI_POS_HEIGHT(1)},
"..."};
GeoPos geopos{
{0, 12 * 16},
{UI_POS_X(0), UI_POS_Y(12)},
GeoPos::alt_unit::METERS,
GeoPos::spd_unit::HIDDEN};
Button button_see_qr{
{UI_POS_X_CENTER(12) - UI_POS_WIDTH(8), UI_POS_Y_BOTTOM(4), 12 * 8, 3 * 16},
{UI_POS_X_CENTER(12) - UI_POS_WIDTH(8), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(12), UI_POS_HEIGHT(3)},
"See QR"};
Button button_see_map{
{UI_POS_X_CENTER(12) + UI_POS_WIDTH(8), UI_POS_Y_BOTTOM(4), 12 * 8, 3 * 16},
{UI_POS_X_CENTER(12) + UI_POS_WIDTH(8), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(12), UI_POS_HEIGHT(3)},
"See on map"};
GeoMapView* geomap_view_{nullptr};
time_t last_timestamp_update_{0};
uint32_t last_altitude_{0};
MessageHandlerRegistration message_handler_packet{
Message::ID::SondePacket,
@@ -285,9 +285,9 @@ bool StandaloneView::on_encoder(const EncoderEvent event) {
bool StandaloneView::on_touch(const TouchEvent event) {
if (get_application_information()->header_version > 1) {
get_application_information()->OnTouchEvent(event.point.x(), event.point.y(), (uint32_t)event.type);
return get_application_information()->OnTouchEvent(event.point.x(), event.point.y(), (uint32_t)event.type);
}
return true;
return false;
}
bool StandaloneView::on_keyboard(const KeyboardEvent event) {
+1 -1
View File
@@ -339,7 +339,7 @@ void SubGhzDRecentEntryDetailView::parseProtocol() {
if (entry_.sensorType == FPS_CAMEATOMO) {
entry_.data ^= 0xFFFFFFFFFFFFFFFF;
entry_.data <<= 4;
uint8_t pack[8] = {};
uint8_t pack[8];
pack[0] = (entry_.data >> 56);
pack[1] = ((entry_.data >> 48) & 0xFF);
pack[2] = ((entry_.data >> 40) & 0xFF);
+1 -1
View File
@@ -612,7 +612,7 @@ void TextEditorView::open_file(const fs::path& path) {
viewer.clear_file();
delete_temp_file(path_);
path_ = {};
path_ = "";
file_dirty_ = false;
has_temp_file_ = false;
auto result = FileWrapper::open(
@@ -197,6 +197,10 @@ WeatherView::~WeatherView() {
baseband::shutdown();
}
uint16_t WeatherView::bcd_decode_short(uint32_t data) {
return (data & 0xF) * 10 + ((data >> 4) & 0xF);
}
const char* WeatherView::getWeatherSensorTypeName(FPROTO_WEATHER_SENSOR type) {
switch (type) {
case FPW_NexusTH:
@@ -225,6 +229,8 @@ const char* WeatherView::getWeatherSensorTypeName(FPROTO_WEATHER_SENSOR type) {
return "LaCrosse TX141THBv2";
case FPW_OREGON2:
return "Oregon2";
case FPW_OREGON2B:
return "Oregon2B";
case FPW_OREGON3:
return "Oregon3";
case FPW_OREGONv1:
@@ -299,7 +305,9 @@ WeatherRecentEntry WeatherView::process_data(const WeatherDataMessage* data) {
WeatherRecentEntry ret = {};
ret.sensorType = data->sensorType;
int16_t i16 = 0;
int32_t i32 = 0;
uint16_t u16 = 0;
uint64_t u64 = 0;
uint8_t u8 = 0;
uint8_t channel_3021[] = {3, 0, 2, 1};
@@ -442,12 +450,34 @@ WeatherRecentEntry WeatherView::process_data(const WeatherDataMessage* data) {
ret.humidity = (data->decode_data >> 8) & 0xFF;
break;
case FPW_OREGON2:
i16 = ((data->decode_data >> 4) & 0xF) * 10 + (((data->decode_data >> 4) >> 4) & 0xF);
i16 *= 10;
i16 += (data->decode_data >> 12) & 0xF;
if (data->decode_data & 0xF) i16 = -i16;
ret.temp = (float)i16 / 10.0;
// todo fix missing parts.
i32 = bcd_decode_short(data->decode_data >> 4);
i32 *= 10;
i32 += (data->decode_data >> 12) & 0xf;
if (data->decode_data & 0xF) i32 = -i32;
ret.temp = (float)i32 / 10.0;
ret.battery_low = ((data->decode_data >> 32) & 0x4) ? 1 : 0;
u8 = (data->decode_data >> 44) & 0xF;
ret.channel = 1;
while (u8 > 1) {
ret.channel++;
u8 >>= 1;
}
break;
case FPW_OREGON2B:
ret.humidity = bcd_decode_short(data->decode_data);
u64 = data->decode_data >> 8;
i32 = bcd_decode_short(u64 >> 4);
i32 *= 10;
i32 += (u64 >> 12) & 0xf;
if (u64 & 0xF) i32 = -i32;
ret.temp = (float)i32 / 10.0;
ret.battery_low = ((data->decode_data >> 32) & 0x4) ? 1 : 0;
u8 = (data->decode_data >> 44) & 0xF;
ret.channel = 1;
while (u8 > 1) {
ret.channel++;
u8 >>= 1;
}
break;
case FPW_OREGON3:
// todo check
@@ -114,6 +114,7 @@ class WeatherView : public View {
private:
void on_tick_second();
uint16_t bcd_decode_short(uint32_t data);
void on_data(const WeatherDataMessage* data);
WeatherRecentEntry process_data(const WeatherDataMessage* data);
NavigationView& nav_;
+20 -2
View File
@@ -147,6 +147,19 @@ void set_sstv_data(const uint8_t vis_code, const uint32_t pixel_duration) {
send_message(&message);
}
void set_sstvrx_data(const uint8_t code) {
const SSTVRXConfigureMessage message{
code};
send_message(&message);
}
void set_sstvrx_phase_slant(const int16_t phase, const int16_t slant) {
const SSTVRXPhaseSlantMessage message{
phase,
slant};
send_message(&message);
}
void set_afsk(const uint32_t baudrate, const uint32_t word_length, const uint32_t trigger_value, const bool trigger_word) {
const AFSKRxConfigureMessage message{
baudrate,
@@ -288,8 +301,8 @@ void set_fsk_data(const uint32_t stream_length, const uint32_t samples_per_bit,
send_message(&message);
}
void set_pocsag() {
const POCSAGConfigureMessage message{};
void set_pocsag(int8_t baud_config) {
const POCSAGConfigureMessage message{baud_config};
send_message(&message);
}
@@ -328,6 +341,11 @@ void set_noaaapt_config() {
send_message(&message);
}
void set_flex_config() {
const FlexConfigureMessage message{};
send_message(&message);
}
void set_siggen_tone(const uint32_t tone) {
const SigGenToneMessage message{
TONES_F2D(tone, TONES_SAMPLERATE)};
+5 -2
View File
@@ -74,13 +74,15 @@ void set_tone(const uint32_t index, const uint32_t delta, const uint32_t duratio
void set_tones_config(const uint32_t bw, const uint32_t pre_silence, const uint16_t tone_count, const bool dual_tone, const bool audio_out);
void kill_tone();
void set_sstv_data(const uint8_t vis_code, const uint32_t pixel_duration);
void set_sstvrx_data(const uint8_t code);
void set_sstvrx_phase_slant(const int16_t phase, const int16_t slant);
void set_audiotx_config(const uint32_t divider, const float deviation_hz, const float audio_gain, uint8_t audio_shift_bits_s16, uint8_t bits_per_sample, const uint32_t tone_key_delta, const bool am_enabled, const bool dsb_enabled, const bool usb_enabled, const bool lsb_enabled);
void set_fifo_data(const int8_t* data);
void set_pitch_rssi(int32_t avg, bool enabled);
void set_afsk_data(const uint32_t afsk_samples_per_bit, const uint32_t afsk_phase_inc_mark, const uint32_t afsk_phase_inc_space, const uint8_t afsk_repeat, const uint32_t afsk_bw, const uint8_t symbol_count);
void kill_afsk();
void set_afsk(const uint32_t baudrate, const uint32_t word_length, const uint32_t trigger_value, const bool trigger_word);
void set_fsk(const uint32_t samplesPerSymbol, const uint32_t syncWord, const uint8_t syncWordLength, const uint32_t preamble, const uint8_t preambleLength, uint16_t numDataBytes);
void set_fsk(const uint8_t samplesPerSymbol, const uint32_t syncWord, const uint8_t syncWordLength, const uint32_t preamble, const uint8_t preambleLength, uint16_t numDataBytes);
void set_aprs(const uint32_t baudrate);
void set_btlerx(uint8_t channel_number);
@@ -91,7 +93,7 @@ void set_nrf(const uint32_t baudrate, const uint32_t word_length, const uint32_t
void set_ook_data(const uint32_t stream_length, const uint32_t samples_per_bit, const uint8_t repeat, const uint32_t pause_symbols, const uint8_t de_bruijn_length = 0);
void kill_ook();
void set_fsk_data(const uint32_t stream_length, const uint32_t samples_per_bit, const uint32_t shift, const uint32_t progress_notice);
void set_pocsag();
void set_pocsag(int8_t baud_config = -1);
void set_adsb();
void set_jammer(const bool run, const jammer::JammerType type, const uint32_t speed);
void set_rds_data(const uint16_t message_length);
@@ -102,6 +104,7 @@ void set_spectrum_painter_config(const uint16_t width, const uint16_t height, bo
void set_subghzd_config(uint8_t modulation, uint32_t sampling_rate);
void set_wefax_config(uint8_t lpm, uint8_t ioc);
void set_noaaapt_config();
void set_flex_config();
void request_roger_beep();
void request_rssi_beep();
+38
View File
@@ -415,6 +415,44 @@ static constexpr Bitmap bitmap_icon_adsb{
{16, 16},
bitmap_icon_adsb_data};
static constexpr uint8_t bitmap_icon_adulttoys_data[] = {
0x00,
0x00,
0x30,
0x0C,
0x78,
0x1E,
0x7C,
0x3E,
0xFE,
0x7F,
0xFE,
0x7F,
0xFE,
0x7F,
0xFE,
0x7F,
0xFC,
0x3F,
0xFC,
0x3F,
0xF8,
0x1F,
0xF0,
0x0F,
0xE0,
0x07,
0xC0,
0x03,
0x80,
0x01,
0x00,
0x00,
};
static constexpr Bitmap bitmap_icon_adulttoys{
{16, 16},
bitmap_icon_adulttoys_data};
static constexpr uint8_t bitmap_icon_ais_data[] = {
0x00,
0x01,
+6 -12
View File
@@ -244,8 +244,7 @@ static void portapack_tcxo_enable() {
/* Delay >10ms at 96MHz clock speed for reference oscillator to start. */
/* Delay an additional 1ms (arbitrary) for the clock generator to detect a signal. */
volatile uint32_t delay = 240000 + 24000;
while (delay--)
;
while (delay--);
}
static void portapack_tcxo_disable() {
@@ -329,8 +328,7 @@ void ClockManager::init_clock_generator() {
: (ref_pll == ClockControl::MultiSynthSource::PLLB)
? 0x40
: 0x20;
while ((clock_generator.device_status() & device_status_mask) != 0)
;
while ((clock_generator.device_status() & device_status_mask) != 0);
clock_generator.set_clock_control(
clock_generator_output_mcu_clkin,
@@ -377,8 +375,7 @@ ClockManager::Reference ClockManager::choose_reference() {
if (hackrf_r9) {
gpio_r9_clkin_en.write(1);
volatile uint32_t delay = 240000 + 24000;
while (delay--)
;
while (delay--);
}
const auto detected_reference = detect_reference_source();
@@ -513,8 +510,7 @@ 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?!
while (LPC_CGU->FREQ_MON.MEAS == 1)
;
while (LPC_CGU->FREQ_MON.MEAS == 1);
}
uint32_t ClockManager::get_frequency_monitor_measurement_in_hertz() {
@@ -559,8 +555,7 @@ void ClockManager::start_audio_pll() {
});
cgu::pll0audio::power_up();
while (!cgu::pll0audio::is_locked())
;
while (!cgu::pll0audio::is_locked());
cgu::pll0audio::clock_enable();
set_base_audio_clock_divider(1);
@@ -577,8 +572,7 @@ void ClockManager::set_base_audio_clock_divider(const size_t divisor) {
void ClockManager::stop_audio_pll() {
cgu::pll0audio::clock_disable();
cgu::pll0audio::power_down();
while (cgu::pll0audio::is_locked())
;
while (cgu::pll0audio::is_locked());
}
void ClockManager::enable_clock_output(bool enable) {
+3 -6
View File
@@ -139,13 +139,11 @@ void runtime_error(uint8_t source) {
led.off();
// wait for DFU button release if pressed, so we don't immediately jump into stack dump
while (swizzled_switches() & (1 << (int)Switch::Dfu))
;
while (swizzled_switches() & (1 << (int)Switch::Dfu));
while (true) {
volatile size_t n = 1000000U;
while (n--)
;
while (n--);
led.toggle();
// Stack dump will cover entire screen, so wait for DFU button press to attempt it
@@ -225,8 +223,7 @@ void draw_stack_dump() {
// Out of room on the screen or end of stack - allow Up/Down paging.
// First wait for button release from previous press.
// NOTE: can't call swizzle_switches() with interrupted enabled!
while (swizzled_switches() & ((1 << (int)Switch::Right) | (1 << (int)Switch::Left) | (1 << (int)Switch::Down) | (1 << (int)Switch::Up) | (1 << (int)Switch::Sel) | (1 << (int)Switch::Dfu)))
;
while (swizzled_switches() & ((1 << (int)Switch::Right) | (1 << (int)Switch::Left) | (1 << (int)Switch::Down) | (1 << (int)Switch::Up) | (1 << (int)Switch::Sel) | (1 << (int)Switch::Dfu)));
painter.draw_string({border, portapack::display.height() - border - 8}, *Theme::getInstance()->bg_darkest_small, "Use UP/DOWN key");
+1 -2
View File
@@ -41,8 +41,7 @@ extern uint32_t __process_stack_end__;
inline uint32_t get_free_stack_space() {
uint32_t* p;
for (p = &__process_stack_base__; *p == CRT0_STACKS_FILL_PATTERN && p < &__process_stack_end__; p++)
;
for (p = &__process_stack_base__; *p == CRT0_STACKS_FILL_PATTERN && p < &__process_stack_end__; p++);
auto stack_space_left = p - &__process_stack_base__;
return stack_space_left;
+13 -16
View File
@@ -124,12 +124,12 @@ void EventDispatcher::request_stop() {
void EventDispatcher::set_display_sleep(const bool sleep) {
// TODO: Distribute display sleep message more broadly, shut down data generation
// on baseband side, since all that data is being discarded during sleep.
// on baseband side, since all that data is being discarded during sleep. -- DON'T TODO it, sincethe stealth mode want to send with screen off!
if (sleep) {
portapack::backlight()->off();
portapack::display.sleep();
portapack::display.sleep(false); // when called the hw_sleep = true, the irq wont fire, so the EVT_MASK_LCD_FRAME_SYNC won't set.
} else {
portapack::display.wake();
portapack::display.wake(true); // not important, command not affect if already hw waken up
// Don't turn on backlight here.
// Let frame sync handler turn on backlight after repaint.
}
@@ -180,12 +180,10 @@ void EventDispatcher::dispatch(const eventmask_t events) {
/*if( events & EVT_MASK_LCD_FRAME_SYNC ) {
blink_timer();
}*/
if (events & EVT_MASK_LCD_FRAME_SYNC) {
handle_lcd_frame_sync(!EventDispatcher::display_sleep);
}
if (!EventDispatcher::display_sleep) {
if (events & EVT_MASK_LCD_FRAME_SYNC) {
handle_lcd_frame_sync();
}
if (events & EVT_MASK_ENCODER) {
handle_encoder();
}
@@ -328,17 +326,16 @@ ui::Widget* EventDispatcher::getFocusedWidget() {
return context.focus_manager().focus_widget();
}
void EventDispatcher::handle_lcd_frame_sync() {
void EventDispatcher::handle_lcd_frame_sync(bool screen_on) {
bool waiting_for_frame = this->waiting_for_frame;
DisplayFrameSyncMessage message;
DisplayFrameSyncMessage message; // send framesync msg all the time, bc some apps relay on it
message_map.send(&message);
static_cast<ui::SystemView*>(top_widget)->paint_overlay();
painter.paint_widget_tree(top_widget);
portapack::backlight()->on();
if (screen_on) { // only draw when screen is on
static_cast<ui::SystemView*>(top_widget)->paint_overlay();
painter.paint_widget_tree(top_widget);
portapack::backlight()->on();
}
if (waiting_for_frame)
this->waiting_for_frame = false;
}
+1 -1
View File
@@ -133,7 +133,7 @@ class EventDispatcher {
void on_keyboard_event(ui::KeyboardEvent event);
// void blink_timer();
void handle_lcd_frame_sync();
void handle_lcd_frame_sync(bool screen_on);
void handle_switches();
void handle_encoder();
void handle_touch();
@@ -0,0 +1,85 @@
/*
* 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 "ui.hpp"
#include "ui_adult_toys_controller.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::adult_toys_controller {
void initialize_app(::ui::NavigationView& nav) {
nav.push<AdultToysView>();
}
} // namespace ui::external_app::adult_toys_controller
extern "C" {
__attribute__((section(".external_app.app_adult_toys_controller.application_information"), used)) application_information_t _application_information_adult_toys_controller = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::adult_toys_controller::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "Adult Toys",
/*.bitmap_data = */ {
0x00,
0x00,
0x30,
0x0C,
0x78,
0x1E,
0x7C,
0x3E,
0xFE,
0x7F,
0xFE,
0x7F,
0xFE,
0x7F,
0xFE,
0x7F,
0xFC,
0x3F,
0xFC,
0x3F,
0xF8,
0x1F,
0xF0,
0x0F,
0xE0,
0x07,
0xC0,
0x03,
0x80,
0x01,
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_btle_tx */ {'P', 'B', 'T', 'T'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
}
@@ -0,0 +1,373 @@
#include "ui_adult_toys_controller.hpp"
#include "ui_modemsetup.hpp"
#include "modems.hpp"
#include "audio.hpp"
#include "baseband_api.hpp"
#include "string_format.hpp"
#include "portapack_persistent_memory.hpp"
#include "ui_navigation.hpp"
using namespace portapack;
using namespace modems;
using namespace ui;
namespace ui::external_app::adult_toys_controller {
void AdultToysView::focus() {
button_on.focus();
}
AdultToysView::AdultToysView(NavigationView& nav)
: nav_{nav} {
add_children({
&button_on,
&btn_adult,
&btn_child,
&btn_mode_decrease,
&btn_mode_increase,
&btn_pcknum_inc,
&btn_pcknum_dec,
&chk_mode_rnd,
&chk_mode_play,
&chk_mode_stop,
&chk_mode_ncnt,
&chk_mode_infinite,
&field_frequency,
&txt_selected_mode,
&options_target,
&labels,
&message_num,
&tx_view,
&screen_message_1,
&screen_message_2,
&screen_message_3,
&screen_message_4,
&screen_message_5,
&screen_message_6,
&screen_message_7,
&screen_message_8,
&screen_message_9,
&screen_message_10,
});
btn_adult.on_select = [this](Button&) {
start_screen = true;
hidden_program(!start_screen);
};
btn_child.on_select = [this](Button&) {
nav_.pop();
};
button_on.on_select = [this](Button&) {
if (play_running || stop_running) {
if (button_onstate) {
button_onstate = false;
stop();
button_on.set_text(LanguageHelper::currentMessages[LANG_START]);
} else {
button_onstate = true;
printCurrentModes();
start();
button_on.set_text(LanguageHelper::currentMessages[LANG_STOP]);
}
} // if play_running || stop_running
};
btn_mode_decrease.on_select = [this](Button&) {
if (toy_packet > 0) {
toy_packet--;
printCurrentModes();
}
};
btn_mode_increase.on_select = [this](Button&) {
if (stop_running || play_running) {
if (play_running && (toy_packet < max_plays - 1)) {
toy_packet++;
} else {
if (stop_running && toy_packet < max_stops - 1) {
toy_packet++;
}
}
printCurrentModes();
}
};
btn_pcknum_inc.on_select = [this](Button&) {
if (!button_onstate) {
chk_mode_ncnt.set_value(true);
if (n_message_set < n_message_max) {
n_message_set++;
} else {
n_message_set = 0;
}
message_num.set_value(n_message_set);
n_message_current = n_message_set;
}
};
btn_pcknum_dec.on_select = [this](Button&) {
if (!button_onstate) {
chk_mode_ncnt.set_value(true);
if (n_message_set > 0) {
n_message_set--;
} else {
n_message_set = n_message_max;
}
message_num.set_value(n_message_set);
n_message_current = n_message_set;
}
};
message_num.on_change = [this](int32_t v) {
if (!button_onstate) {
chk_mode_ncnt.set_value(true);
n_message_set = static_cast<uint16_t>(v);
n_message_current = n_message_set;
} else {
if (!button_onstate) message_num.set_value(n_message_current);
}
};
chk_mode_rnd.on_select = [this](Checkbox&, bool v) {
random_running = v;
};
chk_mode_play.on_select = [this](Checkbox&, bool v) {
play_running = v;
if (play_running && stop_running) {
toy_packet = 0;
stop_running = false;
chk_mode_stop.set_value(stop_running);
}
if (play_running) printCurrentModes();
};
chk_mode_stop.on_select = [this](Checkbox&, bool v) {
stop_running = v;
if (play_running && stop_running) {
toy_packet = 0;
play_running = false;
chk_mode_play.set_value(play_running);
}
if (stop_running) printCurrentModes();
};
chk_mode_ncnt.on_select = [this](Checkbox&, bool v) {
n_message_running = v;
if (n_message_running && inf_message_running) {
inf_message_running = false;
chk_mode_infinite.set_value(inf_message_running);
}
};
chk_mode_infinite.on_select = [this](Checkbox&, bool v) {
inf_message_running = v;
if (n_message_running && inf_message_running) {
n_message_running = false;
chk_mode_ncnt.set_value(n_message_running);
}
};
options_target.on_change = [this](size_t, int32_t i) {
target = (uint8_t)i;
};
chk_mode_infinite.set_value(true);
chk_mode_play.set_value(true);
}
void AdultToysView::hidden_program(bool hide) {
options_target.hidden(hide);
labels.hidden(hide);
button_on.hidden(hide);
btn_mode_decrease.hidden(hide);
btn_mode_increase.hidden(hide);
btn_pcknum_inc.hidden(hide);
btn_pcknum_dec.hidden(hide);
chk_mode_rnd.hidden(hide);
chk_mode_play.hidden(hide);
chk_mode_stop.hidden(hide);
chk_mode_ncnt.hidden(hide);
chk_mode_infinite.hidden(hide);
field_frequency.hidden(hide);
txt_selected_mode.hidden(hide);
message_num.hidden(hide);
tx_view.hidden(hide);
btn_adult.hidden(!hide);
btn_child.hidden(!hide);
screen_message_1.hidden(!hide);
screen_message_2.hidden(!hide);
screen_message_3.hidden(!hide);
screen_message_4.hidden(!hide);
screen_message_5.hidden(!hide);
screen_message_6.hidden(!hide);
screen_message_7.hidden(!hide);
screen_message_8.hidden(!hide);
screen_message_9.hidden(!hide);
screen_message_10.hidden(!hide);
set_dirty();
if (hide)
btn_child.focus();
else
button_on.focus();
}
void AdultToysView::on_show() {
hidden_program(!start_screen);
}
void AdultToysView::createPacket(bool regenerate) {
if (regenerate) randomizeMac();
randomChn();
if (target == 1 || 1) { // now only lovespouse supported, in the future, need to separee them
uint32_t mode = play_running ? plays[toy_packet].value : stops[toy_packet].value;
const uint8_t size = 22;
uint8_t packet[size];
uint8_t i = 0;
// 1. AD Flags
packet[i++] = 2;
packet[i++] = 0x01;
packet[i++] = 0x1A;
// 2. Manufacturer Specific
packet[i++] = 14;
packet[i++] = 0xFF;
packet[i++] = 0xFF;
packet[i++] = 0x00;
packet[i++] = 0x6D;
packet[i++] = 0xB6;
packet[i++] = 0x43;
packet[i++] = 0xCE;
packet[i++] = 0x97;
packet[i++] = 0xFE;
packet[i++] = 0x42;
packet[i++] = 0x7C;
packet[i++] = (mode >> 0x10) & 0xFF;
packet[i++] = (mode >> 0x8) & 0xFF;
packet[i++] = (mode >> 0x0) & 0xFF;
// 3. Service UUID List
packet[i++] = 3;
packet[i++] = 0x03;
packet[i++] = 0x8F;
packet[i++] = 0xAE;
std::string res = to_string_hex_array(packet, i);
memset(advertisementData, 0, sizeof(advertisementData));
std::copy(res.begin(), res.end(), advertisementData);
}
}
AdultToysView::~AdultToysView() {
stop();
}
void AdultToysView::stop() {
transmitter_model.disable();
baseband::shutdown();
}
void AdultToysView::start() {
baseband::run_image(portapack::spi_flash::image_tag_btle_tx);
transmitter_model.enable();
on_tx_progress(true);
}
void AdultToysView::reset() {
stop();
start();
}
uint8_t AdultToysView::randomize(uint8_t max) {
return static_cast<uint8_t>(rand() % max);
}
void AdultToysView::printCurrentModes() {
uint8_t max_val = play_running ? max_plays : max_stops;
auto name = play_running ? plays[toy_packet].name : stops[toy_packet].name;
std::string current = to_string_dec_uint(toy_packet + 1);
std::string max_val_str = to_string_dec_uint(max_val);
std::string result_str = current;
result_str += "/";
result_str += max_val_str;
result_str += " ";
result_str += name;
txt_selected_mode.set(result_str.c_str());
}
uint64_t AdultToysView::get_freq_by_channel_number(uint8_t channel_number) {
uint64_t freq_hz;
switch (channel_number) {
case 37:
freq_hz = 2'402'000'000ull;
break;
case 38:
freq_hz = 2'426'000'000ull;
break;
case 39:
freq_hz = 2'480'000'000ull;
break;
case 0 ... 10:
freq_hz = 2'404'000'000ull + channel_number * 2'000'000ull;
break;
case 11 ... 36:
freq_hz = 2'428'000'000ull + (channel_number - 11) * 2'000'000ull;
break;
default:
freq_hz = UINT64_MAX;
}
return freq_hz;
}
void AdultToysView::randomizeMac() {
const char hexDigits[] = "0123456789ABCDEF";
// Generate 12 random hexadecimal characters
for (int i = 0; i < 12; ++i) {
int randomIndex = rand() % 16;
mac[i] = hexDigits[randomIndex];
}
mac[12] = '\0'; // Null-terminate the string
}
void AdultToysView::randomChn() {
channel_number = 37 + std::rand() % (39 - 37 + 1);
field_frequency.set_value(get_freq_by_channel_number(channel_number));
}
void AdultToysView::on_tx_progress(const bool done) {
if (!done) return;
if (!button_onstate) return;
bool regenerate = (counter++ % 600) == 0;
if (random_running && regenerate) {
toy_packet = randomize(play_running ? max_plays : max_stops);
}
createPacket(regenerate);
printCurrentModes();
if (n_message_running) {
if (n_message_current > 0) {
n_message_current--;
message_num.set_value(n_message_current);
} else {
stop();
message_num.set_value(n_message_set);
button_on.set_text(LanguageHelper::currentMessages[LANG_START]);
button_onstate = false;
n_message_current = n_message_set;
return;
}
} // if n_message
baseband::set_btletx(channel_number, mac, advertisementData, pduType);
}
} // namespace ui::external_app::adult_toys_controller
@@ -0,0 +1,245 @@
/*
* 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.
*/
// Code from https://github.com/Next-Flip/Momentum-Apps/blob/89d493daa1ea0cb86906fa0042c41dd4edc22a6a/ble_spam/protocols/lovespouse.c#L93
// Thanks for the work of the original creators!
#ifndef __UI_ADULT_TOYS_H__
#define __UI_ADULT_TOYS_H__
#include "ui.hpp"
#include "ui_language.hpp"
#include "ui_navigation.hpp"
#include "ui_transmitter.hpp"
#include "ui_freq_field.hpp"
#include "ui_record_view.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "log_file.hpp"
#include "utility.hpp"
using namespace ui;
namespace ui::external_app::adult_toys_controller {
enum PKT_TYPE {
PKT_TYPE_INVALID_TYPE,
PKT_TYPE_RAW,
PKT_TYPE_DISCOVERY,
PKT_TYPE_IBEACON,
PKT_TYPE_ADV_IND,
PKT_TYPE_ADV_DIRECT_IND,
PKT_TYPE_ADV_NONCONN_IND,
PKT_TYPE_ADV_SCAN_IND,
PKT_TYPE_SCAN_REQ,
PKT_TYPE_SCAN_RSP,
PKT_TYPE_CONNECT_REQ,
PKT_TYPE_LL_DATA,
PKT_TYPE_LL_CONNECTION_UPDATE_REQ,
PKT_TYPE_LL_CHANNEL_MAP_REQ,
PKT_TYPE_LL_TERMINATE_IND,
PKT_TYPE_LL_ENC_REQ,
PKT_TYPE_LL_ENC_RSP,
PKT_TYPE_LL_START_ENC_REQ,
PKT_TYPE_LL_START_ENC_RSP,
PKT_TYPE_LL_UNKNOWN_RSP,
PKT_TYPE_LL_FEATURE_REQ,
PKT_TYPE_LL_FEATURE_RSP,
PKT_TYPE_LL_PAUSE_ENC_REQ,
PKT_TYPE_LL_PAUSE_ENC_RSP,
PKT_TYPE_LL_VERSION_IND,
PKT_TYPE_LL_REJECT_IND,
PKT_TYPE_NUM_PKT_TYPE
};
class AdultToysView : public ui::View {
public:
AdultToysView(NavigationView& nav);
~AdultToysView();
void focus() override;
void on_show() override;
std::string title() const override {
return "Adult Toys";
};
struct LovespouseMode {
uint32_t value;
std::string name;
};
private:
NavigationView& nav_;
TxRadioState radio_state_{
2'402'000'000 /* frequency */,
4'000'000 /* bandwidth */,
4'000'000 /* sampling rate */
};
TxFrequencyField field_frequency{
{UI_POS_X(0), UI_POS_Y(0)},
nav_};
TransmitterView2 tx_view{
{UI_POS_X(11), UI_POS_Y(0)},
/*short_ui*/ true};
app_settings::SettingsManager settings_{
"tx_adult_toys", app_settings::Mode::TX};
OptionsField options_target{
{UI_POS_X(6), UI_POS_Y(1)},
11,
{{"LoveSpouse", 1}}};
Button btn_adult{{UI_POS_X(0), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(10), UI_POS_HEIGHT(3)}, "adult"};
Button btn_child{{UI_POS_X_RIGHT(10), UI_POS_Y_BOTTOM(4), UI_POS_WIDTH(10), UI_POS_HEIGHT(3)}, "child"};
Button button_on{
{UI_POS_X(0), UI_POS_Y(3), UI_POS_WIDTH(12), UI_POS_HEIGHT(2)},
LanguageHelper::currentMessages[LANG_START]};
Button btn_mode_decrease{
{UI_POS_X(0), UI_POS_Y(13), UI_POS_WIDTH(3), UI_POS_HEIGHT(2)},
"<-"};
Button btn_mode_increase{
{UI_POS_X_RIGHT(3), UI_POS_Y(13), UI_POS_WIDTH(3), UI_POS_HEIGHT(2)},
"->"};
Text txt_selected_mode{{UI_POS_X_CENTER(22), UI_POS_Y(13.5), UI_POS_WIDTH(22), UI_POS_HEIGHT(1)}, ""};
Button btn_pcknum_inc{
{UI_POS_X(7), UI_POS_Y(9), UI_POS_WIDTH(2), UI_POS_HEIGHT(1.5)},
"+"};
Button btn_pcknum_dec{
{UI_POS_X(0), UI_POS_Y(9), UI_POS_WIDTH(2), UI_POS_HEIGHT(1.5)},
"-"};
NumberField message_num{{UI_POS_X(3), UI_POS_Y(9.2)}, 3, {0, 999}, 1, ' ', true};
Checkbox chk_mode_rnd{{UI_POS_X_RIGHT(15), UI_POS_Y(3)}, 12, "Random Msg.", false};
Checkbox chk_mode_play{{UI_POS_X_RIGHT(15), UI_POS_Y(5)}, 10, "Play Mode", false};
Checkbox chk_mode_stop{{UI_POS_X_RIGHT(15), UI_POS_Y(7)}, 10, "Stop Mode", false};
Checkbox chk_mode_ncnt{{UI_POS_X_RIGHT(15), UI_POS_Y(9)}, 7, "N Msg.", false};
Checkbox chk_mode_infinite{{UI_POS_X_RIGHT(15), UI_POS_Y(11)}, 10, "Inf. Msg.", false};
Text screen_message_1{{0, 0, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "The application is intended"};
Text screen_message_2{{0, 25, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "for controlling Love Spouse"};
Text screen_message_3{{0, 50, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "auxiliary tools/devices."};
Text screen_message_4{{0, 75, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "It is only for use by adults."};
Text screen_message_5{{0, 100, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "Are you an adult?"};
Text screen_message_6{{0, 140, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "To use the application, "};
Text screen_message_7{{0, 165, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "I assume full responsibility"};
Text screen_message_8{{0, 190, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "for the \"I do not assume"};
Text screen_message_9{{0, 215, UI_POS_MAXWIDTH, UI_POS_HEIGHT(1)}, "responsibility\"."};
Text screen_message_10{{UI_POS_X_RIGHT(16), 230, UI_POS_WIDTH(16), UI_POS_HEIGHT(1)}, "(The developer)"};
Labels labels{
{{UI_POS_X(0), UI_POS_Y(1)}, "Type:", Theme::getInstance()->fg_light->foreground}};
bool button_onstate{false};
bool play_running{false};
bool stop_running{false};
bool random_running{false};
bool n_message_running{false};
bool inf_message_running{false};
bool start_screen{false};
uint8_t target = 1; // lovespouse
char mac[13] = "010203040506";
uint8_t channel_number = 37;
char advertisementData[63] = {"03032CFE06162CFED5A59E020AB4\0"};
PKT_TYPE pduType = {PKT_TYPE_DISCOVERY};
uint8_t toy_packet = 0;
uint16_t n_message_max = 999;
uint16_t n_message_set = 0;
uint16_t n_message_current = 0;
static const size_t max_plays = 27;
static const size_t max_stops = 3;
uint16_t counter = 599;
void createPacket(bool regenerate);
void start();
void stop();
void reset();
void printCurrentModes();
void on_tx_progress(const bool done);
void hidden_program(bool hide);
void randomizeMac();
void randomChn();
uint8_t randomize(uint8_t max);
uint64_t get_freq_by_channel_number(uint8_t channel_number);
MessageHandlerRegistration message_handler_tx_progress{
Message::ID::TXProgress,
[this](const Message* const p) {
const auto message = *reinterpret_cast<const TXProgressMessage*>(p);
this->on_tx_progress(message.done);
}};
LovespouseMode plays[max_plays] = {
{0xE49C6C, "Classic 1"},
{0xE7075E, "Classic 2"},
{0xE68E4F, "Classic 3"},
{0xE1313B, "Classic 4"},
{0xE0B82A, "Classic 5"},
{0xE32318, "Classic 6"},
{0xE2AA09, "Classic 7"},
{0xED5DF1, "Classic 8"},
{0xECD4E0, "Classic 9"},
{0xD41F5D, "Independent 1-1"},
{0xD7846F, "Independent 1-2"},
{0xD60D7E, "Independent 1-3"},
{0xD1B20A, "Independent 1-4"},
{0xD0B31B, "Independent 1-5"},
{0xD3A029, "Independent 1-6"},
{0xD22938, "Independent 1-7"},
{0xDDDEC0, "Independent 1-8"},
{0xDC57D1, "Independent 1-9"},
{0xA4982E, "Independent 2-1"},
{0xA7031C, "Independent 2-2"},
{0xA68A0D, "Independent 2-3"},
{0xA13579, "Independent 2-4"},
{0xA0BC68, "Independent 2-5"},
{0xA3275A, "Independent 2-6"},
{0xA2AE4B, "Independent 2-7"},
{0xAD59B3, "Independent 2-8"},
{0xACD0A2, "Independent 2-9"},
};
LovespouseMode stops[max_stops] = {
{0xE5157D, "Classic Stop"},
{0xD5964C, "Independent 1 Stop"},
{0xA5113F, "Independent 2 Stop"},
};
};
}; // namespace ui::external_app::adult_toys_controller
#endif // ui_adult_toys_controller_hpp
@@ -34,7 +34,7 @@ using namespace portapack;
#include <cmath>
#include <array>
namespace ui {
namespace ui::external_app::analogtv {
namespace tv {
/* TimeScopeView******************************************************/
@@ -235,4 +235,4 @@ void TVWidget::on_audio_spectrum() {
}
} /* namespace tv */
} /* namespace ui */
} // namespace ui::external_app::analogtv
@@ -33,7 +33,7 @@
#include <cstdint>
#include <cstddef>
namespace ui {
namespace ui::external_app::analogtv {
namespace tv {
class TimeScopeView : public View {
@@ -167,6 +167,6 @@ class TVWidget : public View {
};
} /* namespace tv */
} /* namespace ui */
} // namespace ui::external_app::analogtv
#endif /*__UI_TV_H__*/
+75 -127
View File
@@ -24,25 +24,25 @@ constexpr uint32_t BLUE_TEAM_ADDRESS = BATTLESHIP_BASE_ADDRESS + 2;
BattleshipView::BattleshipView(NavigationView& nav)
: nav_{nav} {
CELL_SIZE = screen_width / GRID_SIZE;
baseband::run_image(portapack::spi_flash::image_tag_pocsag2);
add_children({&text_title, &text_subtitle,
&rect_radio_settings, &label_radio, &button_frequency,
//&rect_radio_settings, &rect_audio_settings, &rect_team_selection,
&label_radio, &button_frequency,
&label_rf_amp, &checkbox_rf_amp,
&label_lna, &field_lna,
&label_vga, &field_vga,
&label_tx_gain, &field_tx_gain,
&rect_audio_settings, &label_audio,
&label_audio,
&checkbox_sound, &label_volume, &field_volume,
&rect_team_selection, &label_team,
&label_team,
&button_red_team, &button_blue_team,
&rssi, &text_status, &text_score,
&rssi,
&button_rotate, &button_place, &button_fire, &button_menu});
// Hide in-game elements
rssi.hidden(true);
text_status.hidden(true);
text_score.hidden(true);
button_rotate.hidden(true);
button_place.hidden(true);
button_fire.hidden(true);
@@ -151,8 +151,8 @@ BattleshipView::BattleshipView(NavigationView& nav)
field_tx_gain.set_parent_rect({185, 118, 32, 16});
checkbox_sound.set_parent_rect({17, 187, 80, 24});
field_volume.set_parent_rect({165, 187, 32, 16});
button_red_team.set_parent_rect({25, 242, 85, 45});
button_blue_team.set_parent_rect({130, 242, 85, 45});
// button_red_team.set_parent_rect({25, 242, 85, 45});
// button_blue_team.set_parent_rect({130, 242, 85, 45});
// Make menu elements focusable
button_frequency.set_focusable(true);
@@ -191,11 +191,42 @@ void BattleshipView::init_game() {
enemy_grid[y][x] = CellState::EMPTY;
}
}
setup_ships();
update_score();
}
void BattleshipView::show_hide_menu(bool menu_vis) {
text_title.hidden(!menu_vis);
text_subtitle.hidden(!menu_vis);
// rect_radio_settings.hidden(!menu_vis); rect_audio_settings.hidden(!menu_vis); rect_team_selection.hidden(!menu_vis);
label_radio.hidden(!menu_vis);
button_frequency.hidden(!menu_vis);
label_rf_amp.hidden(!menu_vis);
checkbox_rf_amp.hidden(!menu_vis);
label_lna.hidden(!menu_vis);
field_lna.hidden(!menu_vis);
label_vga.hidden(!menu_vis);
field_vga.hidden(!menu_vis);
label_tx_gain.hidden(!menu_vis);
field_tx_gain.hidden(!menu_vis);
label_audio.hidden(!menu_vis);
checkbox_sound.hidden(!menu_vis);
label_volume.hidden(!menu_vis);
field_volume.hidden(!menu_vis);
label_team.hidden(!menu_vis);
button_red_team.hidden(!menu_vis);
button_blue_team.hidden(!menu_vis);
rssi.hidden(menu_vis);
button_rotate.hidden(menu_vis);
button_place.hidden(menu_vis);
button_menu.hidden(menu_vis);
// button_rotate.set_focusable(false); //no need, since can't focus on hidden
// button_place.set_focusable(false);
// button_menu.set_focusable(false);
set_dirty();
}
void BattleshipView::reset_game() {
transmitter_model.disable();
receiver_model.disable();
@@ -221,50 +252,7 @@ void BattleshipView::reset_game() {
update_score();
// Toggle visibility
bool menu_vis = true;
bool game_vis = false;
text_title.hidden(!menu_vis);
text_subtitle.hidden(!menu_vis);
rect_radio_settings.hidden(!menu_vis);
label_radio.hidden(!menu_vis);
button_frequency.hidden(!menu_vis);
label_rf_amp.hidden(!menu_vis);
checkbox_rf_amp.hidden(!menu_vis);
label_lna.hidden(!menu_vis);
field_lna.hidden(!menu_vis);
label_vga.hidden(!menu_vis);
field_vga.hidden(!menu_vis);
label_tx_gain.hidden(!menu_vis);
field_tx_gain.hidden(!menu_vis);
rect_audio_settings.hidden(!menu_vis);
label_audio.hidden(!menu_vis);
checkbox_sound.hidden(!menu_vis);
label_volume.hidden(!menu_vis);
field_volume.hidden(!menu_vis);
rect_team_selection.hidden(!menu_vis);
label_team.hidden(!menu_vis);
button_red_team.hidden(!menu_vis);
button_blue_team.hidden(!menu_vis);
rssi.hidden(!game_vis);
text_status.hidden(!game_vis);
text_score.hidden(!game_vis);
button_rotate.hidden(!game_vis);
button_place.hidden(!game_vis);
button_fire.hidden(!game_vis);
button_menu.hidden(!game_vis);
// Restore focusability
button_frequency.set_focusable(menu_vis);
checkbox_rf_amp.set_focusable(menu_vis);
field_lna.set_focusable(menu_vis);
field_vga.set_focusable(menu_vis);
field_tx_gain.set_focusable(menu_vis);
checkbox_sound.set_focusable(menu_vis);
field_volume.set_focusable(menu_vis);
button_red_team.set_focusable(menu_vis);
button_blue_team.set_focusable(menu_vis);
show_hide_menu(true);
button_frequency.focus();
set_dirty();
@@ -283,45 +271,10 @@ void BattleshipView::start_team(bool red) {
game_state = GameState::PLACING_SHIPS;
// Toggle visibility
bool menu_vis = false;
bool game_vis = true;
text_title.hidden(!menu_vis);
text_subtitle.hidden(!menu_vis);
rect_radio_settings.hidden(!menu_vis);
label_radio.hidden(!menu_vis);
button_frequency.hidden(!menu_vis);
label_rf_amp.hidden(!menu_vis);
checkbox_rf_amp.hidden(!menu_vis);
label_lna.hidden(!menu_vis);
field_lna.hidden(!menu_vis);
label_vga.hidden(!menu_vis);
field_vga.hidden(!menu_vis);
label_tx_gain.hidden(!menu_vis);
field_tx_gain.hidden(!menu_vis);
rect_audio_settings.hidden(!menu_vis);
label_audio.hidden(!menu_vis);
checkbox_sound.hidden(!menu_vis);
label_volume.hidden(!menu_vis);
field_volume.hidden(!menu_vis);
rect_team_selection.hidden(!menu_vis);
label_team.hidden(!menu_vis);
button_red_team.hidden(!menu_vis);
button_blue_team.hidden(!menu_vis);
rssi.hidden(!game_vis);
text_status.hidden(true);
text_score.hidden(true);
button_rotate.hidden(false);
button_place.hidden(false);
button_menu.hidden(false);
show_hide_menu(false);
current_status = "Place carrier (5)";
button_rotate.set_focusable(false);
button_place.set_focusable(false);
button_menu.set_focusable(false);
focus();
is_transmitting = true;
configure_radio_rx();
@@ -382,7 +335,7 @@ void BattleshipView::configure_radio_rx() {
}
void BattleshipView::paint(Painter& painter) {
painter.fill_rectangle({0, 0, 240, 320}, Color::black());
painter.fill_rectangle({0, 0, UI_POS_MAXWIDTH, UI_POS_MAXHEIGHT}, Color::black());
if (game_state == GameState::MENU) {
draw_menu_screen(painter);
@@ -426,24 +379,21 @@ void BattleshipView::paint(Painter& painter) {
}
Color team_color = is_red_team ? Color::red() : Color::blue();
painter.fill_rectangle({0, 5, 240, 16}, team_color);
painter.fill_rectangle({0, 5, screen_width, 16}, team_color);
auto style_white = Style{
.font = ui::font::fixed_8x16,
.background = team_color,
.foreground = Color::white()};
painter.draw_string({85, 5}, style_white, is_red_team ? "RED TEAM" : "BLUE TEAM");
painter.draw_string({UI_POS_X_CENTER(9), 5}, style_white, is_red_team ? "RED TEAM" : "BLUE TEAM");
auto style_status = Style{
.font = ui::font::fixed_8x16,
.background = Color::black(),
.foreground = Color::white()};
painter.fill_rectangle({0, 21, 240, 16}, Color::black());
painter.draw_string({10, 21}, style_status, current_status);
if (game_state != GameState::MENU) {
painter.draw_string({170, 21}, style_status, current_score);
}
painter.fill_rectangle({0, 21, screen_width, 16}, Color::black());
painter.draw_string({5, 21}, style_status, current_status);
painter.draw_string({170, 21}, style_status, current_score);
if (game_state == GameState::PLACING_SHIPS) {
draw_grid(painter, GRID_OFFSET_X, GRID_OFFSET_Y + 5, my_grid, true);
@@ -452,35 +402,35 @@ void BattleshipView::paint(Painter& painter) {
}
} else if (game_state == GameState::MY_TURN) {
draw_grid(painter, GRID_OFFSET_X, GRID_OFFSET_Y + 5, enemy_grid, false, true);
painter.draw_string({10, GRID_OFFSET_Y + GRID_SIZE * CELL_SIZE + 10}, style_status,
"Enemy ships: " + to_string_dec_uint(enemy_ships_remaining));
painter.draw_string({0, GRID_OFFSET_Y + GRID_SIZE * CELL_SIZE + 10}, style_status,
"Enemy: " + to_string_dec_uint(enemy_ships_remaining));
} else if (game_state == GameState::OPPONENT_TURN || game_state == GameState::WAITING_FOR_OPPONENT) {
draw_grid(painter, GRID_OFFSET_X, GRID_OFFSET_Y + 5, my_grid, true);
painter.draw_string({10, GRID_OFFSET_Y + GRID_SIZE * CELL_SIZE + 10}, style_status,
"Your ships: " + to_string_dec_uint(ships_remaining));
painter.draw_string({0, GRID_OFFSET_Y + GRID_SIZE * CELL_SIZE + 10}, style_status,
"You: " + to_string_dec_uint(ships_remaining));
} else if (game_state == GameState::GAME_OVER) {
painter.draw_string({50, 150}, style_status, "Game Over!");
painter.draw_string({UI_POS_X_CENTER(11), 150}, style_status, "Game Over!");
painter.draw_string({30, 170}, style_status, current_status);
}
}
void BattleshipView::draw_menu_screen(Painter& painter) {
painter.draw_hline({12, 38}, 216, Color::dark_cyan());
painter.draw_hline({12, 20 + 16}, screen_width - 24, Color::dark_cyan());
painter.fill_rectangle({13, 41, 214, 116}, Color::dark_grey());
painter.draw_hline({12, 40}, 216, Color::cyan());
painter.draw_hline({12, 157}, 216, Color::cyan());
painter.fill_rectangle({13, 59, screen_width - 26, 116}, Color::dark_grey());
painter.draw_hline({12, 58}, screen_width - 24, Color::cyan());
painter.draw_hline({12, 157}, screen_width - 24, Color::cyan());
painter.fill_rectangle({13, 165, 214, 43}, Color::dark_grey());
painter.draw_hline({12, 164}, 216, Color::cyan());
painter.draw_hline({12, 208}, 216, Color::cyan());
painter.fill_rectangle({13, 165, screen_width - 24, 57}, Color::dark_grey());
painter.draw_hline({12, 164}, screen_width - 24, Color::cyan());
painter.draw_hline({12, 223}, screen_width - 24, Color::cyan());
painter.fill_rectangle({13, 218, 214, 73}, Color::dark_grey());
painter.draw_hline({12, 217}, 216, Color::cyan());
painter.draw_hline({12, 291}, 216, Color::cyan());
painter.fill_rectangle({13, 232, screen_width - 26, 67}, Color::dark_grey());
painter.draw_hline({12, 232}, screen_width - 24, Color::cyan());
painter.draw_hline({12, 300}, screen_width - 24, Color::cyan());
// Radio status indicator
Point indicator_pos{220, 53};
Point indicator_pos{UI_POS_MAXWIDTH - 20, 59};
if (is_transmitting) {
painter.fill_rectangle({indicator_pos, {6, 6}}, Color::red());
painter.draw_rectangle({indicator_pos.x() - 1, indicator_pos.y() - 1, 8, 8}, Color::light_grey());
@@ -490,7 +440,7 @@ void BattleshipView::draw_menu_screen(Painter& painter) {
}
}
void BattleshipView::draw_grid(Painter& painter, uint8_t grid_x, uint8_t grid_y, const std::array<std::array<CellState, GRID_SIZE>, GRID_SIZE>& grid, bool show_ships, bool is_offense_grid) {
void BattleshipView::draw_grid(Painter& painter, uint16_t grid_x, uint16_t grid_y, const std::array<std::array<CellState, GRID_SIZE>, GRID_SIZE>& grid, bool show_ships, bool is_offense_grid) {
painter.fill_rectangle({grid_x, grid_y, GRID_SIZE * CELL_SIZE, GRID_SIZE * CELL_SIZE},
Color::dark_blue());
@@ -501,26 +451,24 @@ void BattleshipView::draw_grid(Painter& painter, uint8_t grid_x, uint8_t grid_y,
GRID_SIZE * CELL_SIZE, Color::grey());
}
for (uint8_t y = 0; y < GRID_SIZE; y++) {
for (uint8_t x = 0; x < GRID_SIZE; x++) {
draw_cell(painter, grid_x + x * CELL_SIZE + 1, grid_y + y * CELL_SIZE + 1,
grid[y][x], show_ships, is_offense_grid,
is_cursor_at(x, y, is_offense_grid));
for (uint16_t y = 0; y < GRID_SIZE; y++) {
for (uint16_t x = 0; x < GRID_SIZE; x++) {
draw_cell(painter, grid_x + x * CELL_SIZE + 1, grid_y + y * CELL_SIZE + 1, grid[y][x], show_ships, is_offense_grid, is_cursor_at(x, y, is_offense_grid));
}
}
}
void BattleshipView::draw_cell(Painter& painter, uint8_t cell_x, uint8_t cell_y, CellState state, bool show_ships, bool is_offense_grid, bool is_cursor) {
void BattleshipView::draw_cell(Painter& painter, uint16_t cell_x, uint16_t cell_y, CellState state, bool show_ships, bool is_offense_grid, bool is_cursor) {
Color cell_color = Color::dark_blue();
bool should_fill = false;
if (game_state == GameState::PLACING_SHIPS && !is_offense_grid && current_ship_index < 5) {
uint8_t ship_size = my_ships[current_ship_index].size();
for (uint8_t i = 0; i < ship_size; i++) {
uint8_t preview_x = placing_horizontal ? cursor_x + i : cursor_x;
uint8_t preview_y = placing_horizontal ? cursor_y : cursor_y + i;
uint8_t grid_x = (cell_x - 1) / CELL_SIZE;
uint8_t grid_y = (cell_y - GRID_OFFSET_Y - 6) / CELL_SIZE;
uint16_t preview_x = placing_horizontal ? cursor_x + i : cursor_x;
uint16_t preview_y = placing_horizontal ? cursor_y : cursor_y + i;
uint16_t grid_x = (cell_x - 1) / CELL_SIZE;
uint16_t grid_y = (cell_y - GRID_OFFSET_Y - 6) / CELL_SIZE;
if (grid_x == preview_x && grid_y == preview_y && preview_x < GRID_SIZE && preview_y < GRID_SIZE) {
return;
}
@@ -597,8 +545,8 @@ void BattleshipView::draw_ship_preview(Painter& painter) {
uint8_t y = placing_horizontal ? cursor_y : cursor_y + i;
if (x < GRID_SIZE && y < GRID_SIZE) {
uint8_t cell_x = GRID_OFFSET_X + x * CELL_SIZE + 1;
uint8_t cell_y = GRID_OFFSET_Y + 5 + y * CELL_SIZE + 1;
uint16_t cell_x = GRID_OFFSET_X + x * CELL_SIZE + 1;
uint16_t cell_y = GRID_OFFSET_Y + 5 + y * CELL_SIZE + 1;
Color preview_color = can_place ? Color::green() : Color::red();
+26 -25
View File
@@ -23,12 +23,9 @@
#include <array>
namespace ui::external_app::battleship {
#define GRID_SIZE 10
constexpr uint8_t GRID_SIZE = 10;
constexpr uint8_t CELL_SIZE = 24;
constexpr uint8_t GRID_OFFSET_X = 0;
constexpr uint8_t GRID_OFFSET_Y = 32;
namespace ui::external_app::battleship {
enum class ShipType : uint8_t {
CARRIER = 5,
@@ -103,6 +100,10 @@ class BattleshipView : public View {
private:
NavigationView& nav_;
uint16_t CELL_SIZE = 24;
uint16_t GRID_OFFSET_X = 0;
uint16_t GRID_OFFSET_Y = 32;
RxRadioState rx_radio_state_{
433920000 /* frequency */,
1750000 /* bandwidth */,
@@ -163,11 +164,11 @@ class BattleshipView : public View {
uint32_t last_address{0};
// UI Elements - Menu/Settings Screen
Text text_title{{60, 2, 120, 24}, "BATTLESHIP"};
Text text_subtitle{{40, 20, 160, 16}, "Naval Combat Game"};
Text text_title{{UI_POS_X_CENTER(11), 2, UI_POS_WIDTH(11), 16}, "BATTLESHIP"};
Text text_subtitle{{UI_POS_X_CENTER(18), 24, UI_POS_WIDTH(18), 16}, "Naval Combat Game"};
Rectangle rect_radio_settings{{12, 40, 216, 118}, Color::dark_grey()};
Text label_radio{{17, 45, 100, 16}, "RADIO SETUP"};
// Rectangle rect_radio_settings{{12, 40, 216, 118}, Color::dark_grey()};
Text label_radio{{UI_POS_X_CENTER(12), 45, UI_POS_WIDTH(12), 16}, "RADIO SETUP"};
ButtonWithEncoder button_frequency{{17, 65, 11 * 8, 20}, ""};
// Radio controls
@@ -183,25 +184,24 @@ class BattleshipView : public View {
Text label_tx_gain{{155, 118, 25, 16}, "TX:"};
NumberField field_tx_gain{{185, 118}, 2, {0, 47}, 8, ' '};
Rectangle rect_audio_settings{{12, 164, 216, 45}, Color::dark_grey()};
Text label_audio{{17, 169, 80, 16}, "AUDIO"};
Checkbox checkbox_sound{{17, 187}, 8, "Sound On", true};
// Rectangle rect_audio_settings{{12, 164, 216, 45}, Color::dark_grey()};
Text label_audio{{UI_POS_X_CENTER(6), 155, UI_POS_WIDTH(6), 16}, "AUDIO"};
Checkbox checkbox_sound{{17, 177}, 8, "Sound On", true};
Text label_volume{{110, 187, 50, 16}, "Volume:"};
AudioVolumeField field_volume{{165, 187}};
AudioVolumeField field_volume{{165, 177}};
Rectangle rect_team_selection{{12, 217, 216, 75}, Color::dark_grey()};
Text label_team{{17, 222, 110, 16}, "SELECT TEAM"};
Button button_red_team{{25, 242, 85, 45}, "RED\nTEAM"};
Button button_blue_team{{130, 242, 85, 45}, "BLUE\nTEAM"};
// Rectangle rect_team_selection{{12, 217, 216, 75}, Color::dark_grey()};
Text label_team{{17, 220, 8 * 12, 16}, "SELECT TEAM"};
Button button_red_team{{UI_POS_X_CENTER(10) - UI_POS_WIDTH(7), 237, UI_POS_WIDTH(10), 45}, "RED\nTEAM"};
Button button_blue_team{{UI_POS_X_CENTER(10) + UI_POS_WIDTH(7), 237, UI_POS_WIDTH(10), 45}, "BLUE\nTEAM"};
// In-game UI elements
RSSI rssi{{21 * 8, 0, 6 * 8, 4}};
Text text_status{{10, 16, 220, 16}, ""};
RSSI rssi{{UI_POS_X_RIGHT(6), 0, 6 * 8, 4}};
Text text_score{{170, 16, 60, 16}, ""};
Button button_rotate{{10, 265, 65, 32}, "Rotate"};
Button button_place{{82, 265, 65, 32}, "Place"};
Button button_fire{{82, 265, 65, 32}, "Fire!"};
Button button_menu{{155, 265, 65, 32}, "Menu"};
Button button_rotate{{5, UI_POS_Y_BOTTOM(3), 65, 32}, "Rotate"};
Button button_place{{UI_POS_X_CENTER(6), UI_POS_Y_BOTTOM(3), 65, 32}, "Place"};
Button button_fire{{UI_POS_X_RIGHT(17), UI_POS_Y_BOTTOM(3), 65, 32}, "Fire!"};
Button button_menu{{UI_POS_X_RIGHT(8), UI_POS_Y_BOTTOM(3), 65, 32}, "Menu"};
// Methods
void init_game();
@@ -209,8 +209,8 @@ class BattleshipView : public View {
void start_team(bool red);
void setup_ships();
void draw_menu_screen(Painter& painter);
void draw_grid(Painter& painter, uint8_t grid_x, uint8_t grid_y, const std::array<std::array<CellState, GRID_SIZE>, GRID_SIZE>& grid, bool show_ships, bool is_offense_grid = false);
void draw_cell(Painter& painter, uint8_t cell_x, uint8_t cell_y, CellState state, bool show_ships, bool is_offense_grid, bool is_cursor);
void draw_grid(Painter& painter, uint16_t grid_x, uint16_t grid_y, const std::array<std::array<CellState, GRID_SIZE>, GRID_SIZE>& grid, bool show_ships, bool is_offense_grid = false);
void draw_cell(Painter& painter, uint16_t cell_x, uint16_t cell_y, CellState state, bool show_ships, bool is_offense_grid, bool is_cursor);
void draw_ship_preview(Painter& painter);
void place_ship();
bool can_place_ship(uint8_t x, uint8_t y, uint8_t size, bool horizontal);
@@ -218,6 +218,7 @@ class BattleshipView : public View {
void process_shot(uint8_t x, uint8_t y);
void update_score();
bool is_cursor_at(uint8_t x, uint8_t y, bool is_offense_grid);
void show_hide_menu(bool menu_vis);
void send_message(const GameMessage& msg);
void process_message(const std::string& message);
-1
View File
@@ -21,7 +21,6 @@
*/
#include "bht.hpp"
#include "portapack_persistent_memory.hpp"
namespace ui::external_app::bht_tx {
+1 -1
View File
@@ -207,7 +207,7 @@ class BHTView : public View {
"Scan"};
Checkbox checkbox_flashing{
{16 * 8, 25 * 8},
{UI_POS_X(16), 25 * 8},
8,
"Flashing"};
NumberField field_speed{
+12 -12
View File
@@ -20,13 +20,13 @@ void initialize_app(ui::NavigationView& nav) {
extern "C" {
__attribute__((section(".external_app.app_breakout.application_information"), used)) application_information_t _application_information_breakout = {
(uint8_t*)0x00000000,
ui::external_app::breakout::initialize_app,
CURRENT_HEADER_VERSION,
VERSION_MD5,
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::breakout::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
"Breakout",
{
/*.app_name = */ "Breakout",
/*.bitmap_data = */ {
0x00,
0x00,
0x7F,
@@ -60,11 +60,11 @@ __attribute__((section(".external_app.app_breakout.application_information"), us
0xF7,
0xF7,
},
ui::Color::green().v,
app_location_t::GAMES,
-1,
/*.icon_color = */ ui::Color::green().v,
/*.menu_location = */ app_location_t::GAMES,
/*.desired_menu_position = */ -1,
{0, 0, 0, 0},
0x00000000,
/*.m4_app_tag = */ {'P', 'A', 'B', 'P'}, // This is the audio beep baseband tag!
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
} // namespace ui::external_app::breakout
}
+279 -10
View File
@@ -7,6 +7,12 @@
*/
#include "ui_breakout.hpp"
#include "baseband_api.hpp"
#include "audio.hpp"
#include "portapack.hpp"
#include "portapack_persistent_memory.hpp"
using namespace portapack;
namespace ui::external_app::breakout {
@@ -92,6 +98,37 @@ void BreakoutView::init_game() {
game_state = STATE_MENU;
menu_blink_state = true;
menu_blink_counter = 0;
// Play startup sound
if (sound_enabled) {
baseband::request_audio_beep(262, 24000, 150); // C4 -
chThdSleepMilliseconds(200);
baseband::request_audio_beep(262, 24000, 150); // C4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(392, 24000, 150); // G4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(392, 24000, 150); // G4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(440, 24000, 150); // A4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(440, 24000, 150); // A4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(392, 24000, 300); // G4
chThdSleepMilliseconds(350);
baseband::request_audio_beep(349, 24000, 150); // F4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(349, 24000, 150); // F4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(330, 24000, 150); // E4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(330, 24000, 150); // E4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(294, 24000, 150); // D4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(294, 24000, 150); // D4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(262, 24000, 400); // C4
}
}
void BreakoutView::init_level() {
@@ -126,6 +163,34 @@ void BreakoutView::draw_screen() {
draw_level();
}
void BreakoutView::draw_menu_volume_bar() {
// Clear the entire volume area first to handle bar shrinking
painter.fill_rectangle({40, 259, 220, 40}, Color::black());
// Draw volume label
auto style = *ui::Theme::getInstance()->fg_light;
painter.draw_string({40, 260}, style, "Volume:");
// Draw volume bar background
painter.draw_rectangle({100, 259, 102, 10}, Color::grey());
// Draw volume level
int bar_width = (volume_level * 100) / 99;
if (bar_width > 0) {
painter.fill_rectangle({101, 260, bar_width, 8}, Color::green());
}
// Draw percentage
painter.draw_string({210, 260}, style, std::to_string(volume_level) + "%");
// Draw sound status
if (sound_enabled) {
painter.draw_string({UI_POS_X_CENTER(11), 280}, *ui::Theme::getInstance()->fg_green, "Sound: ON");
} else {
painter.draw_string({UI_POS_X_CENTER(11), 280}, *ui::Theme::getInstance()->fg_red, "Sound: OFF");
}
}
void BreakoutView::draw_borders() {
rect(0, GAME_AREA_TOP - 1, SCREEN_WIDTH, GAME_AREA_TOP, COLOR_BORDER);
}
@@ -166,6 +231,22 @@ void BreakoutView::draw_level() {
painter.draw_string({80, 30}, style, "Level: " + std::to_string(level));
}
void BreakoutView::adjust_volume(int delta) {
volume_level += delta;
if (volume_level < 0) volume_level = 0;
if (volume_level > 99) volume_level = 99;
// Update the actual audio volume using decibel conversion
// Map 0-99 to roughly -60dB to 0dB range
int db = (volume_level - 99) * 60 / 99; // Maps 0->-60dB, 99->0dB
audio::headphone::set_volume(volume_t::decibel(db));
// If we're in the menu, redraw the volume bar
if (game_state == STATE_MENU) {
draw_menu_volume_bar();
}
}
void BreakoutView::move_paddle_left() {
if (paddle_x > 0) {
fillrect(paddle_x, PADDLE_Y, paddle_x + PADDLE_WIDTH, PADDLE_Y + PADDLE_HEIGHT, COLOR_BACKGROUND);
@@ -231,19 +312,23 @@ void BreakoutView::update_game() {
if (ball_x < 0) {
ball_x = 0;
ball_dx = -ball_dx;
play_wall_hit();
} else if (ball_x > SCREEN_WIDTH - BALL_SIZE) {
ball_x = SCREEN_WIDTH - BALL_SIZE;
ball_dx = -ball_dx;
play_wall_hit();
}
if (ball_y < GAME_AREA_TOP) {
ball_y = GAME_AREA_TOP;
ball_dy = -ball_dy;
play_wall_hit();
}
// Bottom edge - lose life
if (ball_y > GAME_AREA_BOTTOM) {
lives--;
play_death_sound(); // Play death sound
draw_lives();
if (lives <= 0) {
handle_game_over();
@@ -262,6 +347,8 @@ void BreakoutView::update_game() {
ball_y = PADDLE_Y - BALL_SIZE;
ball_dy = -ball_dy;
play_paddle_hit();
// Add some angle based on hit position
float hit_position = (ball_x + (BALL_SIZE / 2)) - paddle_x;
float angle = (hit_position / PADDLE_WIDTH) - 0.5f;
@@ -301,6 +388,8 @@ bool BreakoutView::check_brick_collision(int row, int col) {
score += (5 - row) * 10;
draw_score();
play_brick_hit();
ball_dy = -ball_dy;
return true;
}
@@ -314,6 +403,8 @@ bool BreakoutView::check_level_complete() {
void BreakoutView::next_level() {
level++;
play_level_complete();
chThdSleepMilliseconds(500); // Give time for sound to play
init_level();
draw_screen();
}
@@ -322,9 +413,11 @@ void BreakoutView::handle_game_over() {
game_state = STATE_GAME_OVER;
gameover_blink_state = true;
gameover_blink_counter = 0;
play_game_over();
}
void BreakoutView::show_menu() {
// Only draw the static parts once
if (menu_blink_counter == 0) {
cls();
background(COLOR_BACKGROUND);
@@ -338,23 +431,30 @@ void BreakoutView::show_menu() {
painter.draw_string({UI_POS_X_CENTER(20), 130}, style_cyan, "ROTARY: MOVE PADDLE");
painter.draw_string({UI_POS_X_CENTER(21), 160}, style_cyan, "SELECT: START/LAUNCH");
painter.draw_string({UI_POS_X_CENTER(25), 190}, style_blue, "========================");
// Volume adjustment instructions
painter.draw_string({UI_POS_X_CENTER(24), 220}, style_cyan, "Press UP/DOWN for Volume");
// Draw volume control at bottom
draw_menu_volume_bar();
}
auto style_red = *ui::Theme::getInstance()->fg_red;
// Only flash the "PRESS SELECT" text
if (++menu_blink_counter >= 30) {
menu_blink_counter = 0;
menu_blink_counter = 1; // Keep it at 1 so we don't redraw everything
menu_blink_state = !menu_blink_state;
painter.fill_rectangle({UI_POS_X_CENTER(17), 228, 128, 20}, Color::black());
auto style_red = *ui::Theme::getInstance()->fg_red;
painter.fill_rectangle({UI_POS_X_CENTER(17), 238, 128, 20}, Color::black());
if (menu_blink_state) {
painter.draw_string({UI_POS_X_CENTER(17), 230}, style_red, "* PRESS SELECT *");
painter.draw_string({UI_POS_X_CENTER(17), 240}, style_red, "* PRESS SELECT *");
}
}
}
void BreakoutView::show_game_over() {
// Only draw the static parts once
if (gameover_blink_counter == 0) {
cls();
background(COLOR_BACKGROUND);
@@ -366,12 +466,12 @@ void BreakoutView::show_game_over() {
painter.draw_string({UI_POS_X_CENTER(11), 150}, style_yellow, "SCORE: " + std::to_string(score));
}
auto style_green = *ui::Theme::getInstance()->fg_green;
// Only flash the "PRESS SELECT" text
if (++gameover_blink_counter >= 30) {
gameover_blink_counter = 0;
gameover_blink_counter = 1; // Keep it at 1 so we don't redraw everything
gameover_blink_state = !gameover_blink_state;
auto style_green = *ui::Theme::getInstance()->fg_green;
painter.fill_rectangle({UI_POS_X_CENTER(13), 198, 96, 20}, Color::black());
if (gameover_blink_state) {
@@ -385,17 +485,169 @@ void BreakoutView::reset_game() {
score = 0;
lives = 3;
game_state = STATE_PLAYING;
dummy.focus();
init_level();
draw_screen();
}
// Sound effect implementations with timing control
void BreakoutView::play_paddle_hit() {
if (sound_enabled) {
uint32_t current_time = chTimeNow();
if (current_time - last_sound_time >= min_sound_interval) {
baseband::request_beep_stop(); // Stop any previous sound
chThdSleepMilliseconds(5); // Small delay
baseband::request_audio_beep(440, 24000, 40); // 440Hz A4, 40ms
last_sound_time = current_time;
}
}
}
void BreakoutView::play_brick_hit() {
if (sound_enabled) {
uint32_t current_time = chTimeNow();
if (current_time - last_sound_time >= min_sound_interval) {
baseband::request_beep_stop(); // Stop any previous sound
chThdSleepMilliseconds(5); // Small delay
// Higher pitch that varies with remaining bricks
uint32_t freq = 880 + ((25 - brick_count) * 20); // Gets higher as bricks are destroyed
baseband::request_audio_beep(freq, 24000, 30);
last_sound_time = current_time;
}
}
}
void BreakoutView::play_wall_hit() {
if (sound_enabled) {
uint32_t current_time = chTimeNow();
if (current_time - last_sound_time >= min_sound_interval) {
baseband::request_beep_stop(); // Stop any previous sound
chThdSleepMilliseconds(5); // Small delay
baseband::request_audio_beep(220, 24000, 120); // 220Hz A3, 120ms
last_sound_time = current_time;
}
}
}
void BreakoutView::play_death_sound() {
if (sound_enabled) {
baseband::request_audio_beep(493, 24000, 150); // B4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(466, 24000, 150); // Bb4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(440, 24000, 150); // A4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(415, 24000, 150); // Ab4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(392, 24000, 150); // G4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(369, 24000, 150); // Gb4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(349, 24000, 150); // F4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(329, 24000, 150); // E4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(293, 24000, 150); // D4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(261, 24000, 150); // C4
chThdSleepMilliseconds(180);
baseband::request_audio_beep(196, 24000, 200); // G3
chThdSleepMilliseconds(230);
baseband::request_audio_beep(130, 24000, 300); // C3
}
}
void BreakoutView::play_game_over() {
if (sound_enabled) {
// First phrase
baseband::request_audio_beep(392, 24000, 300); // G4
chThdSleepMilliseconds(350);
baseband::request_audio_beep(392, 24000, 150); // G4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(392, 24000, 150); // G4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(311, 24000, 500); // Eb4 - long
chThdSleepMilliseconds(600);
// Second phrase
baseband::request_audio_beep(349, 24000, 300); // F4
chThdSleepMilliseconds(350);
baseband::request_audio_beep(349, 24000, 150); // F4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(349, 24000, 150); // F4
chThdSleepMilliseconds(200);
baseband::request_audio_beep(294, 24000, 500); // D4 - long
chThdSleepMilliseconds(600);
// Final phrase - slower and more dramatic
baseband::request_audio_beep(262, 24000, 200); // C4
chThdSleepMilliseconds(250);
baseband::request_audio_beep(247, 24000, 200); // B3
chThdSleepMilliseconds(250);
baseband::request_audio_beep(233, 24000, 200); // Bb3
chThdSleepMilliseconds(250);
baseband::request_audio_beep(220, 24000, 200); // A3
chThdSleepMilliseconds(250);
baseband::request_audio_beep(196, 24000, 200); // G3
chThdSleepMilliseconds(250);
baseband::request_audio_beep(175, 24000, 200); // F3
chThdSleepMilliseconds(250);
baseband::request_audio_beep(131, 24000, 600); // C3
}
}
void BreakoutView::play_level_complete() {
if (sound_enabled) {
baseband::request_beep_stop(); // Stop any previous sound
chThdSleepMilliseconds(10);
baseband::request_audio_beep(1047, 24000, 300); // 1047Hz C6, 300ms
}
}
BreakoutView::BreakoutView(NavigationView& nav)
: nav_{nav}, bricks{} { // Add bricks{} here
: nav_{nav}, bricks{} {
// Initialize audio system for beeps FIRST
baseband::run_prepared_image(portapack::memory::map::m4_code.base()); // Load the audio beep baseband
add_children({&dummy});
// Initialize audio
audio::set_rate(audio::Rate::Hz_24000);
audio::output::start();
// Set initial volume to 80% and ensure sound is ON
volume_level = 80;
sound_enabled = true; // Make sure this is explicitly set to ON
// Set the actual volume
int db = (volume_level - 99) * 60 / 99; // Maps to roughly -12dB for 80%
audio::headphone::set_volume(volume_t::decibel(db));
attach(1.0 / 60.0);
}
BreakoutView::~BreakoutView() {
// Clean shutdown
baseband::request_beep_stop();
receiver_model.disable();
baseband::shutdown();
audio::output::stop();
}
void BreakoutView::on_show() {
// Nothing needed here, initialization done in constructor
}
void BreakoutView::on_hide() {
// Additional cleanup
baseband::request_beep_stop();
audio::output::stop();
}
void BreakoutView::focus() {
dummy.focus();
}
void BreakoutView::paint(Painter& painter) {
@@ -433,16 +685,33 @@ bool BreakoutView::on_key(const KeyEvent key) {
} else if (game_state == STATE_PLAYING && ball_attached) {
launch_ball();
} else if (game_state == STATE_GAME_OVER) {
reset_game();
// Return to menu after game over
game_state = STATE_MENU;
menu_blink_counter = 0;
init_game();
}
} else if (key == KeyEvent::Left && game_state == STATE_PLAYING) {
move_paddle_left();
} else if (key == KeyEvent::Right && game_state == STATE_PLAYING) {
move_paddle_right();
} else if (key == KeyEvent::Up && game_state == STATE_MENU) {
// Only adjust volume in menu
adjust_volume(5);
if (!sound_enabled) sound_enabled = true;
set_dirty();
} else if (key == KeyEvent::Down && game_state == STATE_MENU) {
// Only adjust volume in menu
adjust_volume(-5);
set_dirty();
}
set_dirty();
return true;
}
bool BreakoutView::on_touch(const TouchEvent event) {
(void)event; // Intentionally unused - touch disabled to avoid nav bar issues
return true;
}
} // namespace ui::external_app::breakout
+21 -1
View File
@@ -11,6 +11,7 @@
#include "ui.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "event_m0.hpp"
#include "message.hpp"
#include "irq_controls.hpp"
@@ -56,15 +57,18 @@ enum {
class BreakoutView : public View {
public:
BreakoutView(NavigationView& nav);
~BreakoutView();
void on_show() override;
void on_hide() override;
std::string title() const override { return "Breakout"; }
void focus() override { dummy.focus(); }
void focus() override;
void paint(Painter& painter) override;
void frame_sync();
bool on_encoder(const EncoderEvent event) override;
bool on_key(KeyEvent key) override;
bool on_touch(const TouchEvent event) override;
void cls();
void background(int color);
@@ -81,6 +85,7 @@ class BreakoutView : public View {
void draw_lives();
void draw_level();
void draw_borders();
void draw_menu_volume_bar();
void move_paddle_left();
void move_paddle_right();
void launch_ball();
@@ -96,6 +101,15 @@ class BreakoutView : public View {
void check_game_timer();
void attach(double delay_sec);
void detach();
void adjust_volume(int delta);
// Sound effect methods
void play_paddle_hit();
void play_brick_hit();
void play_wall_hit();
void play_death_sound();
void play_game_over();
void play_level_complete();
private:
const Color pp_colors[9] = {
@@ -147,6 +161,12 @@ class BreakoutView : public View {
double game_update_timeout = 0;
uint32_t game_update_counter = 0;
// Audio control
bool sound_enabled = true;
int volume_level = 80; // 0-99
uint32_t last_sound_time = 0;
uint32_t min_sound_interval = 20; // Minimum ms between sounds
Button dummy{
{screen_width, 0, 0, 0},
""};
+1 -1
View File
@@ -118,7 +118,7 @@ class ERTAppView : public View {
// Prevent painting of region covered entirely by a child.
// TODO: Add flag to View that specifies view does not need to be cleared before painting.
void paint(Painter&) override{};
void paint(Painter&) override {};
void focus() override;
+98 -71
View File
@@ -1,259 +1,281 @@
set(EXTCPPSRC
#afsk_rx
#afsk_rx 16 byte
external/afsk_rx/main.cpp
external/afsk_rx/ui_afsk_rx.cpp
#calculator
#calculator 632 bytes
external/calculator/main.cpp
external/calculator/ui_calculator.cpp
#font_viewer
#font_viewer 8 byte?!
external/font_viewer/main.cpp
external/font_viewer/ui_font_viewer.cpp
#blespam
#blespam 336 bytes - array initializers?
external/blespam/main.cpp
external/blespam/ui_blespam.cpp
#analogtv
#analogtv 552 bytes
external/analogtv/main.cpp
external/analogtv/analog_tv_app.cpp
external/analogtv/ui_tv.cpp
#nrf_rx
#nrf_rx 40 byte
external/nrf_rx/main.cpp
external/nrf_rx/ui_nrf_rx.cpp
#coasterp
#coasterp 0 byte
external/coasterp/main.cpp
external/coasterp/ui_coasterp.cpp
#lge
#lge 120 byte
external/lge/main.cpp
external/lge/lge_app.cpp
external/lge/rfm69.cpp
#lcr
#lcr - 460 byte flash
external/lcr/main.cpp
external/lcr/ui_lcr.cpp
#jammer
#jammer 144 byte
external/jammer/main.cpp
external/jammer/ui_jammer.cpp
#gpssim
#gpssim 160 byte
external/gpssim/main.cpp
external/gpssim/gps_sim_app.cpp
#spainter
#spainter 464 byte
external/spainter/main.cpp
external/spainter/ui_spectrum_painter.cpp
external/spainter/ui_spectrum_painter_text.cpp
external/spainter/ui_spectrum_painter_image.cpp
#keyfob
#keyfob 216 byte
external/keyfob/main.cpp
external/keyfob/ui_keyfob.cpp
external/keyfob/ui_keyfob.hpp
#tetris
#tetris 88 byte
external/tetris/main.cpp
external/tetris/ui_tetris.cpp
#extsensors
#extsensors 192 byte
external/extsensors/main.cpp
external/extsensors/ui_extsensors.cpp
external/extsensors/ui_extsensors.hpp
#foxhunt
#foxhunt 0
external/foxhunt/main.cpp
external/foxhunt/ui_foxhunt_rx.cpp
external/foxhunt/ui_foxhunt_rx.hpp
#audio_test
#audio_test 192 byte
external/audio_test/main.cpp
external/audio_test/ui_audio_test.cpp
#wardrivemap
#wardrivemap 64 byte
external/wardrivemap/main.cpp
external/wardrivemap/ui_wardrivemap.cpp
#tpmsrx
#tpmsrx 920 byte- possible shared part with baseband
external/tpmsrx/main.cpp
external/tpmsrx/tpms_app.cpp
#protoview
#protoview 8 byte
external/protoview/main.cpp
external/protoview/ui_protoview.cpp
#adsbtx
#adsbtx 3544 byte - adsb shared part
external/adsbtx/main.cpp
external/adsbtx/ui_adsb_tx.cpp
#morse_tx
#morse_tx 768 bytes
external/morse_tx/main.cpp
external/morse_tx/ui_morse.cpp
#sstvtx
#sstvtx 456 bytes
external/sstvtx/main.cpp
external/sstvtx/ui_sstvtx.cpp
#random
#sstvrx
external/sstvrx/main.cpp
external/sstvrx/ui_sstvrx.cpp
#random 464 bytes.
external/random_password/main.cpp
external/random_password/ui_random_password.cpp
external/random_password/sha512.cpp
external/random_password/sha512.h
#acars
external/acars_rx/main.cpp
external/acars_rx/acars_app.cpp
#external/acars_rx/main.cpp
#external/acars_rx/acars_app.cpp
#wefax_rx
#wefax_rx 192 bytes
external/wefax_rx/main.cpp
external/wefax_rx/ui_wefax_rx.cpp
#noaaapt_rx
#noaaapt_rx 72 bytes
external/noaaapt_rx/main.cpp
external/noaaapt_rx/ui_noaaapt_rx.cpp
#shoppingcart_lock
#shoppingcart_lock 272 bytes
external/shoppingcart_lock/main.cpp
external/shoppingcart_lock/shoppingcart_lock.cpp
#ookbrute
#ookbrute 80 byte
external/ookbrute/main.cpp
external/ookbrute/ui_ookbrute.cpp
#ook_editor
#ook_editor 1808 bytes
external/ook_editor/main.cpp
external/ook_editor/ui_ook_editor.cpp
#cvs_spam
#cvs_spam 24 byte
external/cvs_spam/main.cpp
external/cvs_spam/cvs_spam.cpp
#flippertx
#flippertx 712 bytes
external/flippertx/main.cpp
external/flippertx/ui_flippertx.cpp
#remote
#remote 1664 bytes
external/remote/main.cpp
external/remote/ui_remote.cpp
#mcu_temperature
#mcu_temperature 112
external/mcu_temperature/main.cpp
external/mcu_temperature/mcu_temperature.cpp
#fmradio
#fmradio 640
external/fmradio/main.cpp
external/fmradio/ui_fmradio.cpp
#tuner
#tuner 384
external/tuner/main.cpp
external/tuner/ui_tuner.cpp
#metronome
#metronome 696 bytes
external/metronome/main.cpp
external/metronome/ui_metronome.cpp
#app_manager
#app_manager 40 bytes
external/app_manager/main.cpp
external/app_manager/ui_app_manager.cpp
#hopper
#hopper 472 bytes
external/hopper/main.cpp
external/hopper/ui_hopper.cpp
# whip calculator
# whip calculator 48 bytes
external/antenna_length/main.cpp
external/antenna_length/ui_whipcalc.cpp
# wav viewer
# wav viewer 1232 bytes
external/wav_view/main.cpp
external/wav_view/ui_view_wav.cpp
# wipe sdcard
# wipe sdcard 16 byte
external/sd_wipe/main.cpp
external/sd_wipe/ui_sd_wipe.cpp
# playlist editor
# playlist editor 232 bytes
external/playlist_editor/main.cpp
external/playlist_editor/ui_playlist_editor.cpp
#snake
#snake 240 bytes
external/snake/main.cpp
external/snake/ui_snake.cpp
#stopwatch
#stopwatch 0
external/stopwatch/main.cpp
external/stopwatch/ui_stopwatch.cpp
#breakout
#breakout 1144 bytes
external/breakout/main.cpp
external/breakout/ui_breakout.cpp
#dinogame
#dinogame 0
external/dinogame/main.cpp
external/dinogame/ui_dinogame.cpp
#doom
#doom 224
external/doom/main.cpp
external/doom/ui_doom.cpp
#debug_pmem
#debug_pmem 944 byte
external/debug_pmem/main.cpp
external/debug_pmem/ui_debug_pmem.cpp
#scanner
#scanner 520 byte
external/scanner/main.cpp
external/scanner/ui_scanner.cpp
#level
#level 24 byte
external/level/main.cpp
external/level/ui_level.cpp
#gfxEQ
#gfxEQ 80 byte
external/gfxeq/main.cpp
external/gfxeq/ui_gfxeq.cpp
#detector_rx
#detector_rx 168 byte
external/detector_rx/main.cpp
external/detector_rx/ui_detector_rx.cpp
#space_invaders
#space_invaders 0 byte
external/spaceinv/main.cpp
external/spaceinv/ui_spaceinv.cpp
#blackjack
#blackjack 24 byte
external/blackjack/main.cpp
external/blackjack/ui_blackjack.cpp
#battleship
#battleship 256 byte
external/battleship/main.cpp
external/battleship/ui_battleship.cpp
#ert
#ert 3040 bytes - has common with baseband, could be renamed the namespace, so both could have it, but not kept in fw.
external/ert/main.cpp
external/ert/ert_app.cpp
#epirb_rx
#epirb_rx 168 byte flash
external/epirb_rx/main.cpp
external/epirb_rx/ui_epirb_rx.cpp
#soundboard
#soundboard 272byte - 1236 bytes
external/soundboard/main.cpp
external/soundboard/soundboard_app.cpp
#game2048
#game2048 - 168 byte flash
external/game2048/main.cpp
external/game2048/ui_game2048.cpp
#bht_tx
#bht_tx - 3920 byte flash, unknown
external/bht_tx/main.cpp
external/bht_tx/ui_bht_tx.cpp
external/bht_tx/bht.cpp
#morse_practice - 80 byte flash - bc of array initializers
external/morse_practice/main.cpp
external/morse_practice/ui_morse_practice.cpp
#adult_toys_controller 144 bytes
external/adult_toys_controller/main.cpp
external/adult_toys_controller/ui_adult_toys_controller.cpp
#flex_rx
external/flex_rx/main.cpp
external/flex_rx/ui_flex_rx.cpp
#subcarrx
external/subcarrx/main.cpp
external/subcarrx/ui_subcar.cpp
)
set(EXTAPPLIST
@@ -261,8 +283,8 @@ set(EXTAPPLIST
calculator
font_viewer
blespam
nrf_rx
analogtv
nrf_rx
coasterp
lge
lcr
@@ -275,19 +297,20 @@ set(EXTAPPLIST
foxhunt_rx
audio_test
wardrivemap
cvs_spam
tpmsrx
protoview
adsbtx
morse_tx
sstvtx
sstvrx
random_password
# acars_rx
ookbrute
ook_editor
# acars_rx --not working
wefax_rx
noaaapt_rx
shoppingcart_lock
ookbrute
ook_editor
cvs_spam
flippertx
remote
mcu_temperature
@@ -318,4 +341,8 @@ set(EXTAPPLIST
soundboard
game2048
bht_tx
morse_practice
adult_toys_controller
flex_rx
subcarrx
)
+37 -2
View File
@@ -83,8 +83,12 @@ MEMORY
ram_external_app_epirb_rx (rwx) : org = 0xADEA0000, len = 32k
ram_external_app_soundboard (rwx) : org = 0xADEB0000, len = 32k
ram_external_app_game2048 (rwx) : org = 0xADEC0000, len = 32k
ram_external_app_bht_tx (rwx) : org = 0xADED0000, len = 32k
ram_external_app_bht_tx (rwx) : org = 0xADED0000, len = 32k
ram_external_app_morse_practice (rwx) : org = 0xADEE0000, len = 32k
ram_external_app_adult_toys_controller (rwx) : org = 0xADEF0000, len = 32k
ram_external_app_flex_rx (rwx) : org = 0xADF00000, len = 32k
ram_external_app_sstvrx (rwx) : org = 0xADF10000, len = 32k
ram_external_app_subcarrx (rwx) : org = 0xADF20000, len = 32k
}
@@ -458,5 +462,36 @@ SECTIONS
} > ram_external_app_bht_tx
.external_app_morse_practice : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_morse_practice.application_information));
*(*ui*external_app*morse_practice*);
} > ram_external_app_morse_practice
.external_app_adult_toys_controller : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_adult_toys_controller.application_information));
*(*ui*external_app*adult_toys_controller*);
} > ram_external_app_adult_toys_controller
.external_app_flex_rx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_flex_rx.application_information));
*(*ui*external_app*flex_rx*);
} > ram_external_app_flex_rx
.external_app_sstvrx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_sstvrx.application_information));
*(*ui*external_app*sstvrx*);
} > ram_external_app_sstvrx
.external_app_subcarrx : ALIGN(4) SUBALIGN(4)
{
KEEP(*(.external_app.app_subcarrx.application_information));
*(*ui*external_app*subcarrx*);
} > ram_external_app_subcarrx
}
+83
View File
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2025 HTotoo
*
* 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_flex_rx.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::flex_rx {
void initialize_app(ui::NavigationView& nav) {
nav.push<FlexAppView>();
}
} // namespace ui::external_app::flex_rx
extern "C" {
__attribute__((section(".external_app.app_flex_rx.application_information"), used)) application_information_t _application_information_flex_rx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::flex_rx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "FLEX RX",
/*.bitmap_data = */ {
0x00,
0x00,
0xFE,
0x7F,
0x02,
0x40,
0xFA,
0x5F,
0x02,
0x40,
0xF2,
0x4F,
0x02,
0x40,
0xE2,
0x47,
0x02,
0x40,
0xC2,
0x43,
0x02,
0x40,
0x82,
0x41,
0x02,
0x40,
0xFE,
0x7F,
0x00,
0x00,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::orange().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_flex */ {'P', 'F', 'L', 'X'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
}
+129
View File
@@ -0,0 +1,129 @@
#include "ui_flex_rx.hpp"
#include "baseband_api.hpp"
#include "portapack_persistent_memory.hpp"
#include "string_format.hpp"
#include "memory_map.hpp"
using namespace portapack;
namespace ui::external_app::flex_rx {
FlexAppView::FlexAppView(NavigationView& nav)
: nav_{nav} {
// Load baseband image for FLEX decoding
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
add_children({&field_frequency,
&field_rf_amp,
&field_lna,
&field_vga,
&rssi,
&console});
// Restore saved frequency
field_frequency.set_value(frequency_value);
receiver_model.set_target_frequency(frequency_value);
// Frequency change callback
field_frequency.updated = [this](rf::Frequency f) {
update_freq(f);
};
// Configure receiver
receiver_model.set_sampling_rate(3072000);
receiver_model.set_baseband_bandwidth(1750000);
receiver_model.enable();
receiver_model.set_squelch_level(0);
// Initialize FLEX baseband
baseband::set_flex_config();
console.writeln("Ready");
}
FlexAppView::~FlexAppView() {
receiver_model.disable();
baseband::shutdown();
}
void FlexAppView::focus() {
field_frequency.focus();
}
// Redraw all messages to console
void FlexAppView::redraw_console() {
console.clear(true);
bool first = true;
for (const auto& msg : messages) {
if (!first) {
console.writeln(""); // Blank line between messages
}
first = false;
console.writeln(msg);
}
}
// Add message to log with automatic line wrapping
void FlexAppView::log_message(const std::string& message) {
const size_t chars_per_line = screen_width / 8;
// Console height accounts for status bar and controls row
const size_t console_lines = (screen_height - 2 * 16) / 16;
messages.push_back(message);
// Calculate total lines used (messages + blank lines between them)
size_t total_lines = 0;
for (size_t i = 0; i < messages.size(); i++) {
if (i > 0) total_lines++; // Count blank line separator
size_t msg_lines = (messages[i].length() + chars_per_line - 1) / chars_per_line;
if (msg_lines == 0) msg_lines = 1;
total_lines += msg_lines;
}
// If console would overflow, remove oldest messages and redraw
if (total_lines > console_lines) {
while (total_lines > console_lines && !messages.empty()) {
const auto& oldest = messages.front();
size_t oldest_lines = (oldest.length() + chars_per_line - 1) / chars_per_line;
if (oldest_lines == 0) oldest_lines = 1;
total_lines -= oldest_lines;
if (messages.size() > 1) total_lines--; // Remove separator line too
messages.erase(messages.begin());
}
redraw_console();
} else {
// Just append new message
if (messages.size() > 1) {
console.writeln(""); // Blank line before new message
}
console.writeln(message);
}
}
// Update frequency and save for persistence
void FlexAppView::update_freq(rf::Frequency f) {
frequency_value = f;
receiver_model.set_target_frequency(f);
}
// Handle decoded FLEX packet from baseband
void FlexAppView::on_packet(const FlexPacketMessage* message) {
log_message(message->packet.message);
}
// Handle stats message (currently unused)
void FlexAppView::on_stats(const FlexStatsMessage*) {
}
// Debug handler - uncomment to see baseband debug messages
void FlexAppView::on_debug(const FlexDebugMessage* message) {
(void)message; // Suppress unused parameter warning
// std::string text = "DBG: ";
// text += message->text;
// text += " " + to_string_hex(message->val1, 8);
// text += " " + to_string_hex(message->val2, 8);
// log_message(text);
}
} // namespace ui::external_app::flex_rx
+97
View File
@@ -0,0 +1,97 @@
#ifndef __UI_FLEX_RX_H__
#define __UI_FLEX_RX_H__
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "ui_freq_field.hpp"
#include "ui_rssi.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include <string>
#include <vector>
namespace ui::external_app::flex_rx {
class FlexAppView : public View {
public:
FlexAppView(NavigationView& nav);
~FlexAppView();
void focus() override;
std::string title() const override { return "FLEX RX"; };
private:
NavigationView& nav_;
// Saved settings
rf::Frequency frequency_value{931740000}; // Default FLEX frequency
RxRadioState radio_state_{};
// Message storage for console redraw
static constexpr size_t MAX_MESSAGES = 20;
std::vector<std::string> messages{};
// Helper methods
void log_message(const std::string& message);
void redraw_console();
void update_freq(rf::Frequency f);
// UI Elements - Row 0, dynamically positioned
RxFrequencyField field_frequency{
{UI_POS_X(0), UI_POS_Y(0)},
nav_};
RFAmpField field_rf_amp{
{UI_POS_X(13), UI_POS_Y(0)}};
LNAGainField field_lna{
{UI_POS_X(15), UI_POS_Y(0)}};
VGAGainField field_vga{
{UI_POS_X(18), UI_POS_Y(0)}};
RSSI rssi{
{UI_POS_X(21), 0, UI_POS_WIDTH(9), 4}};
// Message display area (below controls, account for status bar)
Console console{
{0, 1 * 16, screen_width, screen_height - 2 * 16}};
// Persistent settings manager
app_settings::SettingsManager settings_{
"rx_flex",
app_settings::Mode::RX,
{{"frequency", &frequency_value}}};
// Message handlers
void on_packet(const FlexPacketMessage* message);
void on_stats(const FlexStatsMessage* message);
void on_debug(const FlexDebugMessage* message);
// Message handler registrations
MessageHandlerRegistration message_handler_packet{
Message::ID::FlexPacket,
[this](const Message* const p) {
const auto message = *static_cast<const FlexPacketMessage*>(p);
this->on_packet(&message);
}};
MessageHandlerRegistration message_handler_stats{
Message::ID::FlexStats,
[this](const Message* const p) {
const auto message = *static_cast<const FlexStatsMessage*>(p);
this->on_stats(&message);
}};
MessageHandlerRegistration message_handler_debug{
Message::ID::FlexDebug,
[this](const Message* const p) {
const auto message = *static_cast<const FlexDebugMessage*>(p);
this->on_debug(&message);
}};
};
} // namespace ui::external_app::flex_rx
#endif /*__UI_FLEX_RX_H__*/
+1 -1
View File
@@ -79,7 +79,7 @@ class FlipperTxView : public View {
void on_tx_progress(const bool done);
bool on_file_changed(std::filesystem::path new_file_path);
std::filesystem::path filename = {};
std::filesystem::path filename = "";
FlipperProto proto = FLIPPER_PROTO_UNSUPPORTED;
FlipperPreset preset = FLIPPER_PRESET_UNK;
uint16_t te = 0; // for binraw
-1
View File
@@ -41,7 +41,6 @@ gfxEQView::gfxEQView(NavigationView& nav)
audio::set_rate(audio::Rate::Hz_48000);
audio::output::start();
receiver_model.set_headphone_volume(receiver_model.headphone_volume()); // WM8731 hack
//
receiver_model.enable();
receiver_model.set_target_frequency(frequency_value); // Retune to actual freq
+9 -7
View File
@@ -46,6 +46,7 @@ class gfxEQView : public View {
NavigationView& nav_;
uint32_t current_theme{0};
const std::array<ColorTheme, 20> themes{
ColorTheme{Color(255, 0, 255), Color(255, 255, 255)},
ColorTheme{Color(0, 255, 0), Color(255, 0, 0)},
@@ -68,13 +69,14 @@ class gfxEQView : public View {
ColorTheme{Color(64, 64, 64), Color(255, 0, 0)},
ColorTheme{Color(255, 192, 0), Color(0, 64, 128)}};
ButtonWithEncoder button_frequency{{UI_POS_X(0), UI_POS_Y(0) + 4, 11 * 8, 1 * 8}, ""};
RFAmpField field_rf_amp{{13 * 8, UI_POS_Y(0)}};
LNAGainField field_lna{{15 * 8, UI_POS_Y(0)}};
VGAGainField field_vga{{18 * 8, UI_POS_Y(0)}};
Button button_mood{{21 * 8, 0, 6 * 8, 16}, "MOOD"};
AudioVolumeField field_volume{{screen_width - 2 * 8, UI_POS_Y(0)}};
GraphEq gr{{2, UI_POS_DEFAULT_HEIGHT, UI_POS_MAXWIDTH - 4, UI_POS_HEIGHT_REMAINING(2)}, false};
// Widgets with positions using UI_POS macros
ButtonWithEncoder button_frequency{{UI_POS_X(0), UI_POS_Y(0) + 4, UI_POS_WIDTH(11), UI_POS_HEIGHT(1)}, ""};
RFAmpField field_rf_amp{{UI_POS_X(12), UI_POS_Y(0) + 4}};
LNAGainField field_lna{{UI_POS_X(14), UI_POS_Y(0) + 4}};
VGAGainField field_vga{{UI_POS_X(17), UI_POS_Y(0) + 4}};
Button button_mood{{UI_POS_X(21), UI_POS_Y(0) + 4, UI_POS_WIDTH(4), UI_POS_HEIGHT(1)}, "MOOD"};
AudioVolumeField field_volume{{UI_POS_X_RIGHT(2), UI_POS_Y(0) + 4}};
GraphEq gr{{2, UI_POS_Y(1) + 8, UI_POS_MAXWIDTH, UI_POS_Y_BOTTOM(1) - 28}, false};
rf::Frequency frequency_value{93100000};
@@ -24,6 +24,8 @@
#include "crc.hpp"
#include "portapack_shared_memory.hpp"
namespace ui::external_app::lge {
uint32_t RFM69::gen_frame(std::vector<uint8_t>& payload) {
CRC<16> crc{0x1021, 0x1D0F, 0xFFFF};
std::vector<uint8_t> frame{};
@@ -74,3 +76,5 @@ uint32_t RFM69::gen_frame(std::vector<uint8_t>& payload) {
// Copy for baseband
return frame.size();
}
} /* namespace ui::external_app::lge */
@@ -28,6 +28,8 @@
#include "utility.hpp"
namespace ui::external_app::lge {
class RFM69 {
public:
RFM69(const uint8_t num_preamble, const uint16_t sync_word, const bool CRC, const bool manchester)
@@ -54,4 +56,6 @@ class RFM69 {
bool manchester_{false};
};
} /* namespace ui::external_app::lge */
#endif /*__RFM69_H__*/
+87
View File
@@ -0,0 +1,87 @@
/*
* 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 "ui.hpp"
#include "ui_morse_practice.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::morse_practice {
void initialize_app(NavigationView& nav) {
nav.push<MorsePracticeView>();
}
} // namespace ui::external_app::morse_practice
extern "C" {
__attribute__((section(".external_app.app_morse_practice.application_information"), used))
application_information_t _application_information_morse_practice = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::morse_practice::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "Morse P",
/*.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::GAMES,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_none */ {'P', 'A', 'B', 'P'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
} // extern "C"
@@ -0,0 +1,348 @@
#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>
#define MORSEDEC_ERROR "<ERR>"
namespace ui::external_app::morse_practice {
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];
}
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() {}
DecodeResult handleInput(int32_t duration_ms) {
DecodeResult result = {"", 0.0};
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 != MORSEDEC_ERROR) ? last_confidence_ : 0.0;
if (gap_duration >= getInterWordThreshold()) {
result.text += " ";
}
current_sequence_ = "";
}
}
updateLearning();
return result;
}
inline double getInterElementThreshold() { return time_unit_ms_ * 2.0; }
inline double getInterCharThreshold() { return time_unit_ms_ * 4.0; }
inline double getInterWordThreshold() { return time_unit_ms_ * 7.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_ = 160.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 MORSEDEC_ERROR; // 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_ = 41;
MorseEntry morse_table_[41] = {
{".-", "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::morse_practice
#endif // __MORSEDECODER_HPP__
@@ -0,0 +1,144 @@
#include "ui_morse_practice.hpp"
using namespace portapack;
namespace ui::external_app::morse_practice {
MorsePracticeView::MorsePracticeView(ui::NavigationView& nav)
: nav_(nav) {
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
add_children({&btn_tt,
&txt_last,
&btn_clear,
&console_text,
&field_volume});
audio::set_rate(audio::Rate::Hz_24000);
btn_tt.on_select = [this](Button&) {
if (button_touch) {
button_touch = false;
return;
}
button_was_selected = true;
onPress();
};
btn_tt.on_touch_press = [this](Button&) {
button_touch = true;
button_was_selected = false;
onPress();
};
btn_tt.on_touch_release = [this](Button&) {
button_touch = true;
button_was_selected = false;
onRelease();
};
btn_clear.on_select = [this](Button&) {
console_text.clear(true);
txt_last.set("");
};
audio::output::start();
auto vol = field_volume.value();
field_volume.set_value(0);
field_volume.set_value(vol);
}
MorsePracticeView::~MorsePracticeView() {
receiver_model.disable();
baseband::shutdown();
audio::output::stop();
}
void MorsePracticeView::on_show() {
console_text.write("Morse Practice ready\n");
start_time = 0;
end_time = 0;
}
void MorsePracticeView::focus() {
btn_tt.focus();
}
void MorsePracticeView::onPress() {
start_time = chTimeNow();
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;
decode_timeout_calc = false;
baseband::request_audio_beep(1000, 24000, 2000);
}
void MorsePracticeView::onRelease() {
end_time = chTimeNow();
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 MorsePracticeView::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 == MORSEDEC_ERROR) {
color_id = 0;
} 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);
}
inline bool MorsePracticeView::tx_button_held() {
const auto switches_state = get_switches_state();
return switches_state[(size_t)ui::KeyEvent::Select];
}
void MorsePracticeView::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;
}
}
}
} // namespace ui::external_app::morse_practice
@@ -0,0 +1,91 @@
/*
* 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.
*/
#ifndef __MORSE_PRACTICE_H__
#define __MORSE_PRACTICE_H__
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_navigation.hpp"
#include "ui_language.hpp"
#include "ui_painter.hpp"
#include "ui_receiver.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 <ch.h>
namespace ui::external_app::morse_practice {
class MorsePracticeView : public ui::View {
public:
MorsePracticeView(ui::NavigationView& nav);
~MorsePracticeView();
std::string title() { return "Morse P"; }
void focus() override;
void on_show() override;
private:
void onPress();
void onRelease();
void on_framesync();
void writeCharToConsole(const std::string& ch, double confidence);
bool tx_button_held();
ui::NavigationView& nav_;
MorseDecoder morse_decoder_{};
int64_t start_time = 0;
int64_t end_time = 0;
ui::Button btn_tt{{UI_POS_X_CENTER(12), UI_POS_Y(3), UI_POS_WIDTH(12), UI_POS_HEIGHT(3)}, "KEY"};
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)}};
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;
MessageHandlerRegistration message_handler_framesync{
Message::ID::DisplayFrameSync,
[this](const Message* const p) {
(void)p;
this->on_framesync();
}};
};
} // namespace ui::external_app::morse_practice
#endif // __MORSE_PRACTICE_H__
+15 -14
View File
@@ -45,12 +45,9 @@ static msg_t ookthread_fn(void* arg) {
uint8_t* message_symbols = shared_memory.bb_data.tones_data.message;
uint8_t symbol;
MorseView* arg_c = (MorseView*)arg;
chRegSetThreadName("ookthread");
for (uint32_t i = 0; i < arg_c->symbol_count; i++) {
if (chThdShouldTerminate()) break;
symbol = message_symbols[i];
v = (symbol < 2) ? 1 : 0; // TX on for dot or dash, off for pause
@@ -61,9 +58,7 @@ static msg_t ookthread_fn(void* arg) {
} else {
gpio_og_tx.write(v); // in hackrf <=r6, "1" means tx , "0" no tx.
}
arg_c->on_tx_progress(i, false);
chThdSleepMilliseconds(delay * arg_c->time_unit_ms);
}
@@ -82,19 +77,14 @@ static msg_t ookthread_fn(void* arg) {
static msg_t loopthread_fn(void* arg) {
MorseView* arg_c = (MorseView*)arg;
uint32_t wait = arg_c->loop;
chRegSetThreadName("loopthread");
for (uint32_t i = 0; i < wait; i++) {
if (chThdShouldTerminate()) break;
arg_c->on_loop_progress(i, false);
chThdSleepMilliseconds(1000);
}
arg_c->on_loop_progress(0, true);
if (!chThdShouldTerminate()) arg_c->on_loop_progress(0, true);
chThdExit(0);
return 0;
}
@@ -132,6 +122,15 @@ void MorseView::focus() {
}
MorseView::~MorseView() {
if (ookthread) {
chThdTerminate(ookthread);
ookthread = nullptr;
}
if (loopthread) {
chThdTerminate(loopthread);
chThdWait(loopthread);
loopthread = nullptr;
}
transmitter_model.disable();
baseband::shutdown();
}
@@ -181,6 +180,9 @@ void MorseView::update_tx_duration() {
void MorseView::on_tx_progress(const uint32_t progress, const bool done) {
if (done) {
if (ookthread) {
ookthread = nullptr;
}
transmitter_model.disable();
progressbar.set_value(0);
@@ -190,10 +192,10 @@ void MorseView::on_tx_progress(const uint32_t progress, const bool done) {
progressbar.set_value(0);
if (loopthread) {
chThdRelease(loopthread);
chThdTerminate(loopthread);
chThdWait(loopthread);
loopthread = nullptr;
}
loopthread = chThdCreateFromHeap(NULL, 1024, NORMALPRIO, loopthread_fn, this);
} else {
tx_view.set_transmitting(false);
@@ -219,7 +221,6 @@ void MorseView::set_foxhunt(size_t i) {
MorseView::MorseView(
NavigationView& nav)
: nav_(nav) {
// baseband::run_image(portapack::spi_flash::image_tag_tones);
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
add_children({&labels,
+1 -1
View File
@@ -110,7 +110,7 @@ class MorseView : public View {
bool run{false};
Labels labels{
{{4 * 8, 6 * 8}, "Speed: wps", Theme::getInstance()->fg_light->foreground},
{{4 * 8, 6 * 8}, "Speed: wpm", Theme::getInstance()->fg_light->foreground},
{{4 * 8, 8 * 8}, "Tone: Hz", Theme::getInstance()->fg_light->foreground},
{{4 * 8, 10 * 8}, "Modulation:", Theme::getInstance()->fg_light->foreground},
{{4 * 8, 12 * 8}, "Loop:", Theme::getInstance()->fg_light->foreground},
@@ -231,7 +231,7 @@ void RandomPasswordView::on_data(uint32_t value, bool is_data) {
}
void RandomPasswordView::clean_buffer() {
seeds_deque = {};
seeds_deque.clear();
}
void RandomPasswordView::on_freqchg(int64_t freq) {
@@ -247,6 +247,18 @@ void RandomPasswordView::set_random_freq() {
field_frequency.set_value(random_freq);
}
bool RandomPasswordView::islower(char c) {
return (c >= 'a' && c <= 'z');
}
bool RandomPasswordView::isupper(char c) {
return (c >= 'A' && c <= 'Z');
}
bool RandomPasswordView::isdigit(char c) {
return (c >= '0' && c <= '9');
}
void RandomPasswordView::new_password() {
if (seeds_deque.size() < MAX_DIGITS * 2) {
seeds_buffer_not_full = true;
@@ -261,21 +273,21 @@ void RandomPasswordView::new_password() {
int password_length = field_digits.value();
/// charset worker
if (check_digits.value())
charset += "0123456789";
if (check_latin_lower.value())
charset += "abcdefghijklmnopqrstuvwxyz";
if (check_latin_upper.value())
charset += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (check_digits.value()) {
charset += "23456789";
if (check_allow_confusable_chars.value()) charset += "01";
}
if (check_latin_lower.value()) {
charset += "abcdefghijkmnpqrstuvwxyz";
if (check_allow_confusable_chars.value()) charset += "ol";
}
if (check_latin_upper.value()) {
charset += "ABCDEFGHIJKLMNPQRSTUVWXYZ";
if (check_allow_confusable_chars.value()) charset += "O";
}
if (check_punctuation.value())
charset += ".,-!?";
if (!check_allow_confusable_chars.value()) {
charset.erase(std::remove_if(charset.begin(), charset.end(),
[](char c) { return c == '0' || c == 'O' || c == 'o' || c == '1' || c == 'l'; }),
charset.end());
}
if (charset.empty()) {
text_generated_passwd.set("generate failed,");
text_char_type_hints.set("select at least 1 type");
@@ -306,11 +318,11 @@ void RandomPasswordView::new_password() {
/// hint text worker
for (char c : password_chars) {
password += c;
if (std::isdigit(c)) {
if (isdigit(c)) {
char_type_hints += "1";
} else if (std::islower(c)) {
} else if (islower(c)) {
char_type_hints += "a";
} else if (std::isupper(c)) {
} else if (isupper(c)) {
char_type_hints += "A";
} else {
char_type_hints += ",";
@@ -360,11 +372,11 @@ void RandomPasswordView::paint_password_hints() {
for (size_t i = 0; i < password.length(); i++) {
char c = password[i];
Color color;
if (std::isdigit(c)) {
if (isdigit(c)) {
color = Color::red();
} else if (std::islower(c)) {
} else if (islower(c)) {
color = Color::green();
} else if (std::isupper(c)) {
} else if (isupper(c)) {
color = Color::blue();
} else {
color = Color::white();
@@ -379,8 +391,8 @@ void RandomPasswordView::paint_password_hints() {
std::string RandomPasswordView::generate_log_line() {
std::string seeds_set = "";
for (auto seed : seeds_deque) {
seeds_set += std::to_string(seed);
for (unsigned int seed : seeds_deque) {
seeds_set += to_string_dec_uint(seed);
seeds_set += " ";
}
std::string line = "\npassword=" + password +
@@ -92,6 +92,10 @@ class RandomPasswordView : public View {
std::string generate_log_line();
void paint_password_hints();
bool islower(char c);
bool isupper(char c);
bool isdigit(char c);
NavigationView& nav_;
RxRadioState radio_state_{};
app_settings::SettingsManager settings_{
+88
View File
@@ -0,0 +1,88 @@
/*
* Copyright (C) 2025 StarVore Labs
*
* 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_sstvrx.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::sstvrx {
void initialize_app(NavigationView& nav) {
nav.push<SstvRxView>();
}
} // namespace ui::external_app::sstvrx
extern "C" {
// Az alkalmazás információ C-linkage-ként, hogy a firmware hívhassa
__attribute__((section(".external_app.app_sstvrx.application_information"), used))
application_information_t _application_information_sstvrx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::sstvrx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "SSTV RX",
/*.bitmap_data = */ {
0x00,
0x00,
0x00,
0x00,
0xFE,
0x7F,
0x03,
0xC0,
0x53,
0xD5,
0xAB,
0xCA,
0x53,
0xD5,
0xAB,
0xCA,
0x53,
0xD5,
0xAB,
0xCA,
0x53,
0xD5,
0x03,
0xC0,
0xFF,
0xFF,
0xFB,
0xD7,
0xFE,
0x7F,
0x00,
0x00,
},
/*.icon_color = */ ui::Color::yellow().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_none */ {'P', 'S', 'R', 'X'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
} // extern "C"
+510
View File
@@ -0,0 +1,510 @@
/*
* Copyright (C) 2025 StarVore Labs
*
* 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_sstvrx.hpp"
#include "portapack_persistent_memory.hpp"
#include "portapack.hpp"
#include "hackrf_hal.hpp"
#include "file_path.hpp"
#include "message.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <stdio.h>
using namespace portapack;
using namespace modems;
using namespace ui;
#if SSTVRX_ENABLE_LOGGER
#define SSTVRX_LOG_INFO(msg) \
do { \
if (logger) { \
logger->log_info(msg); \
} \
} while (0)
#define SSTVRX_LOG_ERROR(msg) \
do { \
if (logger) { \
logger->log_error(msg); \
} \
} while (0)
#else
#define SSTVRX_LOG_INFO(msg) \
do { \
(void)sizeof(msg); \
} while (0)
#define SSTVRX_LOG_ERROR(msg) \
do { \
(void)sizeof(msg); \
} while (0)
#endif
// SSTV RX View Implementation
namespace ui::external_app::sstvrx {
static_assert(sizeof(shared_memory.bb_data.data) == 512,
"SSTV shared buffer size mismatch");
#if SSTVRX_ENABLE_LOGGER
void SstvRxLogger::log_error(const std::string& error_message) {
log_file.write_entry(rtc_time::now(), "ERROR: " + error_message);
}
void SstvRxLogger::log_info(const std::string& info_message) {
log_file.write_entry(rtc_time::now(), "INFO: " + info_message);
}
#endif
SstvRxView::SstvRxView(ui::NavigationView& nav)
: nav_(nav) {
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
DISPLAY_HEIGHT = screen_height - SSTV_IMG_START_ROW * 16 - 16;
DISPLAY_WIDTH = screen_width;
add_children({&field_rf_amp,
&field_lna,
&field_vga,
&rssi,
&channel,
&field_frequency,
&field_volume,
&audio,
&start_stop_btn,
&options_mode,
&field_phase,
&field_slant,
&labels,
&text_calibration});
// Initialize audio with proper rate for SSTV
audio::set_rate(audio::Rate::Hz_48000);
audio::output::start();
// Configure receiver with optimal settings for SSTV
// NOTE: Do NOT set modulation mode - SSTV uses a custom baseband processor
// Standard sampling rate (3.072MHz) with wide bandwidth to capture full SSTV audio spectrum
// SSTV uses 1200-2300 Hz tones, so we need wide baseband to avoid distortion
receiver_model.set_sampling_rate(3072000);
receiver_model.set_baseband_bandwidth(1750000); // Standard wideband setting
receiver_model.set_squelch_level(1);
receiver_model.set_hidden_offset(0); // No offset needed
// Field values will be set in on_show() to ensure proper initialization
using option_t = std::pair<std::string, int32_t>;
using options_t = std::vector<option_t>;
options_t mode_options;
uint32_t c;
// Start/Stop button handler - toggles between start and stop
start_stop_btn.on_select = [this](Button&) {
start_stop_btn.focus();
on_start_stop();
};
// Initialize frequency field from settings or use default
if (settings_.loaded() && settings_.raw().rx_frequency != 0) {
field_frequency.set_value(settings_.raw().rx_frequency);
} else if (field_frequency.value() == 0) {
field_frequency.set_value(145800000); // Default to 145.800 MHz (ISS)
}
field_frequency.set_step(25000);
// Populate mode list
for (c = 0; c < SSTV_MODES_NB; c++)
mode_options.emplace_back(sstv_modes[c].name, c);
options_mode.set_options(mode_options);
options_mode.on_change = [this](size_t i, int32_t) {
this->on_mode_changed(i);
};
options_mode.set_selected_index(1); // Scottie 2
on_mode_changed(1);
// Initialize phase and slant controls from loaded settings
field_phase.set_value(phase_adjustment);
field_phase.on_change = [this](int32_t v) {
phase_adjustment = v;
if (is_receiving) {
baseband::set_sstvrx_phase_slant(phase_adjustment, slant_adjustment);
} else if (max_received_line > 0) {
// Auto-redraw when adjusting after reception
redraw_image();
}
};
field_slant.set_value(slant_adjustment);
field_slant.on_change = [this](int32_t v) {
slant_adjustment = v;
if (is_receiving) {
baseband::set_sstvrx_phase_slant(phase_adjustment, slant_adjustment);
} else if (max_received_line > 0) {
// Auto-redraw when adjusting after reception
redraw_image();
}
};
#if SSTVRX_ENABLE_LOGGER
logger = std::make_unique<SstvRxLogger>();
if (logger) {
logger->append(logs_dir / "SSTVRX.txt");
logger->log_info("----------SSTV RX Started----------");
}
#endif
}
// Destructor: Ensure reception is stopped
SstvRxView::~SstvRxView() {
is_receiving = true;
on_stop();
baseband::shutdown();
SSTVRX_LOG_INFO("SSTV RX Stopped");
}
void SstvRxView::on_show() {
// Update field values from receiver model to reflect loaded settings
field_lna.set_value(receiver_model.lna());
field_vga.set_value(receiver_model.vga());
field_rf_amp.set_value(receiver_model.rf_amp());
field_volume.set_value(receiver_model.normalized_headphone_volume());
}
void SstvRxView::focus() {
field_frequency.focus();
}
// Combined start/stop handler - toggles based on current state
void SstvRxView::on_start_stop() {
if (is_receiving) {
// Currently receiving - stop it
on_stop();
start_stop_btn.set_text("Start RX");
} else {
// Currently stopped - start reception
SSTVRX_LOG_INFO("Starting SSTV RX Reception");
start_audio();
start_stop_btn.set_text("Stop RX");
}
}
// Stop NFM audio reception
void SstvRxView::on_stop() {
SSTVRX_LOG_INFO("Stopping SSTV RX Reception");
if (is_receiving) {
// Stop in reverse order of start
receiver_model.disable();
audio::output::stop();
// Reset state
is_receiving = false;
// Close image file if still open
bmp.close();
pending_line_valid = false;
pending_chunk_mask = 0;
std::fill(pending_line_rgb.begin(), pending_line_rgb.end(), 0);
*reinterpret_cast<volatile uint8_t*>(&shared_memory.bb_data.data[CHUNK_FLAG_INDEX]) = 0;
SSTVRX_LOG_INFO("SSTV RX Reception Stopped");
} else {
SSTVRX_LOG_ERROR("SSTV RX Reception Not Running");
}
}
// Start NFM audio reception
void SstvRxView::start_audio() {
SSTVRX_LOG_INFO("Configuring SSTV RX Audio Reception");
// Configure the baseband processor with VIS code
if (rx_sstv_mode) {
baseband::set_sstvrx_data(rx_sstv_mode->vis_code);
SSTVRX_LOG_INFO("Sent VIS code to processor: " + to_string_dec_uint(rx_sstv_mode->vis_code));
}
// Send phase and slant adjustments
baseband::set_sstvrx_phase_slant(phase_adjustment, slant_adjustment);
// Initialize audio path
audio::output::stop();
audio::set_rate(audio::Rate::Hz_48000);
// Set audio routing and volume
// audio::output::start();
// Clear display area and reset line counter
portapack::display.fill_rectangle(
{0, SSTV_IMG_START_ROW * 16, DISPLAY_WIDTH, DISPLAY_HEIGHT},
{0, 0, 0});
line_num = 0;
file_line_num = 0;
max_received_line = 0;
pending_line_valid = false;
pending_chunk_mask = 0;
std::fill(pending_line_rgb.begin(), pending_line_rgb.end(), 0);
*reinterpret_cast<volatile uint8_t*>(&shared_memory.bb_data.data[CHUNK_FLAG_INDEX]) = 0;
// Clear calibration display
text_calibration.set("Calibrating...");
// Initialize new image file
current_line_rx = 0;
auto timestamp = to_string_timestamp(rtc_time::now());
auto dir_error = ensure_directory(sstv_dir / "RX");
if (!dir_error.ok()) {
SSTVRX_LOG_ERROR("Failed to create directory: SSTV/RX");
}
current_image_path = sstv_dir / ("RX/SSTV_" + timestamp + ".bmp");
auto ok = bmp.create(current_image_path, IMAGE_WIDTH, 1);
if (!ok) {
SSTVRX_LOG_ERROR("Failed to create file: " + current_image_path.string());
bmp.close();
}
// Start audio output
audio::output::start();
audio::headphone::set_volume(persistent_memory::headphone_volume());
// Keep ReceiverModel in capture mode so it doesn't override our custom baseband/audio configuration.
receiver_model.set_modulation(ReceiverModel::Mode::Capture);
// Enable receiver last
receiver_model.enable();
is_receiving = true;
SSTVRX_LOG_INFO("SSTV RX Started");
}
void SstvRxView::on_mode_changed(const size_t index) {
rx_sstv_mode = &sstv_modes[index];
}
void SstvRxView::write_line_to_file(uint16_t line_num, const uint8_t* rgb_line) {
(void)line_num;
if (!bmp.is_loaded()) return;
// Ensure BMP height is sufficient
if (bmp.get_real_height() <= file_line_num) {
bmp.expand_y(file_line_num + 1);
}
bmp.seek(0, file_line_num);
// Write RGB data in BGR order
for (uint16_t x = 0; x < IMAGE_WIDTH; x++) {
uint8_t r = rgb_line[x * 3 + 0];
uint8_t g = rgb_line[x * 3 + 1];
uint8_t b = rgb_line[x * 3 + 2];
Color px(g, b, r);
bmp.write_next_px(px);
}
file_line_num++;
}
void SstvRxView::update_display(uint16_t current_line, const uint8_t* rgb_line) {
if (current_line >= IMAGE_HEIGHT) return;
// Reset line counter if we reach the bottom of display
if (line_num >= DISPLAY_HEIGHT) {
line_num = 0;
}
// Scale line to display width
for (uint16_t x = 0; x < DISPLAY_WIDTH; x++) {
// Scale x coordinate
uint16_t src_x = (x * IMAGE_WIDTH) / DISPLAY_WIDTH;
if (src_x >= IMAGE_WIDTH) continue;
// Get RGB values from interleaved data [R,G,B,R,G,B,...]
uint8_t r = rgb_line[src_x * 3 + 0];
uint8_t g = rgb_line[src_x * 3 + 1];
uint8_t b = rgb_line[src_x * 3 + 2];
// Display uses BGR order like BMP format
// line_buffer[x] = Color(b, r, g);
line_buffer[x] = Color(g, b, r);
}
// Render the line at the current position
portapack::display.render_line(
{0, line_num + SSTV_IMG_START_ROW * 16},
DISPLAY_WIDTH,
line_buffer);
// Increment line counter
line_num++;
}
void SstvRxView::redraw_image() {
// Disabled: Post-reception redraw requires 245KB buffer which exceeds M0 memory
// Phase and slant adjustments must be set before reception starts
}
void SstvRxView::on_progress(uint16_t line, uint16_t total_lines) {
if (!is_receiving) {
if (line < 0xFFF0) {
*reinterpret_cast<volatile uint8_t*>(&shared_memory.bb_data.data[CHUNK_FLAG_INDEX]) = 0;
}
return;
}
// Handle debug messages
if (line == 0xFFFF) {
SSTVRX_LOG_ERROR("Processor not configured");
return;
}
if (line == 0xFFFE) {
SSTVRX_LOG_INFO("Sync pulse duration: " + to_string_dec_uint(total_lines) + " samples");
return;
}
if (line == 0xFFFD) {
SSTVRX_LOG_INFO("Sync detected, count=" + to_string_dec_uint(total_lines));
text_calibration.set("Syncs: " + to_string_dec_uint(total_lines));
return;
}
if (line == 0xFFFC) {
SSTVRX_LOG_INFO("Expected interval: " + to_string_dec_uint(total_lines) + " samples");
return;
}
if (line == 0xFFFB) {
SSTVRX_LOG_INFO("Actual interval: " + to_string_dec_uint(total_lines) + " samples");
return;
}
if (line == 0xFFFA) {
SSTVRX_LOG_INFO("SYNC TIMEOUT after " + to_string_dec_uint(total_lines) + " samples - continuing without sync");
return;
}
if (line == 0xFFF9) {
SSTVRX_LOG_INFO("Detected frequency at sync: " + to_string_dec_uint(total_lines) + " Hz");
return;
}
if (line == 0xFFF8) {
SSTVRX_LOG_INFO("OUTLIER REJECTED: interval=" + to_string_dec_uint(total_lines) + " samples (expected 10000-15000)");
return;
}
if (line == 0xFFF7) {
SSTVRX_LOG_INFO("PRE-RECORD: sync_history_count=" + to_string_dec_uint(total_lines));
return;
}
if (line == 0xFFF6) {
SSTVRX_LOG_INFO("MAX_SYNC_HISTORY EXCEEDED: count=" + to_string_dec_uint(total_lines));
return;
}
if (line == 0xFFF5) {
// Decode rejection reason bit flags: 0x1=interval, 0x2=freq, 0x4=duration
std::string reasons = "";
if (total_lines & 0x1) reasons += "interval ";
if (total_lines & 0x2) reasons += "freq ";
if (total_lines & 0x4) reasons += "duration ";
if (reasons.empty()) reasons = "unknown";
SSTVRX_LOG_INFO("FALSE SYNC PAIR REJECTED on Line 0: " + reasons);
return;
}
if (line == 0xFFF4) {
SSTVRX_LOG_INFO("STARTING LINE 0 DECODE after sync_sample_count=" + to_string_dec_uint(total_lines));
return;
}
std::array<uint8_t, CHUNK_COPY_BYTES> chunk{};
memcpy(chunk.data(), shared_memory.bb_data.data, chunk.size());
*reinterpret_cast<volatile uint8_t*>(&shared_memory.bb_data.data[CHUNK_FLAG_INDEX]) = 0;
const uint16_t line_num_encoded = chunk[0] | (chunk[1] << 8);
const bool is_second_chunk = (line_num_encoded & 1) == 1;
const uint16_t actual_line_num = line_num_encoded / 2;
if (actual_line_num >= IMAGE_HEIGHT) {
return;
}
const bool multi_chunk_line = PIXELS_PER_LINE > MAX_CHUNK_PIXELS;
if (!pending_line_valid || pending_line_number != actual_line_num) {
pending_line_number = actual_line_num;
pending_line_valid = true;
pending_chunk_mask = 0;
std::fill(pending_line_rgb.begin(), pending_line_rgb.end(), 0);
}
const uint16_t chunk_pixels = multi_chunk_line
? (is_second_chunk ? (PIXELS_PER_LINE - MAX_CHUNK_PIXELS) : MAX_CHUNK_PIXELS)
: PIXELS_PER_LINE;
const uint16_t dest_pixel_offset = (multi_chunk_line && is_second_chunk) ? MAX_CHUNK_PIXELS : 0;
const uint16_t chunk_bytes = chunk_pixels * 3;
const uint16_t max_copy_bytes = static_cast<uint16_t>(chunk.size() > CHUNK_HEADER_BYTES ? (chunk.size() - CHUNK_HEADER_BYTES) : 0);
const uint16_t bytes_to_copy = (chunk_bytes < max_copy_bytes) ? chunk_bytes : max_copy_bytes;
const uint16_t dest_byte_offset = dest_pixel_offset * 3;
if (bytes_to_copy > 0 && (dest_byte_offset + bytes_to_copy) <= pending_line_rgb.size()) {
memcpy(pending_line_rgb.data() + dest_byte_offset, chunk.data() + CHUNK_HEADER_BYTES, bytes_to_copy);
}
const uint8_t chunk_bit = (multi_chunk_line && is_second_chunk) ? 0x2 : 0x1;
pending_chunk_mask |= chunk_bit;
const uint8_t required_mask = multi_chunk_line ? 0x3 : 0x1;
if (pending_chunk_mask != required_mask) {
return;
}
pending_line_valid = false;
pending_chunk_mask = 0;
current_line_rx = actual_line_num;
if (actual_line_num < IMAGE_HEIGHT) {
write_line_to_file(actual_line_num, pending_line_rgb.data());
update_display(actual_line_num, pending_line_rgb.data());
max_received_line = max_received_line > (actual_line_num + 1) ? max_received_line : (actual_line_num + 1);
}
#if SSTVRX_ENABLE_LOGGER
if (logger && (actual_line_num % 10 == 0)) {
logger->log_info("Line " + to_string_dec_uint(actual_line_num) + "/" + to_string_dec_uint(total_lines));
}
#endif
// if (actual_line_num >= (total_lines - 1)) { //don't auto finish image upon end, user need to manually stop. this method is not reliable enough.
// finish_image();
// }
}
void SstvRxView::finish_image() {
bmp.close();
SSTVRX_LOG_INFO("Image completed: " + current_image_path.string());
}
void SstvRxView::on_calibration(int16_t suggested_phase, int16_t suggested_slant, uint16_t sync_count) {
if (!is_receiving) return;
// Display calibration suggestions to the user
if (sync_count >= 4) {
std::string cal_text = "Try Slant=" + to_string_dec_int(suggested_slant);
text_calibration.set(cal_text);
text_calibration.set_dirty();
// Don't auto-apply yet - just suggest for now until we verify the values are correct
// User can manually adjust if needed
// Log the suggestion
SSTVRX_LOG_INFO("Calibration suggestion: phase=" + to_string_dec_int(suggested_phase) +
" slant=" + to_string_dec_int(suggested_slant) +
" (from " + to_string_dec_uint(sync_count) + " syncs)");
} else {
// Log that we received calibration but not enough syncs yet
SSTVRX_LOG_INFO("Calibration received: " + to_string_dec_uint(sync_count) + " syncs (need 4+)");
}
}
} // namespace ui::external_app::sstvrx
+196
View File
@@ -0,0 +1,196 @@
/*
* Copyright (C) 2025 StarVore Labs
*
* 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 __SSTVRX_H__
#define __SSTVRX_H__
#include "ui.hpp"
#include "ui_widget.hpp"
#include "ui_receiver.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "ui_freq_field.hpp"
#include "ui_freqman.hpp"
#include "ui_channel.hpp"
#include "baseband_api.hpp"
#include "event_m0.hpp"
#include "message.hpp"
#include "sstv.hpp"
#include "file.hpp"
#include "bmpfile.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "oversample.hpp"
#include "string_format.hpp"
#include "log_file.hpp"
#include "utility.hpp"
#include "audio.hpp"
#include "portapack.hpp"
#include <array>
#include <ch.h>
#ifndef SSTVRX_ENABLE_LOGGER
#define SSTVRX_ENABLE_LOGGER 0
#endif
using namespace sstv;
namespace ui::external_app::sstvrx {
#define FMR_BTNGRID_TOP 60
#if SSTVRX_ENABLE_LOGGER
class SstvRxLogger {
public:
Optional<File::Error> append(const std::filesystem::path& filename) {
return log_file.append(filename);
}
void log_error(const std::string& error_message);
void log_info(const std::string& info_message);
private:
LogFile log_file{};
};
#endif
class SstvRxView : public ui::View {
public:
SstvRxView(ui::NavigationView& nav);
SstvRxView& operator=(const SstvRxView&) = delete;
SstvRxView(const SstvRxView&) = delete;
~SstvRxView();
std::string title() { return "SSTV RX"; }
void focus() override;
void on_show() override;
private:
ui::NavigationView& nav_;
#if SSTVRX_ENABLE_LOGGER
std::unique_ptr<SstvRxLogger> logger{};
#endif
// Phase and slant adjustments (runtime only, not persisted)
int16_t phase_adjustment{0}; // Horizontal offset in pixels (-50 to +50)
int16_t slant_adjustment{0}; // Timing adjustment in 0.1% units (-100 to +100)
// Settings must be declared before UI controls
app_settings::SettingsManager settings_{
"rx_sstv",
app_settings::Mode::RX};
ReceiverModel::Mode receiver_mode = ReceiverModel::Mode::WidebandFMAudio;
AudioSpectrum* audio_spectrum_data{nullptr};
int16_t audio_spectrum[128]{0};
RxRadioState radio_state_{};
audio::Rate audio_sampling_rate = audio::Rate::Hz_48000;
uint8_t radio_bw = 0;
bool is_receiving = false;
const sstv_mode* rx_sstv_mode{};
// Image data storage - only store current line to save memory
static constexpr uint16_t IMAGE_WIDTH = 320;
static constexpr uint16_t IMAGE_HEIGHT = 256;
static constexpr uint16_t PIXELS_PER_LINE = 320;
uint16_t DISPLAY_WIDTH = 240; // Scaled display width
uint16_t DISPLAY_HEIGHT = 192; // Scaled display height
static constexpr uint16_t SSTV_IMG_START_ROW = 7; // Start drawing at row 7 (after controls)
static constexpr size_t SHARED_BUFFER_BYTES = 512;
static constexpr size_t CHUNK_FLAG_INDEX = SHARED_BUFFER_BYTES - 1;
static constexpr size_t CHUNK_HEADER_BYTES = 2;
static constexpr size_t CHUNK_COPY_BYTES = CHUNK_FLAG_INDEX; // Exclude flag byte
static constexpr uint16_t MAX_CHUNK_PIXELS = (CHUNK_COPY_BYTES - CHUNK_HEADER_BYTES) / 3;
uint16_t current_line_rx{0};
BMPFile bmp{};
std::filesystem::path current_image_path{};
ui::Color line_buffer[320];
uint16_t line_num{0}, file_line_num{0};
std::array<uint8_t, IMAGE_WIDTH * 3> pending_line_rgb{};
uint16_t pending_line_number{0};
uint8_t pending_chunk_mask{0};
bool pending_line_valid{false};
// Note: Post-reception phase/slant adjustment disabled due to M0 memory constraints
// The 245KB image buffer exceeds available heap memory
uint16_t max_received_line{0};
MessageHandlerRegistration message_handler_progress{
Message::ID::SSTVRXProgress,
[this](const Message* const p) {
const auto message = *reinterpret_cast<const SSTVRXProgressMessage*>(p);
this->on_progress(message.line, message.total_lines);
}};
MessageHandlerRegistration message_handler_calibration{
Message::ID::SSTVRXCalibration,
[this](const Message* const p) {
const auto message = *reinterpret_cast<const SSTVRXCalibrationMessage*>(p);
this->on_calibration(message.suggested_phase, message.suggested_slant, message.sync_count);
}};
// UI Elements
RFAmpField field_rf_amp{{UI_POS_X(13), UI_POS_Y(0)}};
LNAGainField field_lna{{UI_POS_X(15), UI_POS_Y(0)}};
VGAGainField field_vga{{UI_POS_X(18), UI_POS_Y(0)}};
RSSI rssi{{UI_POS_X(21), 0, UI_POS_WIDTH_REMAINING(24), 4}};
Channel channel{{UI_POS_X(21), 5, UI_POS_WIDTH_REMAINING(24), 4}};
RxFrequencyField field_frequency{{UI_POS_X(0), UI_POS_Y(0)}, nav_};
AudioVolumeField field_volume{{UI_POS_X_RIGHT(2), UI_POS_Y(0)}};
OptionsField options_mode{{UI_POS_X(6), UI_POS_Y(1)}, 16, {}};
NumberField field_phase{{UI_POS_X(4), UI_POS_Y(2)}, 3, {-50, 50}, 1, ' '};
NumberField field_slant{{UI_POS_X(13), UI_POS_Y(2)}, 4, {-100, 100}, 1, ' '};
Labels labels{
{{UI_POS_X(1), UI_POS_Y(1)}, "Mode:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(1), UI_POS_Y(2)}, "Ph:", Theme::getInstance()->fg_light->foreground},
{{UI_POS_X(8), UI_POS_Y(2)}, "Slnt:", Theme::getInstance()->fg_light->foreground}};
Audio audio{{UI_POS_X(21), 10, UI_POS_WIDTH(6), 4}};
ui::Button start_stop_btn{{UI_POS_X_RIGHT(12), UI_POS_Y(3), UI_POS_WIDTH(11), UI_POS_HEIGHT(2)}, "Start RX"};
// ui::Button redraw_btn{{16 * 8, UI_POS_Y(5), UI_POS_WIDTH(12), UI_POS_HEIGHT(3)}, "Redraw"};
// Calibration suggestion display
Text text_calibration{
{UI_POS_X(1), UI_POS_Y(3), UI_POS_WIDTH(17), UI_POS_HEIGHT(1)},
"Calib: N/A"};
void on_audio_spectrum();
void update_display(uint16_t line_num, const uint8_t* rgb_line);
void redraw_image(); // Disabled due to memory constraints
void start_audio();
void on_start_stop(); // Combined start/stop handler
void on_stop();
void on_mode_changed(const size_t index);
void on_progress(uint16_t line, uint16_t total_lines);
void on_calibration(int16_t suggested_phase, int16_t suggested_slant, uint16_t sync_count);
void write_bmp_header();
void write_line_to_file(uint16_t line_num, const uint8_t* rgb_line);
void finish_image();
};
} // namespace ui::external_app::sstvrx
#endif // __SSTVRX_H__
+81
View File
@@ -0,0 +1,81 @@
/*
* Copyright (C) 2026 HTotoo
*
* 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_subcar.hpp"
#include "ui_navigation.hpp"
#include "external_app.hpp"
namespace ui::external_app::subcarrx {
void initialize_app(ui::NavigationView& nav) {
nav.push<SubCarView>();
}
} // namespace ui::external_app::subcarrx
extern "C" {
__attribute__((section(".external_app.app_subcarrx.application_information"), used)) application_information_t _application_information_subcarrx = {
/*.memory_location = */ (uint8_t*)0x00000000,
/*.externalAppEntry = */ ui::external_app::subcarrx::initialize_app,
/*.header_version = */ CURRENT_HEADER_VERSION,
/*.app_version = */ VERSION_MD5,
/*.app_name = */ "SubCar",
/*.bitmap_data = */ {
0xC0,
0x03,
0xE0,
0x07,
0x30,
0x0C,
0x30,
0x0C,
0x30,
0x0C,
0x30,
0x0C,
0xE0,
0x07,
0xC0,
0x03,
0x80,
0x01,
0x80,
0x01,
0x80,
0x01,
0x80,
0x01,
0x80,
0x07,
0x80,
0x03,
0x80,
0x07,
0x80,
0x01,
},
/*.icon_color = */ ui::Color::orange().v,
/*.menu_location = */ app_location_t::RX,
/*.desired_menu_position = */ -1,
/*.m4_app_tag = portapack::spi_flash::image_tag_acars */ {'P', 'S', 'C', 'D'},
/*.m4_app_offset = */ 0x00000000, // will be filled at compile time
};
}
+459
View File
@@ -0,0 +1,459 @@
/*
* Copyright (C) 2026 HTotoo
*
* 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_subcar.hpp"
#include "audio.hpp"
#include "baseband_api.hpp"
#include "string_format.hpp"
#include "file_path.hpp"
#include "portapack_persistent_memory.hpp"
using namespace portapack;
using namespace ui;
namespace ui::external_app::subcarrx {
std::string SubCarRecentEntry::to_csv() {
std::string csv = ";";
csv += SubCarView::getSensorTypeName((FPROTO_SUBCAR_SENSOR)sensorType);
csv += ";" + to_string_dec_uint(bits) + ";";
csv += to_string_hex(data, 64 / 4) + ";" + to_string_hex(data2, 64 / 4);
return csv;
}
void SubCarLogger::log_data(SubCarRecentEntry& data) {
log_file.write_entry(data.to_csv());
}
void SubCarRecentEntryDetailView::update_data() {
// process protocol data
parseProtocol();
// set text elements
text_type.set(SubCarView::getSensorTypeName((FPROTO_SUBCAR_SENSOR)entry_.sensorType));
text_id.set("0x" + to_string_hex(serial));
if (entry_.bits > 0) console.writeln("Bits: " + to_string_dec_uint(entry_.bits));
if (!btn.empty()) console.writeln("Btn: " + btn);
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_.data2 != 0) console.writeln("Data2: " + to_string_hex(entry_.data2));
}
SubCarRecentEntryDetailView::SubCarRecentEntryDetailView(NavigationView& nav, const SubCarRecentEntry& entry)
: nav_{nav},
entry_{entry} {
add_children({&button_done,
&text_type,
&text_id,
&console,
&labels});
button_done.on_select = [&nav](const ui::Button&) {
nav.pop();
};
update_data();
}
void SubCarRecentEntryDetailView::focus() {
button_done.focus();
}
void SubCarView::focus() {
field_frequency.focus();
}
SubCarView::SubCarView(NavigationView& nav)
: nav_{nav} {
add_children({&rssi,
&channel,
&field_rf_amp,
&field_lna,
&field_vga,
&field_frequency,
&button_clear_list,
&check_log,
&labels,
&recent_entries_view});
baseband::run_prepared_image(portapack::memory::map::m4_code.base());
logger = std::make_unique<SubCarLogger>();
button_clear_list.on_select = [this](Button&) {
recent.clear();
recent_entries_view.set_dirty();
};
field_frequency.set_step(10000);
check_log.on_select = [this](Checkbox&, bool v) {
logging = v;
if (logger && logging) {
logger->append(logs_dir.string() + "/SubCarLOG_" + to_string_timestamp(rtc_time::now()) + ".CSV");
logger->write_header();
}
};
check_log.set_value(logging);
const Rect content_rect{0, header_height, screen_width, screen_height - header_height};
recent_entries_view.set_parent_rect(content_rect);
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();
signal_token_tick_second = rtc_time::signal_tick_second += [this]() {
on_tick_second();
};
}
void SubCarView::on_tick_second() {
for (auto& entry : recent) {
entry.inc_age(1);
}
recent_entries_view.set_dirty();
}
void SubCarView::on_data(const SubCarDataMessage* data) {
SubCarRecentEntry key{data->sensorType, data->data, data->data2, data->bits};
if (logger && logging) {
logger->log_data(key);
}
auto matching_recent = find(recent, key.key());
if (matching_recent != std::end(recent)) {
// Found within. Move to front of list, increment counter.
(*matching_recent).reset_age();
recent.push_front(*matching_recent);
recent.erase(matching_recent);
} else {
recent.emplace_front(key);
truncate_entries(recent, 64);
}
recent_entries_view.set_dirty();
}
SubCarView::~SubCarView() {
rtc_time::signal_tick_second -= signal_token_tick_second;
receiver_model.disable();
baseband::shutdown();
}
const char* SubCarView::getSensorTypeName(FPROTO_SUBCAR_SENSOR type) {
switch (type) {
case FPC_SUZUKI:
return "Suzuki";
case FPC_VW:
return "VW";
case FPC_SUBARU:
return "Subaru";
case FPC_KIAV5:
return "Kia V5";
case FPC_KIAV3V4:
return "Kia V3/V4";
case FPC_KIAV2:
return "Kia V2";
case FPC_KIAV1:
return "Kia V1";
case FPC_KIAV0:
return "Kia V0";
case FPC_FORDV0:
return "Ford V0";
case FPC_FIATV0:
return "Fiat V0";
case FPC_BMWV0:
return "BMW V0";
case FPC_Invalid:
default:
return "Unknown";
}
}
std::string SubCarView::pad_string_with_spaces(int snakes) {
std::string paddedStr(snakes, ' ');
return paddedStr;
}
void SubCarView::on_freqchg(int64_t freq) {
field_frequency.set_value(freq);
}
void subaru_decode_count(const uint8_t* KB, uint16_t* count) {
uint8_t lo = 0;
if ((KB[4] & 0x40) == 0)
lo |= 0x01;
if ((KB[4] & 0x80) == 0)
lo |= 0x02;
if ((KB[5] & 0x01) == 0)
lo |= 0x04;
if ((KB[5] & 0x02) == 0)
lo |= 0x08;
if ((KB[6] & 0x01) == 0)
lo |= 0x10;
if ((KB[6] & 0x02) == 0)
lo |= 0x20;
if ((KB[5] & 0x40) == 0)
lo |= 0x40;
if ((KB[5] & 0x80) == 0)
lo |= 0x80;
uint8_t REG_SH1 = (KB[7] << 4) & 0xF0;
if (KB[5] & 0x04)
REG_SH1 |= 0x04;
if (KB[5] & 0x08)
REG_SH1 |= 0x08;
if (KB[6] & 0x80)
REG_SH1 |= 0x02;
if (KB[6] & 0x40)
REG_SH1 |= 0x01;
uint8_t REG_SH2 = ((KB[6] << 2) & 0xF0) | ((KB[7] >> 4) & 0x0F);
uint8_t SER0 = KB[3];
uint8_t SER1 = KB[1];
uint8_t SER2 = KB[2];
uint8_t total_rot = 4 + lo;
for (uint8_t i = 0; i < total_rot; ++i) {
uint8_t t_bit = (SER0 >> 7) & 1;
SER0 = ((SER0 << 1) & 0xFE) | ((SER1 >> 7) & 1);
SER1 = ((SER1 << 1) & 0xFE) | ((SER2 >> 7) & 1);
SER2 = ((SER2 << 1) & 0xFE) | t_bit;
}
uint8_t T1 = SER1 ^ REG_SH1;
uint8_t T2 = SER2 ^ REG_SH2;
uint8_t hi = 0;
if ((T1 & 0x10) == 0)
hi |= 0x04;
if ((T1 & 0x20) == 0)
hi |= 0x08;
if ((T2 & 0x80) == 0)
hi |= 0x02;
if ((T2 & 0x40) == 0)
hi |= 0x01;
if ((T1 & 0x01) == 0)
hi |= 0x40;
if ((T1 & 0x02) == 0)
hi |= 0x80;
if ((T2 & 0x08) == 0)
hi |= 0x20;
if ((T2 & 0x04) == 0)
hi |= 0x10;
*count = ((hi << 8) | lo) & 0xFFFF;
}
void SubCarRecentEntryDetailView::parseProtocol() {
btn = "";
cnt = SD_NO_CNT;
serial = 0;
if (entry_.sensorType == FPC_Invalid) return;
if (entry_.sensorType == FPC_SUZUKI) {
uint32_t serial_button = (((entry_.data >> 32) & 0xFFF) << 20) | (entry_.data >> 12);
serial = serial_button >> 4;
uint8_t buttonid = serial_button & 0xF;
cnt = (entry_.data >> 44) & 0xFFFF;
btn = to_string_dec_uint(buttonid);
return;
}
if (entry_.sensorType == FPC_VW) {
// uint32_t key_high = (entry_.data >> 32) & 0xFFFFFFFF;
uint32_t key_low = entry_.data & 0xFFFFFFFF;
serial = key_low; // trimmed to 32 bits for VW
uint8_t check = entry_.data2 & 0xFF;
uint8_t btnid = (check >> 4) & 0xF;
switch (btnid) {
case 0x1:
btn = "UNLOCK";
break;
case 0x2:
btn = "LOCK";
break;
case 0x3:
btn = "Un+Lk";
break;
case 0x4:
btn = "TRUNK";
break;
case 0x5:
btn = "Un+Tr";
break;
case 0x6:
btn = "Lk+Tr";
break;
case 0x7:
btn = "Un+Lk+Tr";
break;
case 0x8:
btn = "PANIC";
break;
default:
btn = "Unknown";
break;
}
}
if (entry_.sensorType == FPC_SUBARU) {
uint8_t* data_bytes = (uint8_t*)entry_.data;
serial = ((uint32_t)data_bytes[1] << 16) | ((uint32_t)data_bytes[2] << 8) | data_bytes[3];
uint8_t button = data_bytes[0] & 0x0F;
btn = to_string_dec_uint(button);
uint16_t cnttmp = 0;
subaru_decode_count(data_bytes, &cnttmp);
cnt = cnttmp;
}
if (entry_.sensorType == FPC_KIAV5) {
serial = (uint32_t)(((entry_.data >> 32) & 0x0FFFFFFF) >> 1);
uint8_t button = (entry_.data >> 61) & 0x07;
btn = to_string_dec_uint(button);
cnt = (uint16_t)(entry_.data & 0xFFFF);
}
if (entry_.sensorType == FPC_KIAV3V4) {
// not decrypted!
serial = SD_NO_SERIAL; //(uint32_t)entry_.data;
// uint8_t button = entry_.data2 & 0xFF;
btn = "?"; // to_string_dec_uint(button);
}
if (entry_.sensorType == FPC_KIAV2) {
serial = (uint32_t)((entry_.data >> 20) & 0xFFFFFFFF);
uint8_t button = (uint8_t)((entry_.data >> 16) & 0x0F);
uint16_t raw_count = (uint16_t)((entry_.data >> 4) & 0xFFF);
cnt = ((raw_count >> 4) | (raw_count << 8)) & 0xFFF;
btn = to_string_dec_uint(button);
}
if (entry_.sensorType == FPC_KIAV1) {
serial = (uint32_t)((entry_.data >> 24) & 0xFFFFFFFF);
uint8_t button = (uint8_t)((entry_.data >> 16) & 0xFF);
cnt = (uint8_t)((entry_.data >> 8) & 0xFF);
btn = to_string_dec_uint(button);
}
if (entry_.sensorType == FPC_KIAV0) {
serial = (uint32_t)((entry_.data >> 12) & 0x0FFFFFFF);
uint8_t button = (entry_.data >> 8) & 0x0F;
cnt = (entry_.data >> 40) & 0xFFFF;
btn = to_string_dec_uint(button);
}
if (entry_.sensorType == FPC_FORDV0) {
uint8_t buf[13] = {0};
for (int i = 0; i < 8; ++i) {
buf[i] = (uint8_t)(entry_.data >> (56 - i * 8));
}
buf[8] = (uint8_t)(entry_.data2 >> 8);
buf[9] = (uint8_t)(entry_.data2 & 0xFF);
uint8_t tmp = buf[8];
uint8_t parity = 0;
uint8_t parity_any = (tmp != 0);
while (tmp) {
parity ^= (tmp & 1);
tmp >>= 1;
}
buf[11] = parity_any ? parity : 0;
uint8_t xor_byte;
uint8_t limit;
if (buf[11]) {
xor_byte = buf[7];
limit = 7;
} else {
xor_byte = buf[6];
limit = 6;
}
for (int idx = 1; idx < limit; ++idx) {
buf[idx] ^= xor_byte;
}
if (buf[11] == 0) {
buf[7] ^= xor_byte;
}
uint8_t orig_b7 = buf[7];
buf[7] = (orig_b7 & 0xAA) | (buf[6] & 0x55);
uint8_t mixed = (buf[6] & 0xAA) | (orig_b7 & 0x55);
buf[12] = mixed;
buf[6] = mixed;
uint32_t serial_le = ((uint32_t)buf[1]) |
((uint32_t)buf[2] << 8) |
((uint32_t)buf[3] << 16) |
((uint32_t)buf[4] << 24);
serial = ((serial_le & 0xFF) << 24) |
(((serial_le >> 8) & 0xFF) << 16) |
(((serial_le >> 16) & 0xFF) << 8) |
((serial_le >> 24) & 0xFF);
uint8_t button = (buf[5] >> 4) & 0x0F;
cnt = ((buf[5] & 0x0F) << 16) |
(buf[6] << 8) |
buf[7];
btn = to_string_dec_uint(button);
}
if (entry_.sensorType == FPC_FIATV0) {
serial = (uint32_t)(entry_.data & 0xFFFFFFFF);
cnt = (uint32_t)((entry_.data >> 32) & 0xFFFFFFFF);
uint8_t button = (uint8_t)(entry_.data2 & 0xFF);
btn = to_string_dec_uint(button);
}
if (entry_.sensorType == FPC_BMWV0) {
serial = (uint32_t)((entry_.data >> 12) & 0x0FFFFFFF);
uint8_t button = (entry_.data >> 8) & 0x0F;
cnt = (entry_.data >> 40) & 0xFFFF;
btn = to_string_dec_uint(button);
}
return;
}
} // namespace ui::external_app::subcarrx
namespace ui {
template <>
void RecentEntriesTable<ui::external_app::subcarrx::SubCarRecentEntries>::draw(
const Entry& entry,
const Rect& target_rect,
Painter& painter,
const Style& style,
ui::RecentEntriesColumns& columns) {
std::string line{};
line.reserve(30);
line = ui::external_app::subcarrx::SubCarView::getSensorTypeName((FPROTO_SUBCAR_SENSOR)entry.sensorType);
line = line + " " + to_string_hex(entry.data << 32);
line.resize(columns.at(0).second, ' ');
std::string ageStr = to_string_dec_uint(entry.age);
std::string bitsStr = to_string_dec_uint(entry.bits);
line += ui::external_app::subcarrx::SubCarView::pad_string_with_spaces(5 - bitsStr.length()) + bitsStr;
line += ui::external_app::subcarrx::SubCarView::pad_string_with_spaces(4 - ageStr.length()) + ageStr;
line.resize(target_rect.width() / 8, ' ');
painter.draw_string(target_rect.location(), style, line);
}
} // namespace ui
+222
View File
@@ -0,0 +1,222 @@
/*
* Copyright (C) 2026 HTotoo
*
* 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.
*/
/*
This and The other files related to this is based on a lot of great people's work. https://github.com/RocketGod-git/ProtoPirate Check the repo, and the credits inside.
*/
#ifndef __UI_SubCar_H__
#define __UI_SubCar_H__
#define SD_NO_SERIAL 0xFFFFFFFF
#define SD_NO_BTN 0xFF
#define SD_NO_CNT 0xFF
#include "ui.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "ui_freq_field.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "utility.hpp"
#include "log_file.hpp"
#include "recent_entries.hpp"
#include "../../baseband/fprotos/subcartypes.hpp"
using namespace ui;
namespace ui::external_app::subcarrx {
struct SubCarRecentEntry {
using Key = uint64_t;
static constexpr Key invalid_key = 0x0fffffff;
uint8_t sensorType = FPC_Invalid;
uint16_t bits = 0;
uint16_t age = 0; // updated on each seconds, show how long the signal was last seen
uint64_t data = 0;
uint64_t data2 = 0;
SubCarRecentEntry() {}
SubCarRecentEntry(
uint8_t sensorType,
uint64_t data = 0,
uint64_t data2 = 0,
uint16_t bits = 0)
: sensorType{sensorType},
bits{bits},
data{data},
data2{data2} {
}
Key key() const {
return (data ^ ((static_cast<uint64_t>(sensorType) & 0xFF) << 0)); // should be optimized...
}
void inc_age(int delta) {
if (UINT16_MAX - delta > age) age += delta;
}
void reset_age() {
age = 0;
}
std::string to_csv();
};
class SubCarLogger {
public:
Optional<File::Error> append(const std::filesystem::path& filename) {
return log_file.append(filename);
}
void log_data(SubCarRecentEntry& data);
void write_header() {
log_file.write_entry(";Type; Bits; Data;");
}
private:
LogFile log_file{};
};
using SubCarRecentEntries = RecentEntries<SubCarRecentEntry>;
using SubCarRecentEntriesView = RecentEntriesView<SubCarRecentEntries>;
class SubCarView : public View {
public:
SubCarView(NavigationView& nav);
~SubCarView();
void focus() override;
std::string title() const override { return "SubCar"; };
static const char* getSensorTypeName(FPROTO_SUBCAR_SENSOR type);
static std::string pad_string_with_spaces(int snakes);
private:
void on_tick_second();
void on_data(const SubCarDataMessage* data);
NavigationView& nav_;
RxRadioState radio_state_{
433'920'000 /* frequency */,
1'750'000 /* bandwidth */,
4'000'000 /* sampling rate */,
ReceiverModel::Mode::AMAudio};
bool logging = false;
app_settings::SettingsManager settings_{
"rx_subcar",
app_settings::Mode::RX,
{
{"log"sv, &logging},
}};
SubCarRecentEntries recent{};
RFAmpField field_rf_amp{
{13 * 8, UI_POS_Y(0)}};
LNAGainField field_lna{
{15 * 8, UI_POS_Y(0)}};
VGAGainField field_vga{
{18 * 8, UI_POS_Y(0)}};
RSSI rssi{
{21 * 8, 0, UI_POS_WIDTH_REMAINING(24), 4}};
Channel channel{
{21 * 8, 5, UI_POS_WIDTH_REMAINING(24), 4},
};
RxFrequencyField field_frequency{
{UI_POS_X(0), UI_POS_Y(0)},
nav_};
SignalToken signal_token_tick_second{};
Button button_clear_list{
{0, 16, 7 * 8, 32},
"Clear"};
Checkbox check_log{
{10 * 8, 18},
3,
"Log",
true};
Labels labels{
{{UI_POS_X_RIGHT(14), UI_POS_Y(1)}, "no fm yet :(", Theme::getInstance()->fg_light->foreground},
};
static constexpr auto header_height = 3 * 16;
std::unique_ptr<SubCarLogger> logger{};
ui::RecentEntriesColumns columns{{
{"Type", 0},
{"Bits", 4},
{"Age", 3},
}};
SubCarRecentEntriesView recent_entries_view{columns, recent};
void on_freqchg(int64_t freq);
MessageHandlerRegistration message_handler_freqchg{
Message::ID::FreqChangeCommand,
[this](Message* const p) {
const auto message = static_cast<const FreqChangeCommandMessage*>(p);
this->on_freqchg(message->freq);
}};
MessageHandlerRegistration message_handler_packet{
Message::ID::SubCarData,
[this](Message* const p) {
const auto message = static_cast<const SubCarDataMessage*>(p);
this->on_data(message);
}};
};
class SubCarRecentEntryDetailView : public View {
public:
SubCarRecentEntryDetailView(NavigationView& nav, const SubCarRecentEntry& entry);
void update_data();
void focus() override;
private:
NavigationView& nav_;
SubCarRecentEntry entry_{};
uint32_t serial = 0;
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}, "?"};
Console console{
{0, 4 * 16, screen_width, 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},
};
Button button_done{
{screen_width - 96 - 4, screen_height - 32 - 12, 96, 32},
"Done"};
void parseProtocol();
};
} // namespace ui::external_app::subcarrx
#endif /*__UI_SubCar_H__*/
+1 -2
View File
@@ -598,8 +598,7 @@ void pause_game() {
joystick.detach();
locate((INFO_LEFT + SCREEN_WIDTH) / 2 - 25, 200);
printf("PAUSED");
while ((get_switches_state().to_ulong() & 0x10) == 0)
;
while ((get_switches_state().to_ulong() & 0x10) == 0);
fillrect(INFO_LEFT, 195, SCREEN_WIDTH, 210, Black);
joystick.attach(&ReadJoystickForFigure, 0.3);
game.attach(&PlayGame, delays[level]);
+1 -1
View File
@@ -99,7 +99,7 @@ class TPMSAppView : public View {
// Prevent painting of region covered entirely by a child.
// TODO: Add flag to View that specifies view does not need to be cleared before painting.
void paint(Painter&) override{};
void paint(Painter&) override {};
void focus() override;
+1 -1
View File
@@ -315,7 +315,7 @@ class File {
template <typename T>
using Result = Result<T, Error>;
File(){};
File() {};
~File();
File(File&& other) {
+1 -2
View File
@@ -361,8 +361,7 @@ class Si5351 {
}
void wait_for_device_ready() {
while (device_status() & 0x80)
;
while (device_status() & 0x80);
}
bool plla_loss_of_signal() {
+1 -1
View File
@@ -114,7 +114,7 @@ Optional<capture_metadata> read_metadata_file(const fs::path& path) {
}
bool parse_float_meta(std::string_view str, float& out_val) {
out_val = {};
out_val = 0.0f;
if (str.size() > max_parse_int_length)
return false;
+3 -6
View File
@@ -322,8 +322,7 @@ static void shutdown_base() {
});
cgu::pll1::enable();
while (!cgu::pll1::is_locked())
;
while (!cgu::pll1::is_locked());
set_clock_config(clock_config_pll1_boot);
@@ -361,15 +360,13 @@ static void set_cpu_clock_speed() {
});
cgu::pll1::enable();
while (!cgu::pll1::is_locked())
;
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--)
;
while (delay--);
set_clock_config(clock_config_pll1);
+27
View File
@@ -265,4 +265,31 @@ uint8_t day_of_week(uint16_t year, uint8_t month, uint8_t day) {
return (day - 1 + (13 * m / 5) + y + (y / 4) - (y / 100) + (y / 400)) % 7;
}
bool isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
time_t rtcToUnixUTC(const rtc::RTC& rtc) {
const uint8_t daysOfMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
uint16_t y = rtc.year();
uint8_t m = rtc.month();
uint8_t d = rtc.day();
uint32_t totalDays = 0;
for (int i = 1970; i < y; i++) {
totalDays += isLeap(i) ? 366 : 365;
}
for (int i = 1; i < m; i++) {
totalDays += daysOfMonth[i];
if (i == 2 && isLeap(y)) {
totalDays++;
}
}
totalDays += (d - 1);
time_t totalSeconds = totalDays * 86400; // 24 * 60 * 60
totalSeconds += rtc.hour() * 3600;
totalSeconds += rtc.minute() * 60;
totalSeconds += rtc.second();
return totalSeconds;
}
} /* namespace rtc_time */
+3
View File
@@ -56,6 +56,9 @@ bool leap_year(uint16_t year);
uint16_t day_of_year(uint16_t year, uint8_t month, uint8_t day);
uint16_t day_of_year_of_nth_weekday(uint16_t year, uint8_t month, uint8_t n, uint8_t weekday);
bool isLeap(int year);
time_t rtcToUnixUTC(const rtc::RTC& rtc);
} /* namespace rtc_time */
#endif /*__RTC_TIME_H__*/
+1 -1
View File
@@ -81,7 +81,7 @@ class AlphanumView : public TextEntryView {
std::array<Button, 29> buttons{};
NewButton button_shift{
{192, 214, screen_width / 5, 38},
{screen_width - screen_width / 5, 214, screen_width / 5, 38},
{},
&bitmap_icon_shift,
Theme::getInstance()->bg_dark->background,
+27
View File
@@ -93,6 +93,33 @@ void FreqManUIList::on_blur() {
set_dirty();
}
bool FreqManUIList::on_touch(const TouchEvent event) {
if (!db_ || db_->empty())
return false;
if (event.type == TouchEvent::Type::Start) {
focus();
set_dirty();
int16_t rel_y = event.point.y() - screen_rect().top();
size_t new_selected = rel_y / char_height;
if (new_selected + start_index_ >= db_->entry_count()) {
return true; // clicked, where there is no entry, skip it
}
// selected_index_ is the current
if (selected_index_ == new_selected) {
// already selected, trigger on_select
if (on_select) {
// on_select(new_selected); //causes strange behavior, not so confident to use it
}
return true;
} else {
// just change selection
selected_index_ = new_selected;
}
return true;
}
return true;
}
bool FreqManUIList::on_keyboard(const KeyboardEvent key) {
if (!db_ || db_->empty())
return false;
+1
View File
@@ -50,6 +50,7 @@ class FreqManUIList : public Widget {
bool on_key(const KeyEvent key) override;
bool on_encoder(EncoderEvent delta) override;
bool on_keyboard(const KeyboardEvent event) override;
bool on_touch(const TouchEvent event) override;
void set_parent_rect(Rect new_parent_rect) override;
+28 -17
View File
@@ -199,7 +199,7 @@ bool GeoMap::on_encoder(const EncoderEvent delta) {
}
}
map_osm_zoom++;
if (has_osm) set_osm_max_zoom();
if (has_osm) set_osm_max_zoom(true);
} else if (delta < 0) {
if (map_zoom > -MAX_MAP_ZOOM_OUT) {
if (map_zoom == 1) {
@@ -212,6 +212,7 @@ bool GeoMap::on_encoder(const EncoderEvent delta) {
}
}
if (map_osm_zoom > 0) map_osm_zoom--;
if (has_osm) set_osm_max_zoom(true);
} else {
return false;
}
@@ -299,8 +300,8 @@ ui::Point GeoMap::item_rect_pixel(GeoMarker& item) {
return {(int16_t)x, (int16_t)y};
}
// osm calculation
double y = lat_to_pixel_y_tile(item.lat, map_osm_zoom) - viewport_top_left_py;
double x = lon_to_pixel_x_tile(item.lon, map_osm_zoom) - viewport_top_left_px;
double y = lat_to_pixel_y_tile(item.lat, map_osm_real_zoom) - viewport_top_left_py;
double x = lon_to_pixel_x_tile(item.lon, map_osm_real_zoom) - viewport_top_left_px;
return {(int16_t)x, (int16_t)y};
}
@@ -327,7 +328,7 @@ int GeoMap::lat2tile(double lat, int zoom) {
return (int)floor((1.0 - log(tan(lat_rad) + 1.0 / cos(lat_rad)) / M_PI) / 2.0 * pow(2.0, zoom));
}
void GeoMap::set_osm_max_zoom() {
void GeoMap::set_osm_max_zoom(bool changeboth) {
if (map_osm_zoom > 20) map_osm_zoom = 20;
for (uint8_t i = map_osm_zoom; i > 0; i--) {
int tile_x = lon2tile(lon_, i);
@@ -335,11 +336,13 @@ void GeoMap::set_osm_max_zoom() {
std::string filename = "/OSM/" + to_string_dec_int(i) + "/" + to_string_dec_int(tile_x) + "/" + to_string_dec_int(tile_y) + ".bmp";
std::filesystem::path file_path(filename);
if (file_exists(file_path)) {
map_osm_zoom = i;
map_osm_real_zoom = i;
if (changeboth) map_osm_zoom = i;
return;
}
}
map_osm_zoom = 0; // should not happen
if (changeboth) map_osm_zoom = 0; // should not happen
map_osm_real_zoom = 0; // should not happen
}
// checks if the tile file presents or not. to determine if we got osm or not
@@ -454,14 +457,22 @@ bool GeoMap::draw_osm_file(int zoom, int tile_x, int tile_y, int relative_x, int
return false;
}
std::vector<ui::Color> line(clip_w);
for (int y = 0; y < clip_h; ++y) {
int source_row = src_y + y;
int dest_row = dest_y + y;
bmp.seek(src_x, source_row);
for (int x = 0; x < clip_w; ++x) {
bmp.read_next_px(line[x], true);
if (bmp.is_bottomup()) {
for (int y = clip_h - 1; y >= 0; --y) {
int source_row = src_y + y;
int dest_row = dest_y + y;
bmp.seek(src_x, source_row);
bmp.read_next_px_cnt(line.data(), clip_w, false);
display.draw_pixels({dest_x + r.left(), dest_row + r.top(), clip_w, 1}, line);
}
} else {
for (int y = 0; y < clip_h; ++y) {
int source_row = src_y + y;
int dest_row = dest_y + y;
bmp.seek(src_x, source_row);
bmp.read_next_px_cnt(line.data(), clip_w, false);
display.draw_pixels({dest_x + r.left(), dest_row + r.top(), clip_w, 1}, line);
}
display.draw_pixels({dest_x + r.left(), dest_row + r.top(), clip_w, 1}, line);
}
return true;
}
@@ -522,8 +533,8 @@ void GeoMap::paint(Painter& painter) {
} else {
// display osm tiles
// Convert center GPS to a global pixel coordinate
double global_center_px = lon_to_pixel_x_tile(lon_, map_osm_zoom);
double global_center_py = lat_to_pixel_y_tile(lat_, map_osm_zoom);
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);
// Find the top-left corner of the screen (viewport) in global pixel coordinates
viewport_top_left_px = global_center_px - (r.width() / 2.0);
@@ -552,7 +563,7 @@ void GeoMap::paint(Painter& painter) {
// For the first tile (x=0, y=0), this will be the negative offset.
int draw_pos_x = round(render_offset_x + x * TILE_SIZE);
int draw_pos_y = round(render_offset_y + y * TILE_SIZE);
if (!draw_osm_file(map_osm_zoom, current_tile_x, current_tile_y, draw_pos_x, draw_pos_y)) {
if (!draw_osm_file(map_osm_real_zoom, current_tile_x, current_tile_y, draw_pos_x, draw_pos_y)) {
// already blanked it.
}
}
@@ -615,7 +626,7 @@ bool GeoMap::on_touch(const TouchEvent event) {
on_move(p.x() / 2.0 * lon_ratio, p.y() / 2.0 * lat_ratio, false);
} else {
p = event.point - screen_rect().location();
on_move(tile_pixel_x_to_lon(p.x() + viewport_top_left_px, map_osm_zoom), tile_pixel_y_to_lat(p.y() + viewport_top_left_py, map_osm_zoom), true);
on_move(tile_pixel_x_to_lon(p.x() + viewport_top_left_px, map_osm_real_zoom), tile_pixel_y_to_lat(p.y() + viewport_top_left_py, map_osm_real_zoom), true);
}
return true;
}
+3 -2
View File
@@ -255,7 +255,7 @@ class GeoMap : public Widget {
void map_read_line_bin(ui::Color* buffer, uint16_t pixels);
// open street map related
uint8_t find_osm_file_tile();
void set_osm_max_zoom();
void set_osm_max_zoom(bool changeboth = false);
bool draw_osm_file(int zoom, int tile_x, int tile_y, int relative_x, int relative_y);
int lon2tile(double lon, int zoom);
int lat2tile(double lat, int zoom);
@@ -263,7 +263,8 @@ class GeoMap : public Widget {
double lat_to_pixel_y_tile(double lat, int zoom);
double tile_pixel_x_to_lon(int x, int zoom);
double tile_pixel_y_to_lat(int y, int zoom);
uint8_t map_osm_zoom{3};
uint8_t map_osm_zoom{5};
uint8_t map_osm_real_zoom{5};
double viewport_top_left_px = 0;
double viewport_top_left_py = 0;
+12
View File
@@ -243,6 +243,18 @@ void MenuView::on_blur() {
item_view(highlighted_item - offset)->unhighlight();
}
bool MenuView::on_touch(const TouchEvent event) {
size_t i = 0;
for (const auto child : children_) {
if (i >= menu_item_views.size()) break;
if (child->screen_rect().contains(event.point)) {
return set_highlighted(i + offset);
}
i++;
}
return false;
}
bool MenuView::on_key(const KeyEvent key) {
switch (key) {
case KeyEvent::Up:
+1
View File
@@ -99,6 +99,7 @@ class MenuView : public View {
bool on_key(const KeyEvent event) override;
bool on_encoder(const EncoderEvent event) override;
bool on_keyboard(const KeyboardEvent event) override;
bool on_touch(const TouchEvent event) override;
private:
void update_items();
+3 -4
View File
@@ -769,9 +769,9 @@ void add_apps(NavigationView& nav, BtnGridView& grid, app_location_t loc) {
}
// clang-format off
void add_external_items(NavigationView& nav, app_location_t location, BtnGridView& grid, uint8_t error_tile_pos) {
void add_external_items(NavigationView& nav, app_location_t location, BtnGridView& grid, uint8_t error_tile_pos, bool show_error_tile ) {
auto externalItems = ExternalItemsMenuLoader::load_external_items(location, nav);
if (externalItems.empty()) {
if (externalItems.empty() && show_error_tile) {
grid.insert_item({"ExtAppErr",
Theme::getInstance()->error_dark->foreground,
nullptr,
@@ -848,8 +848,7 @@ void TranceiversMenuView::on_populate() {
add_items({{"..", Theme::getInstance()->fg_light->foreground, &bitmap_icon_previous, [this]() { nav_.pop(); }}});
}
add_apps(nav_, *this, TRX);
// add_external_items(nav_, app_location_t::TRX, *this, return_icon ? 1 : 0);
// this folder doesn't have external apps, comment to prevent pop the err msg.
add_external_items(nav_, app_location_t::TRX, *this, return_icon ? 1 : 0, false); // this folder doesn't have external apps, so don't show error for it.
// NB: when has external app someday, uncomment this.
}
+1 -1
View File
@@ -61,7 +61,7 @@ using namespace sd_card;
namespace ui {
void add_apps(NavigationView& nav, BtnGridView& grid, app_location_t loc);
void add_external_items(NavigationView& nav, app_location_t location, BtnGridView& grid, uint8_t error_tile_pos);
void add_external_items(NavigationView& nav, app_location_t location, BtnGridView& grid, uint8_t error_tile_pos, bool show_error_tile = true);
bool verify_sdcard_format();
enum modal_t {
+2 -2
View File
@@ -175,7 +175,7 @@ void RecordView::start() {
text_record_filename.set("");
text_record_dropped.set("");
trim_path = {};
trim_path = "";
if (sampling_rate == 0) {
return;
@@ -348,7 +348,7 @@ void RecordView::trim_capture() {
trim_ui.clear();
}
trim_path = {};
trim_path = "";
}
void RecordView::on_gps(const GPSPosDataMessage* msg) {
@@ -59,13 +59,23 @@ static bool report_on_error(BaseSequentialStream* chp, File::Result<uint64_t> er
return false;
}
std::string full_fn_from_args(int argc, char* argv[]) {
std::string full_fn;
for (int i = 0; i < argc; i++) {
if (i != 0)
full_fn += " ";
full_fn += argv[i];
}
return full_fn;
}
void cmd_sd_list_dir(BaseSequentialStream* chp, int argc, char* argv[]) {
if (argc != 1) {
if (argc < 1) {
chprintf(chp, "usage: ls /\r\n");
return;
}
auto path = path_from_string8(argv[0]);
auto path = path_from_string8((char*)full_fn_from_args(argc, argv).c_str());
for (const auto& entry : std::filesystem::directory_iterator(path, "*")) {
if (std::filesystem::is_directory(entry.status())) {
@@ -79,12 +89,12 @@ void cmd_sd_list_dir(BaseSequentialStream* chp, int argc, char* argv[]) {
}
void cmd_sd_unlink(BaseSequentialStream* chp, int argc, char* argv[]) {
if (argc != 1) {
if (argc < 1) {
chprintf(chp, "usage: unlink <path>\r\n");
return;
}
auto path = path_from_string8(argv[0]);
auto path = path_from_string8((char*)full_fn_from_args(argc, argv).c_str());
auto error = delete_file(path);
if (report_on_error(chp, error)) return;
@@ -92,12 +102,12 @@ void cmd_sd_unlink(BaseSequentialStream* chp, int argc, char* argv[]) {
}
void cmd_sd_mkdir(BaseSequentialStream* chp, int argc, char* argv[]) {
if (argc != 1) {
if (argc < 1) {
chprintf(chp, "usage: mkdir <path>\r\n");
return;
}
auto path = path_from_string8(argv[0]);
auto path = path_from_string8((char*)full_fn_from_args(argc, argv).c_str());
if (std::filesystem::is_directory(path)) {
chprintf(chp, "directory already exists.\r\n");
@@ -111,11 +121,11 @@ void cmd_sd_mkdir(BaseSequentialStream* chp, int argc, char* argv[]) {
}
void cmd_sd_filesize(BaseSequentialStream* chp, int argc, char* argv[]) {
if (argc != 1) {
if (argc < 1) {
chprintf(chp, "usage: filesize <path>\r\n");
return;
}
auto path = path_from_string8(argv[0]);
auto path = path_from_string8((char*)full_fn_from_args(argc, argv).c_str());
FILINFO res;
auto stat = f_stat(path.tchar(), &res);
if (report_on_error(chp, stat)) return;
@@ -125,7 +135,7 @@ void cmd_sd_filesize(BaseSequentialStream* chp, int argc, char* argv[]) {
}
void cmd_sd_open(BaseSequentialStream* chp, int argc, char* argv[]) {
if (argc != 1) {
if (argc < 1) {
chprintf(chp, "usage: fopen <path>\r\n");
return;
}
@@ -135,7 +145,7 @@ void cmd_sd_open(BaseSequentialStream* chp, int argc, char* argv[]) {
return;
}
auto path = path_from_string8(argv[0]);
auto path = path_from_string8((char*)full_fn_from_args(argc, argv).c_str());
shell_file = new File();
auto error = shell_file->open(path, false, true);
if (report_on_error(chp, error)) return;
@@ -375,12 +385,12 @@ void cmd_sd_write_binary(BaseSequentialStream* chp, int argc, char* argv[]) {
}
void cmd_sd_crc32(BaseSequentialStream* chp, int argc, char* argv[]) {
if (argc != 1) {
if (argc < 1) {
chprintf(chp, "usage: crc32 <path>\r\n");
return;
}
auto path = path_from_string8(argv[0]);
auto path = path_from_string8((char*)full_fn_from_args(argc, argv).c_str());
File* crc_file = new File();
auto error = crc_file->open(path, true, false);
if (report_on_error(chp, error)) return;
+21
View File
@@ -556,6 +556,13 @@ DeclareTargets(PUSB sd_over_usb)
set(add_to_firmware FALSE)
set(MODE_FLAGS "-O3")
### FLEX RX
set(MODE_CPPSRC
proc_flex.cpp
)
DeclareTargets(PFLX flex)
### ACARS RX
set(MODE_CPPSRC
@@ -644,6 +651,13 @@ set(MODE_CPPSRC
)
DeclareTargets(PSTX sstvtx)
### SSTV RX
set(MODE_CPPSRC
proc_sstvrx.cpp
)
DeclareTargets(PSRX sstvrx)
### TPMS
set(MODE_CPPSRC
@@ -690,6 +704,13 @@ set(MODE_CPPSRC
)
DeclareTargets(PATX audio_tx)
### SubCar Decoders
set(MODE_CPPSRC
proc_subcar.cpp
)
DeclareTargets(PSCD subcar)
### HackRF "factory" firmware
+1 -1
View File
@@ -34,7 +34,7 @@ class BasebandProcessor {
virtual void execute(const buffer_c8_t& buffer) = 0;
virtual void on_message(const Message* const){};
virtual void on_message(const Message* const) {};
protected:
void feed_channel_stats(const buffer_c16_t& channel);
+1 -2
View File
@@ -30,8 +30,7 @@ extern uint32_t __process_stack_end__;
inline uint32_t get_free_stack_space() {
uint32_t* p;
for (p = &__process_stack_base__; *p == CRT0_STACKS_FILL_PATTERN && p < &__process_stack_end__; p++)
;
for (p = &__process_stack_base__; *p == CRT0_STACKS_FILL_PATTERN && p < &__process_stack_end__; p++);
auto stack_space_left = p - &__process_stack_base__;
return stack_space_left;
+169
View File
@@ -0,0 +1,169 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
BMWDecoderStepReset = 0,
BMWDecoderStepCheckPreambula,
BMWDecoderStepSaveDuration,
BMWDecoderStepCheckDuration,
} BMWDecoderStep;
class FProtoSubCarBMWV0 : public FProtoSubCarBase {
public:
FProtoSubCarBMWV0() {
sensorType = FPC_BMWV0;
te_short = 350;
te_long = 700;
te_delta = 120;
min_count_bit_for_found = 61;
}
uint8_t subghz_protocol_bmw_crc8(uint8_t* data, size_t len) {
uint8_t crc = 0x00;
for (size_t i = 0; i < len; i++) {
crc ^= data[i];
for (uint8_t j = 0; j < 8; j++) {
if (crc & 0x80)
crc = (uint8_t)((crc << 1) ^ 0x31);
else
crc <<= 1;
}
}
return crc;
}
uint16_t subghz_protocol_bmw_crc16(uint8_t* data, size_t len) {
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < len; i++) {
crc ^= ((uint16_t)data[i] << 8);
for (uint8_t j = 0; j < 8; j++) {
if (crc & 0x8000)
crc = (crc << 1) ^ 0x1021;
else
crc <<= 1;
}
}
return crc;
}
void subghz_protocol_decoder_bmw_reset_internal() {
decode_data = 0;
decode_count_bit = 0;
decode_data2 = 0;
parser_step = BMWDecoderStepReset;
header_count = 0;
crc_type = 0;
}
void feed(bool level, uint32_t duration) {
switch (parser_step) {
case BMWDecoderStepReset:
if (level && (DURATION_DIFF(duration, te_short) <
te_delta)) {
parser_step = BMWDecoderStepCheckPreambula;
te_last = duration;
header_count = 0;
decode_data = 0;
decode_count_bit = 0;
}
break;
case BMWDecoderStepCheckPreambula:
if (level) {
if ((DURATION_DIFF(duration, te_short) <
te_delta) ||
(DURATION_DIFF(duration, te_long) <
te_delta)) {
te_last = duration;
} else {
parser_step = BMWDecoderStepReset;
}
} else if (
(DURATION_DIFF(duration, te_short) <
te_delta) &&
(DURATION_DIFF(te_last, te_short) <
te_delta)) {
header_count++;
} else if (
(DURATION_DIFF(duration, te_long) <
te_delta) &&
(DURATION_DIFF(te_last, te_long) <
te_delta)) {
if (header_count > 15) {
parser_step = BMWDecoderStepSaveDuration;
decode_data = 0ULL;
decode_count_bit = 0;
} else {
parser_step = BMWDecoderStepReset;
}
} else {
parser_step = BMWDecoderStepReset;
}
break;
case BMWDecoderStepSaveDuration:
if (level) {
if (duration >=
(te_long + te_delta * 2UL)) {
if (decode_count_bit >=
min_count_bit_for_found) {
// instance->generic.data = decode_data;
data_count_bit = decode_count_bit;
// Perform CRC check with both CRC8 and CRC16
uint8_t* raw_bytes = (uint8_t*)decode_data;
size_t raw_len = (decode_count_bit + 7) / 8;
uint8_t crc8 = subghz_protocol_bmw_crc8(raw_bytes, raw_len - 1);
if (crc8 == raw_bytes[raw_len - 1]) {
crc_type = 8;
} else {
uint16_t crc16 = subghz_protocol_bmw_crc16(raw_bytes, raw_len - 2);
uint16_t rx_crc16 = (raw_bytes[raw_len - 2] << 8) | raw_bytes[raw_len - 1];
if (crc16 == rx_crc16) {
crc_type = 16;
} else {
crc_type = 0; // invalid
}
}
if (crc_type != 0 && callback) {
callback(this);
}
}
subghz_protocol_decoder_bmw_reset_internal();
} else {
te_last = duration;
parser_step = BMWDecoderStepCheckDuration;
}
} else {
parser_step = BMWDecoderStepReset;
}
break;
case BMWDecoderStepCheckDuration:
if (!level) {
if ((DURATION_DIFF(te_last, te_short) <
te_delta) &&
(DURATION_DIFF(duration, te_short) <
te_delta)) {
subghz_protocol_blocks_add_bit(0);
parser_step = BMWDecoderStepSaveDuration;
} else if (
(DURATION_DIFF(te_last, te_long) <
te_delta) &&
(DURATION_DIFF(duration, te_long) <
te_delta)) {
subghz_protocol_blocks_add_bit(1);
parser_step = BMWDecoderStepSaveDuration;
} else {
parser_step = BMWDecoderStepReset;
}
} else {
parser_step = BMWDecoderStepReset;
}
break;
}
}
uint16_t header_count = 0;
uint8_t crc_type = 0;
};
+204
View File
@@ -0,0 +1,204 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
FiatV0DecoderStepReset = 0,
FiatV0DecoderStepPreamble = 1,
FiatV0DecoderStepData = 2,
} FiatV0DecoderStep;
class FProtoSubCarFiatV0 : public FProtoSubCarBase {
public:
FProtoSubCarFiatV0() {
sensorType = FPC_FIATV0;
te_short = 200;
te_long = 400;
te_delta = 100;
min_count_bit_for_found = 64;
}
void feed(bool level, uint32_t duration) {
uint32_t gap_threshold = 800;
uint32_t diff;
switch (decoder_state) {
case FiatV0DecoderStepReset:
if (!level) {
return;
}
if (duration < te_short) {
diff = te_short - duration;
} else {
diff = duration - te_short;
}
if (diff < te_delta) {
data_low = 0;
data_high = 0;
decoder_state = FiatV0DecoderStepPreamble;
te_last = duration;
preamble_count = 0;
bit_count = 0;
FProtoGeneral::manchester_advance(
manchester_state,
ManchesterEventReset,
&manchester_state,
NULL);
}
break;
case FiatV0DecoderStepPreamble:
if (level) {
return;
}
if (duration < te_short) {
diff = te_short - duration;
if (diff < te_delta) {
preamble_count++;
te_last = duration;
if (preamble_count >= 0x96) {
if (duration < gap_threshold) {
diff = gap_threshold - duration;
} else {
diff = duration - gap_threshold;
}
if (diff < te_delta) {
decoder_state = FiatV0DecoderStepData;
preamble_count = 0;
data_low = 0;
data_high = 0;
bit_count = 0;
te_last = duration;
return;
}
}
} else {
decoder_state = FiatV0DecoderStepReset;
if (preamble_count >= 0x96) {
if (duration < gap_threshold) {
diff = gap_threshold - duration;
} else {
diff = duration - gap_threshold;
}
if (diff < te_delta) {
decoder_state = FiatV0DecoderStepData;
preamble_count = 0;
data_low = 0;
data_high = 0;
bit_count = 0;
te_last = duration;
return;
}
}
}
} else {
diff = duration - te_short;
if (diff < te_delta) {
preamble_count++;
te_last = duration;
} else {
decoder_state = FiatV0DecoderStepReset;
}
if (preamble_count >= 0x96) {
if (duration >= 799) {
diff = duration - gap_threshold;
} else {
diff = gap_threshold - duration;
}
if (diff < te_delta) {
decoder_state = FiatV0DecoderStepData;
preamble_count = 0;
data_low = 0;
data_high = 0;
bit_count = 0;
te_last = duration;
return;
}
}
}
break;
case FiatV0DecoderStepData:
ManchesterEvent event = ManchesterEventReset;
if (duration < te_short) {
diff = te_short - duration;
if (diff < te_delta) {
event = level ? ManchesterEventShortLow : ManchesterEventShortHigh;
}
} else {
diff = duration - te_short;
if (diff < te_delta) {
event = level ? ManchesterEventShortLow : ManchesterEventShortHigh;
} else {
if (duration < te_long) {
diff = te_long - duration;
} else {
diff = duration - te_long;
}
if (diff < te_delta) {
event = level ? ManchesterEventLongLow : ManchesterEventLongHigh;
}
}
}
if (event != ManchesterEventReset) {
bool data_bit_bool;
if (FProtoGeneral::manchester_advance(
manchester_state,
event,
&manchester_state,
&data_bit_bool)) {
uint32_t new_bit = data_bit_bool ? 1 : 0;
uint32_t carry = (data_low >> 31) & 1;
data_low = (data_low << 1) | new_bit;
data_high = (data_high << 1) | carry;
bit_count++;
if (bit_count == 0x40) {
fix = data_low;
hop = data_high;
data_low = 0;
data_high = 0;
}
if (bit_count > 0x46) {
final_count = bit_count;
endbyte = (uint8_t)data_low;
/*
generic.data = ((uint64_t)hop << 32) | fix;
generic.data_count_bit = 64;
generic.serial = fix;
generic.btn = endbyte; // still exported as btn for UI compatibility
generic.cnt = hop;
*/
decode_data = ((uint64_t)hop << 32) | fix; // this is my own data passer, not the original
decode_data2 = endbyte;
data_count_bit = 64;
if (callback) {
callback(this);
}
data_low = 0;
data_high = 0;
bit_count = 0;
decoder_state = FiatV0DecoderStepReset;
}
}
}
te_last = duration;
break;
}
}
ManchesterState manchester_state = ManchesterStateMid1;
uint8_t decoder_state = 0;
uint16_t preamble_count = 0;
uint32_t data_low = 0;
uint32_t data_high = 0;
uint8_t bit_count = 0;
uint32_t hop = 0;
uint32_t fix = 0;
uint8_t endbyte = 0;
uint8_t final_count = 0;
uint32_t te_last = 0;
};
+151
View File
@@ -0,0 +1,151 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
FordV0DecoderStepReset = 0,
FordV0DecoderStepPreamble,
FordV0DecoderStepPreambleCheck,
FordV0DecoderStepGap,
FordV0DecoderStepData,
} FordV0DecoderStep;
class FProtoSubCarFordV0 : public FProtoSubCarBase {
public:
FProtoSubCarFordV0() {
sensorType = FPC_FORDV0;
te_short = 250;
te_long = 500;
te_delta = 100;
min_count_bit_for_found = 64;
}
void ford_v0_add_bit(bool bit) {
uint32_t low = (uint32_t)data_low;
data_low = (data_low << 1) | (bit ? 1 : 0);
data_high = (data_high << 1) | ((low >> 31) & 1);
bit_count++;
}
bool ford_v0_process_data() {
if (bit_count == 64) {
uint64_t combined = ((uint64_t)data_high << 32) | data_low;
key1 = ~combined;
data_low = 0;
data_high = 0;
return false;
}
if (bit_count == 80) {
uint16_t key2_raw = (uint16_t)(data_low & 0xFFFF);
uint16_t key2 = ~key2_raw;
decode_data = key1;
decode_data2 = key2;
// decode_ford_v0(key1, key2, &serial, &button, &count);
return true;
}
return false;
}
void feed(bool level, uint32_t duration) {
uint32_t gap_threshold = 3500;
switch (parser_step) {
case FordV0DecoderStepReset:
if (level && (DURATION_DIFF(duration, te_short) < te_delta)) {
data_low = 0;
data_high = 0;
parser_step = FordV0DecoderStepPreamble;
te_last = duration;
header_count = 0;
bit_count = 0;
FProtoGeneral::manchester_advance(manchester_state, ManchesterEventReset, &manchester_state, NULL);
}
break;
case FordV0DecoderStepPreamble:
if (!level) {
if (DURATION_DIFF(duration, te_long) < te_delta) {
te_last = duration;
parser_step = FordV0DecoderStepPreambleCheck;
} else {
parser_step = FordV0DecoderStepReset;
}
}
break;
case FordV0DecoderStepPreambleCheck:
if (level) {
if (DURATION_DIFF(duration, te_long) < te_delta) {
header_count++;
te_last = duration;
parser_step = FordV0DecoderStepPreamble;
} else if (DURATION_DIFF(duration, te_short) < te_delta) {
parser_step = FordV0DecoderStepGap;
} else {
parser_step = FordV0DecoderStepReset;
}
}
break;
case FordV0DecoderStepGap:
if (!level && (DURATION_DIFF(duration, gap_threshold) < 250)) {
data_low = 1;
data_high = 0;
bit_count = 1;
parser_step = FordV0DecoderStepData;
} else if (!level && duration > gap_threshold + 250) {
parser_step = FordV0DecoderStepReset;
}
break;
case FordV0DecoderStepData: {
ManchesterEvent event;
if (DURATION_DIFF(duration, te_short) < te_delta) {
event = level ? ManchesterEventShortLow : ManchesterEventShortHigh;
} else if (DURATION_DIFF(duration, te_long) < te_delta) {
event = level ? ManchesterEventLongLow : ManchesterEventLongHigh;
} else {
parser_step = FordV0DecoderStepReset;
break;
}
bool data_bit;
if (FProtoGeneral::manchester_advance(manchester_state, event, &manchester_state, &data_bit)) {
ford_v0_add_bit(data_bit);
if (ford_v0_process_data()) {
/* instance->generic.data = instance->key1;
instance->generic.data_count_bit = 64;
instance->generic.serial = instance->serial;
instance->generic.btn = instance->button;
instance->generic.cnt = instance->count;
*/
data_count_bit = 64;
if (callback) {
callback(this);
}
data_low = 0;
data_high = 0;
bit_count = 0;
parser_step = FordV0DecoderStepReset;
}
}
te_last = duration;
break;
}
}
}
ManchesterState manchester_state = ManchesterStateMid1;
uint64_t data_low = 0;
uint64_t data_high = 0;
uint8_t bit_count = 0;
uint16_t header_count = 0;
uint64_t key1 = 0;
uint16_t key2 = 0;
};
+121
View File
@@ -0,0 +1,121 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
KIADecoderStepReset = 0,
KIADecoderStepCheckPreambula,
KIADecoderStepSaveDuration,
KIADecoderStepCheckDuration,
} KIADecoderStep;
class FProtoSubCarKiaV0 : public FProtoSubCarBase {
public:
FProtoSubCarKiaV0() {
sensorType = FPC_KIAV0;
te_short = 250;
te_long = 500;
te_delta = 100;
min_count_bit_for_found = 61;
}
void feed(bool level, uint32_t duration) {
switch (parser_step) {
case KIADecoderStepReset:
if ((level) && (DURATION_DIFF(duration, te_short) < te_delta)) {
parser_step = KIADecoderStepCheckPreambula;
te_last = duration;
header_count = 0;
}
break;
case KIADecoderStepCheckPreambula:
if (level) {
if ((DURATION_DIFF(duration, te_short) < te_delta) ||
(DURATION_DIFF(duration, te_long) < te_delta)) {
te_last = duration;
} else {
parser_step = KIADecoderStepReset;
}
} else if (
(DURATION_DIFF(duration, te_short) < te_delta) &&
(DURATION_DIFF(te_last, te_short) < te_delta)) {
header_count++;
break;
} else if (
(DURATION_DIFF(duration, te_long) < te_delta) &&
(DURATION_DIFF(te_last, te_long) < te_delta)) {
if (header_count > 15) {
parser_step = KIADecoderStepSaveDuration;
decode_data = 0;
decode_count_bit = 1;
subghz_protocol_blocks_add_bit(1);
// FURI_LOG_I(TAG, "Starting data decode after %u header pulses", header_count);
} else {
parser_step = KIADecoderStepReset;
}
} else {
parser_step = KIADecoderStepReset;
}
break;
case KIADecoderStepSaveDuration:
if (level) {
if (duration >=
(te_long + te_delta * 2UL)) {
// Signal ended too early!
// FURI_LOG_W(TAG, "Signal ended at %u bits (expected 61). Duration: %lu", decode_count_bit, duration);
parser_step = KIADecoderStepReset;
if (decode_count_bit == min_count_bit_for_found) {
// instance->generic.data = decode_data;
data_count_bit = decode_count_bit;
if (callback)
callback(this);
} else {
// FURI_LOG_E(TAG, "Incomplete signal: only %u bits", decode_count_bit);
}
decode_data = 0;
decode_count_bit = 0;
break;
} else {
te_last = duration;
parser_step = KIADecoderStepCheckDuration;
}
} else {
parser_step = KIADecoderStepReset;
}
break;
case KIADecoderStepCheckDuration:
if (!level) {
if ((DURATION_DIFF(te_last, te_short) < te_delta) &&
(DURATION_DIFF(duration, te_short) < te_delta)) {
subghz_protocol_blocks_add_bit(0);
if (decode_count_bit % 10 == 0) {
// FURI_LOG_D(TAG, "Decoded %u bits so far", decode_count_bit);
}
parser_step = KIADecoderStepSaveDuration;
} else if (
(DURATION_DIFF(te_last, te_long) < te_delta) &&
(DURATION_DIFF(duration, te_long) < te_delta)) {
subghz_protocol_blocks_add_bit(1);
if (decode_count_bit % 10 == 0) {
// FURI_LOG_D(TAG, "Decoded %u bits so far", decode_count_bit);
}
parser_step = KIADecoderStepSaveDuration;
} else {
// FURI_LOG_W(TAG, "Timing mismatch at bit %u. Last: %lu, Current: %lu", decode_count_bit, te_last, duration);
parser_step = KIADecoderStepReset;
}
} else {
parser_step = KIADecoderStepReset;
}
break;
}
}
bool is_running = false;
size_t preamble_count = 0;
size_t data_bit_index = 0;
uint8_t last_bit = 0;
bool send_high = false;
uint16_t header_count = 0;
};
+192
View File
@@ -0,0 +1,192 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
KiaV1DecoderStepReset = 0,
KiaV1DecoderStepCheckPreamble,
KiaV1DecoderStepFoundShortLow,
KiaV1DecoderStepCollectRawBits,
} KiaV1DecoderStep;
class FProtoSubCarKiaV1 : public FProtoSubCarBase {
public:
FProtoSubCarKiaV1() {
sensorType = FPC_KIAV1;
te_short = 800;
te_long = 1600;
te_delta = 200;
min_count_bit_for_found = 56;
}
void kia_v1_add_raw_bit(bool bit) {
if (raw_bit_count < 192) {
uint16_t byte_idx = raw_bit_count / 8;
uint8_t bit_idx = 7 - (raw_bit_count % 8);
if (bit) {
raw_bits[byte_idx] |= (1 << bit_idx);
} else {
raw_bits[byte_idx] &= ~(1 << bit_idx);
}
raw_bit_count++;
}
}
inline bool kia_v1_get_raw_bit(uint16_t idx) {
uint16_t byte_idx = idx / 8;
uint8_t bit_idx = 7 - (idx % 8);
return (raw_bits[byte_idx] >> bit_idx) & 1;
}
bool kia_v1_manchester_decode() {
if (raw_bit_count < 113) {
// FURI_LOG_D(TAG, "Not enough raw bits: %u", raw_bit_count);
return false;
}
// Try different offsets to find best alignment (RTL-433 uses -1 bit offset)
uint16_t best_bits = 0;
uint64_t best_data = 0;
// uint16_t best_offset = 0;
for (uint16_t offset = 0; offset < 8; offset++) {
uint64_t data = 0;
uint16_t decoded_bits = 0;
for (uint16_t i = offset; i + 1 < raw_bit_count && decoded_bits < 56; i += 2) {
bool bit1 = kia_v1_get_raw_bit(i);
bool bit2 = kia_v1_get_raw_bit(i + 1);
uint8_t two_bits = (bit1 << 1) | bit2;
// V1 uses: 10=1, 01=0
if (two_bits == 0x02) { // 10 = decoded 1
data = (data << 1) | 1;
decoded_bits++;
} else if (two_bits == 0x01) { // 01 = decoded 0
data = (data << 1);
decoded_bits++;
} else {
break;
}
}
if (decoded_bits > best_bits) {
best_bits = decoded_bits;
best_data = data;
// best_offset = offset;
}
}
// FURI_LOG_I(TAG, "Best: offset=%u bits=%u data=%014llX", best_offset, best_bits, best_data);
decode_data = best_data;
decode_count_bit = best_bits;
return best_bits >= min_count_bit_for_found;
}
void feed(bool level, uint32_t duration) {
switch (parser_step) {
case KiaV1DecoderStepReset:
// Preamble 0xCCCCCCCD produces alternating LONG pulses
if ((level) && (DURATION_DIFF(duration, te_long) <
te_delta)) {
parser_step = KiaV1DecoderStepCheckPreamble;
te_last = duration;
header_count = 1;
}
break;
case KiaV1DecoderStepCheckPreamble:
if (level) {
if (DURATION_DIFF(duration, te_long) <
te_delta) {
te_last = duration;
header_count++;
} else if (
DURATION_DIFF(duration, te_short) <
te_delta) {
te_last = duration;
} else {
parser_step = KiaV1DecoderStepReset;
}
} else {
// LOW pulse
if (DURATION_DIFF(duration, te_long) <
te_delta) {
header_count++;
} else if (
DURATION_DIFF(duration, te_short) <
te_delta) {
// Short LOW - this is the start of sync (0xCD ends: ...long H, short L, short H)
if (header_count > 12) {
parser_step = KiaV1DecoderStepFoundShortLow;
}
} else {
parser_step = KiaV1DecoderStepReset;
}
}
break;
case KiaV1DecoderStepFoundShortLow:
// Expecting SHORT HIGH to complete sync
if (level && (DURATION_DIFF(duration, te_short) <
te_delta)) {
// FURI_LOG_I(TAG, "Sync! hdr=%u", header_count);
parser_step = KiaV1DecoderStepCollectRawBits;
raw_bit_count = 0;
memset(raw_bits, 0, sizeof(raw_bits));
// Add the sync short HIGH as first raw bit
kia_v1_add_raw_bit(true);
} else {
parser_step = KiaV1DecoderStepReset;
}
break;
case KiaV1DecoderStepCollectRawBits:
if (duration > 2400) {
// FURI_LOG_I(TAG, "End! raw_bits=%u", raw_bit_count);
if (kia_v1_manchester_decode()) {
// instance->generic.data = decode_data;
data_count_bit = raw_bit_count / 8;
// Extract fields from 56-bit data per RTL-433:
// Serial: bits 55-24 (32 bits)
// Btn: bits 23-16 (8 bits)
// Count: bits 15-8 (8 bits)
// CRC: bits 7-0 (8 bits)
// instance->generic.serial = (uint32_t)((instance->generic.data >> 24) & 0xFFFFFFFF);
// instance->generic.btn = (uint8_t)((instance->generic.data >> 16) & 0xFF);
// instance->generic.cnt = (uint8_t)((instance->generic.data >> 8) & 0xFF);
if (callback)
callback(this);
}
parser_step = KiaV1DecoderStepReset;
break;
}
int num_bits = 0;
if (DURATION_DIFF(duration, te_short) <
te_delta) {
num_bits = 1;
} else if (
DURATION_DIFF(duration, te_long) <
te_delta) {
num_bits = 2;
} else {
parser_step = KiaV1DecoderStepReset;
break;
}
for (int i = 0; i < num_bits; i++) {
kia_v1_add_raw_bit(level);
}
break;
}
}
uint8_t raw_bits[24]{0};
uint16_t raw_bit_count = 0;
uint16_t header_count = 0;
};
+167
View File
@@ -0,0 +1,167 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
KiaV2DecoderStepReset = 0,
KiaV2DecoderStepCheckPreamble,
KiaV2DecoderStepCollectRawBits,
} KiaV2DecoderStep;
class FProtoSubCarKiaV2 : public FProtoSubCarBase {
public:
FProtoSubCarKiaV2() {
sensorType = FPC_KIAV2;
te_short = 500;
te_long = 1000;
te_delta = 160;
min_count_bit_for_found = 51;
}
void kia_v2_add_raw_bit(bool bit) {
if (raw_bit_count < 160) {
uint16_t byte_idx = raw_bit_count / 8;
uint8_t bit_idx = 7 - (raw_bit_count % 8);
if (bit) {
raw_bits[byte_idx] |= (1 << bit_idx);
} else {
raw_bits[byte_idx] &= ~(1 << bit_idx);
}
raw_bit_count++;
}
}
inline bool kia_v2_get_raw_bit(uint16_t idx) {
uint16_t byte_idx = idx / 8;
uint8_t bit_idx = 7 - (idx % 8);
return (raw_bits[byte_idx] >> bit_idx) & 1;
}
bool kia_v2_manchester_decode() {
if (raw_bit_count < 100) {
return false;
}
uint16_t best_bits = 0;
uint64_t best_data = 0;
for (uint16_t offset = 0; offset < 8; offset++) {
uint64_t data = 0;
uint16_t decoded_bits = 0;
for (uint16_t i = offset; i + 1 < raw_bit_count && decoded_bits < 53; i += 2) {
bool bit1 = kia_v2_get_raw_bit(i);
bool bit2 = kia_v2_get_raw_bit(i + 1);
uint8_t two_bits = (bit1 << 1) | bit2;
if (two_bits == 0x02) {
data = (data << 1) | 1;
decoded_bits++;
} else if (two_bits == 0x01) {
data = (data << 1);
decoded_bits++;
} else {
break;
}
}
if (decoded_bits > best_bits) {
best_bits = decoded_bits;
best_data = data;
}
}
decode_data = best_data;
decode_count_bit = best_bits;
return best_bits >= min_count_bit_for_found;
}
void feed(bool level, uint32_t duration) {
switch (parser_step) {
case KiaV2DecoderStepReset:
if ((level) && (DURATION_DIFF(duration, te_long) < te_delta)) {
parser_step = KiaV2DecoderStepCheckPreamble;
te_last = duration;
header_count = 1;
}
break;
case KiaV2DecoderStepCheckPreamble:
if (level) {
if (DURATION_DIFF(duration, te_long) <
te_delta) {
te_last = duration;
header_count++;
} else if (
DURATION_DIFF(duration, te_short) <
te_delta) {
te_last = duration;
} else {
parser_step = KiaV2DecoderStepReset;
}
} else {
if (DURATION_DIFF(duration, te_long) <
te_delta) {
header_count++;
} else if (
DURATION_DIFF(duration, te_short) <
te_delta) {
if (header_count > 10 &&
DURATION_DIFF(te_last, te_short) <
te_delta) {
parser_step = KiaV2DecoderStepCollectRawBits;
raw_bit_count = 0;
memset(raw_bits, 0, sizeof(raw_bits));
}
} else {
parser_step = KiaV2DecoderStepReset;
}
}
break;
case KiaV2DecoderStepCollectRawBits:
if (duration > 1500) {
if (kia_v2_manchester_decode()) {
/*data = decode_data;
data_count_bit = decode_count_bit;
serial = (uint32_t)((data >> 20) & 0xFFFFFFFF);
btn = (uint8_t)((data >> 16) & 0x0F);
uint16_t raw_count = (uint16_t)((data >> 4) & 0xFFF);
cnt = ((raw_count >> 4) | (raw_count << 8)) & 0xFFF;
*/
data_count_bit = decode_count_bit;
if (callback)
callback(this);
}
parser_step = KiaV2DecoderStepReset;
break;
}
int num_bits = 0;
if (DURATION_DIFF(duration, te_short) <
te_delta) {
num_bits = 1;
} else if (
DURATION_DIFF(duration, te_long) <
te_delta) {
num_bits = 2;
} else {
parser_step = KiaV2DecoderStepReset;
break;
}
for (int i = 0; i < num_bits; i++) {
kia_v2_add_raw_bit(level);
}
break;
}
}
uint8_t raw_bits[20]{0};
uint16_t raw_bit_count = 0;
uint16_t header_count = 0;
};
+185
View File
@@ -0,0 +1,185 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
KiaV3V4DecoderStepReset = 0,
KiaV3V4DecoderStepCheckPreamble,
KiaV3V4DecoderStepCollectRawBits,
} KiaV3V4DecoderStep;
class FProtoSubCarKiaV3V4 : public FProtoSubCarBase {
public:
FProtoSubCarKiaV3V4() {
sensorType = FPC_KIAV3V4;
te_short = 400;
te_long = 800;
te_delta = 150;
min_count_bit_for_found = 64;
}
uint8_t reverse8(uint8_t byte) {
byte = (byte & 0xF0) >> 4 | (byte & 0x0F) << 4;
byte = (byte & 0xCC) >> 2 | (byte & 0x33) << 2;
byte = (byte & 0xAA) >> 1 | (byte & 0x55) << 1;
return byte;
}
void kia_v3_v4_add_raw_bit(bool bit) {
if (raw_bit_count < 256) {
uint16_t byte_idx = raw_bit_count / 8;
uint8_t bit_idx = 7 - (raw_bit_count % 8);
if (bit) {
raw_bits[byte_idx] |= (1 << bit_idx);
} else {
raw_bits[byte_idx] &= ~(1 << bit_idx);
}
raw_bit_count++;
}
}
bool kia_v3_v4_process_buffer() {
if (raw_bit_count < 64) {
return false;
}
uint8_t* b = raw_bits;
// For V3-style (long LOW sync), data is inverted
if (is_v3_sync) {
uint16_t num_bytes = (raw_bit_count + 7) / 8;
for (uint16_t i = 0; i < num_bytes; i++) {
b[i] = ~b[i];
}
}
// Extract fields
// uint32_t encrypted = ((uint32_t)reverse8(b[3]) << 24) | ((uint32_t)reverse8(b[2]) << 16) | ((uint32_t)reverse8(b[1]) << 8) | (uint32_t)reverse8(b[0]);
uint32_t serial = ((uint32_t)reverse8(b[7] & 0xF0) << 24) | ((uint32_t)reverse8(b[6]) << 16) | ((uint32_t)reverse8(b[5]) << 8) | (uint32_t)reverse8(b[4]);
uint8_t btn = (reverse8(b[7]) & 0xF0) >> 4;
decode_data = serial;
decode_count_bit = 64;
decode_data2 = btn;
data_count_bit = decode_count_bit;
if (callback)
callback(this);
// uint8_t our_serial_lsb = serial & 0xFF;
// Decrypt --skipped, no keeloq decoding
/* uint32_t decrypted = keeloq_common_decrypt(encrypted, kia_mf_key);
uint8_t dec_btn = (decrypted >> 28) & 0x0F;
uint8_t dec_serial_lsb = (decrypted >> 16) & 0xFF;
// Validate
if (dec_btn != btn || dec_serial_lsb != our_serial_lsb) {
return false;
}
// Valid decode - version determined by sync type
instance->encrypted = encrypted;
instance->decrypted = decrypted;
instance->generic.serial = serial;
instance->generic.btn = btn;
instance->generic.cnt = decrypted & 0xFFFF;
instance->version = is_v3_sync ? 1 : 0;
uint64_t key_data = ((uint64_t)b[0] << 56) | ((uint64_t)b[1] << 48) | ((uint64_t)b[2] << 40) |
((uint64_t)b[3] << 32) | ((uint64_t)b[4] << 24) | ((uint64_t)b[5] << 16) |
((uint64_t)b[6] << 8) | (uint64_t)b[7];
instance->generic.data = key_data;
instance->generic.data_count_bit = 64;
*/
return true;
}
void feed(bool level, uint32_t duration) {
switch (parser_step) {
case KiaV3V4DecoderStepReset:
if (level && DURATION_DIFF(duration, te_short) <
te_delta) {
parser_step = KiaV3V4DecoderStepCheckPreamble;
te_last = duration;
header_count = 1;
}
break;
case KiaV3V4DecoderStepCheckPreamble:
if (level) {
if (DURATION_DIFF(duration, te_short) <
te_delta) {
te_last = duration;
} else if (duration > 1000 && duration < 1500) {
// V4 style: Sync is LONG HIGH
if (header_count >= 8) {
parser_step = KiaV3V4DecoderStepCollectRawBits;
raw_bit_count = 0;
is_v3_sync = false;
memset(raw_bits, 0, sizeof(raw_bits));
} else {
parser_step = KiaV3V4DecoderStepReset;
}
} else {
parser_step = KiaV3V4DecoderStepReset;
}
} else {
if (duration > 1000 && duration < 1500) {
// V3 style: Sync is LONG LOW
if (header_count >= 8) {
parser_step = KiaV3V4DecoderStepCollectRawBits;
raw_bit_count = 0;
is_v3_sync = true;
memset(raw_bits, 0, sizeof(raw_bits));
} else {
parser_step = KiaV3V4DecoderStepReset;
}
} else if (
DURATION_DIFF(duration, te_short) <
te_delta &&
DURATION_DIFF(te_last, te_short) <
te_delta) {
header_count++;
} else if (duration > 1500) {
parser_step = KiaV3V4DecoderStepReset;
}
}
break;
case KiaV3V4DecoderStepCollectRawBits:
if (level) {
if (duration > 1000 && duration < 1500) {
// Next sync pulse (V4 style) - end this packet
kia_v3_v4_process_buffer();
parser_step = KiaV3V4DecoderStepReset;
} else if (
DURATION_DIFF(duration, te_short) <
te_delta) {
kia_v3_v4_add_raw_bit(false);
} else if (
DURATION_DIFF(duration, te_long) <
te_delta) {
kia_v3_v4_add_raw_bit(true);
} else {
parser_step = KiaV3V4DecoderStepReset;
}
} else {
if (duration > 1000 && duration < 1500) {
// Next sync pulse (V3 style) - end this packet
kia_v3_v4_process_buffer();
parser_step = KiaV3V4DecoderStepReset;
} else if (duration > 1500) {
// Long gap - end of transmission
kia_v3_v4_process_buffer();
parser_step = KiaV3V4DecoderStepReset;
}
}
break;
}
}
bool is_v3_sync = false; // true = V3 (long LOW sync), false = V4 (long HIGH sync)
uint8_t version = 0; // 0 = V4, 1 = V3
uint8_t raw_bits[32]{0};
uint16_t raw_bit_count = 0;
uint16_t header_count = 0;
// uint32_t encrypted;
// uint32_t decrypted;
};
+176
View File
@@ -0,0 +1,176 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
KiaV5DecoderStepReset = 0,
KiaV5DecoderStepCheckPreamble,
KiaV5DecoderStepCollectRawBits,
} KiaV5DecoderStep;
class FProtoSubCarKiaV5 : public FProtoSubCarBase {
public:
FProtoSubCarKiaV5() {
sensorType = FPC_KIAV5;
te_short = 400;
te_long = 800;
te_delta = 150;
min_count_bit_for_found = 64;
}
inline bool kia_v5_get_raw_bit(uint16_t idx) {
uint16_t byte_idx = idx / 8;
uint8_t bit_idx = 7 - (idx % 8);
return (raw_bits[byte_idx] >> bit_idx) & 1;
}
void kia_v5_add_raw_bit(bool bit) {
if (raw_bit_count < 256) {
uint16_t byte_idx = raw_bit_count / 8;
uint8_t bit_idx = 7 - (raw_bit_count % 8);
if (bit) {
raw_bits[byte_idx] |= (1 << bit_idx);
} else {
raw_bits[byte_idx] &= ~(1 << bit_idx);
}
raw_bit_count++;
}
}
bool kia_v5_manchester_decode() {
if (raw_bit_count < 130) {
return false;
}
decode_data = 0;
decode_count_bit = 0;
// Start at offset 2 for proper Manchester alignment
const uint16_t start_bit = 2;
for (uint16_t i = start_bit;
i + 1 < raw_bit_count && decode_count_bit < 64;
i += 2) {
bool bit1 = kia_v5_get_raw_bit(i);
bool bit2 = kia_v5_get_raw_bit(i + 1);
uint8_t two_bits = (bit1 << 1) | bit2;
if (two_bits == 0x01) { // 01 = decoded 1
decode_data = (decode_data << 1) | 1;
decode_count_bit++;
} else if (two_bits == 0x02) { // 10 = decoded 0
decode_data = (decode_data << 1);
decode_count_bit++;
} else {
break;
}
}
return decode_count_bit >= min_count_bit_for_found;
}
void feed(bool level, uint32_t duration) {
switch (parser_step) {
case KiaV5DecoderStepReset:
if ((level) && (DURATION_DIFF(duration, te_short) <
te_delta)) {
parser_step = KiaV5DecoderStepCheckPreamble;
te_last = duration;
header_count = 1;
}
break;
case KiaV5DecoderStepCheckPreamble:
if (level) {
if ((DURATION_DIFF(duration, te_short) <
te_delta) ||
(DURATION_DIFF(duration, te_long) <
te_delta)) {
te_last = duration;
} else {
parser_step = KiaV5DecoderStepReset;
}
} else {
if ((DURATION_DIFF(duration, te_short) <
te_delta) &&
(DURATION_DIFF(te_last, te_short) <
te_delta)) {
header_count++;
} else if (
(DURATION_DIFF(duration, te_long) <
te_delta) &&
(DURATION_DIFF(te_last, te_short) <
te_delta)) {
if (header_count > 40) {
parser_step = KiaV5DecoderStepCollectRawBits;
raw_bit_count = 0;
memset(raw_bits, 0, sizeof(raw_bits));
} else {
header_count++;
}
} else if (
DURATION_DIFF(te_last, te_long) <
te_delta) {
header_count++;
} else {
parser_step = KiaV5DecoderStepReset;
}
}
break;
case KiaV5DecoderStepCollectRawBits:
if (duration > 1200) {
if (kia_v5_manchester_decode()) {
// generic.data = decode_data;
// generic.data_count_bit = decode_count_bit;
data_count_bit = decode_count_bit;
// Compute yek (bit-reverse each byte)
uint64_t yek = 0;
for (int i = 0; i < 8; i++) {
uint8_t byte = (decode_data >> (i * 8)) & 0xFF;
uint8_t reversed = 0;
for (int b = 0; b < 8; b++) {
if (byte & (1 << b))
reversed |= (1 << (7 - b));
}
yek |= ((uint64_t)reversed << ((7 - i) * 8));
}
decode_data = yek;
// Shift serial right by 1 to correct alignment
// generic.serial = (uint32_t)(((yek >> 32) & 0x0FFFFFFF) >> 1);
// generic.btn = (uint8_t)((yek >> 61) & 0x07); // Shift btn too
// generic.cnt = (uint16_t)(yek & 0xFFFF);
if (callback)
callback(this);
}
parser_step = KiaV5DecoderStepReset;
break;
}
int num_bits = 0;
if (DURATION_DIFF(duration, te_short) <
te_delta) {
num_bits = 1;
} else if (
DURATION_DIFF(duration, te_long) <
te_delta) {
num_bits = 2;
} else {
parser_step = KiaV5DecoderStepReset;
break;
}
for (int i = 0; i < num_bits; i++) {
kia_v5_add_raw_bit(level);
}
break;
}
}
uint8_t raw_bits[32]{};
uint16_t raw_bit_count = 0;
uint16_t header_count = 0;
};
+172
View File
@@ -0,0 +1,172 @@
#pragma once
#include "subcarbase.hpp"
#include <cstring>
typedef enum {
SubaruDecoderStepReset = 0,
SubaruDecoderStepCheckPreamble,
SubaruDecoderStepFoundGap,
SubaruDecoderStepFoundSync,
SubaruDecoderStepSaveDuration,
SubaruDecoderStepCheckDuration,
} SubaruDecoderStep;
class FProtoSubCarSubaru : public FProtoSubCarBase {
public:
FProtoSubCarSubaru() {
sensorType = FPC_SUBARU;
te_short = 800;
te_long = 1600;
te_delta = 260;
min_count_bit_for_found = 64;
}
void subghz_protocol_decoder_subaru_reset() {
parser_step = SubaruDecoderStepReset;
te_last = 0;
header_count = 0;
bit_count = 0;
memset(data, 0, sizeof(data));
}
void subaru_add_bit(bool bit) {
if (bit_count < 64) {
uint8_t byte_idx = bit_count / 8;
uint8_t bit_idx = 7 - (bit_count % 8);
if (bit) {
data[byte_idx] |= (1 << bit_idx);
} else {
data[byte_idx] &= ~(1 << bit_idx);
}
bit_count++;
}
}
bool subaru_process_data() {
if (bit_count < 64) {
return false;
}
uint8_t* b = data;
uint64_t key = ((uint64_t)b[0] << 56) | ((uint64_t)b[1] << 48) |
((uint64_t)b[2] << 40) | ((uint64_t)b[3] << 32) |
((uint64_t)b[4] << 24) | ((uint64_t)b[5] << 16) |
((uint64_t)b[6] << 8) | ((uint64_t)b[7]);
decode_data = key;
// uint32_t serial = ((uint32_t)b[1] << 16) | ((uint32_t)b[2] << 8) | b[3];
// uint8_t button = b[0] & 0x0F;
// uint16_t cnt;
// subaru_decode_count(b, &cnt);
data_count_bit = bit_count;
if (callback) {
callback(this);
}
return true;
}
void feed(bool level, uint32_t duration) {
switch (parser_step) {
case SubaruDecoderStepReset:
if (level && DURATION_DIFF(duration, te_long) < te_delta) {
parser_step = SubaruDecoderStepCheckPreamble;
te_last = duration;
header_count = 1;
}
break;
case SubaruDecoderStepCheckPreamble:
if (!level) {
if (DURATION_DIFF(duration, te_long) < te_delta) {
header_count++;
} else if (duration > 2000 && duration < 3500) {
if (header_count > 20) {
parser_step = SubaruDecoderStepFoundGap;
} else {
parser_step = SubaruDecoderStepReset;
}
} else {
parser_step = SubaruDecoderStepReset;
}
} else {
if (DURATION_DIFF(duration, te_long) < te_delta) {
te_last = duration;
header_count++;
} else {
parser_step = SubaruDecoderStepReset;
}
}
break;
case SubaruDecoderStepFoundGap:
if (level && duration > 2000 && duration < 3500) {
parser_step = SubaruDecoderStepFoundSync;
} else {
parser_step = SubaruDecoderStepReset;
}
break;
case SubaruDecoderStepFoundSync:
if (!level && DURATION_DIFF(duration, te_long) < te_delta) {
parser_step = SubaruDecoderStepSaveDuration;
bit_count = 0;
memset(data, 0, sizeof(data));
} else {
parser_step = SubaruDecoderStepReset;
}
break;
case SubaruDecoderStepSaveDuration:
if (level) {
// HIGH pulse duration encodes the bit:
// Short HIGH (~800µs) = 1
// Long HIGH (~1600µs) = 0
if (DURATION_DIFF(duration, te_short) < te_delta) {
// Short HIGH = bit 1
subaru_add_bit(true);
te_last = duration;
parser_step = SubaruDecoderStepCheckDuration;
} else if (DURATION_DIFF(duration, te_long) < te_delta) {
// Long HIGH = bit 0
subaru_add_bit(false);
te_last = duration;
parser_step = SubaruDecoderStepCheckDuration;
} else if (duration > 3000) {
// End of transmission
if (bit_count >= 64) {
subaru_process_data();
}
parser_step = SubaruDecoderStepReset;
} else {
parser_step = SubaruDecoderStepReset;
}
} else {
parser_step = SubaruDecoderStepReset;
}
break;
case SubaruDecoderStepCheckDuration:
if (!level) {
// LOW pulse - just validates timing, doesn't encode bit
if (DURATION_DIFF(duration, te_short) < te_delta ||
DURATION_DIFF(duration, te_long) < te_delta) {
parser_step = SubaruDecoderStepSaveDuration;
} else if (duration > 3000) {
// Gap - end of packet
if (bit_count >= 64) {
subaru_process_data();
}
parser_step = SubaruDecoderStepReset;
} else {
parser_step = SubaruDecoderStepReset;
}
} else {
parser_step = SubaruDecoderStepReset;
}
break;
}
}
uint16_t header_count = 0;
uint8_t data[8];
uint8_t bit_count = 0;
};
+120
View File
@@ -0,0 +1,120 @@
#pragma once
#include "subcarbase.hpp"
#define SUZUKI_GAP_TIME 2000
#define SUZUKI_GAP_DELTA 400
typedef enum {
SuzukiDecoderStepReset = 0,
SuzukiDecoderStepFoundStartPulse,
SuzukiDecoderStepSaveDuration,
} SuzukiDecoderStep;
class FProtoSubCarSuzuki : public FProtoSubCarBase {
public:
FProtoSubCarSuzuki() {
sensorType = FPC_SUZUKI;
te_short = 250;
te_long = 500;
te_delta = 110;
min_count_bit_for_found = 64;
}
void suzuki_add_bit(uint32_t bit) {
uint32_t carry = data_low >> 31;
data_low = (data_low << 1) | bit;
data_high = (data_high << 1) | carry;
data_count_bit++;
}
void subghz_protocol_decoder_suzuki_reset() {
parser_step = SuzukiDecoderStepReset;
header_count = 0;
data_count_bit = 0;
data_low = 0;
data_high = 0;
}
void feed(bool level, uint32_t duration) {
switch (parser_step) {
case SuzukiDecoderStepReset:
// Wait for short HIGH pulse (~250µs) to start preamble
if (!level)
return;
if (DURATION_DIFF(duration, te_short) > te_delta) {
return;
}
data_low = 0;
data_high = 0;
parser_step = SuzukiDecoderStepFoundStartPulse;
header_count = 0;
data_count_bit = 0;
break;
case SuzukiDecoderStepFoundStartPulse:
if (level) {
// HIGH pulse
if (header_count < 257) {
// Still in preamble - just count
return;
}
// After preamble, look for long HIGH to start data
if (DURATION_DIFF(duration, te_long) < te_delta) {
parser_step = SuzukiDecoderStepSaveDuration;
suzuki_add_bit(1);
}
// Ignore short HIGHs after preamble until we see a long one
} else {
// LOW pulse - count as header if short
if (DURATION_DIFF(duration, te_short) < te_delta) {
te_last = duration;
header_count++;
} else {
parser_step = SuzukiDecoderStepReset;
}
}
break;
case SuzukiDecoderStepSaveDuration:
if (level) {
// HIGH pulse - determines bit value
// Long HIGH (~500µs) = 1, Short HIGH (~250µs) = 0
if (DURATION_DIFF(duration, te_long) < te_delta) {
suzuki_add_bit(1);
} else if (DURATION_DIFF(duration, te_short) < te_delta) {
suzuki_add_bit(0);
} else {
parser_step = SuzukiDecoderStepReset;
}
// Stay in this state for next bit
} else {
// LOW pulse - check for gap (end of transmission)
if (DURATION_DIFF(duration, SUZUKI_GAP_TIME) < SUZUKI_GAP_DELTA) {
// Gap found - end of transmission
if (data_count_bit == 64) {
data_count_bit = 64;
decode_data = ((uint64_t)data_high << 32) | (uint64_t)data_low;
// Check manufacturer nibble (should be 0xF)
uint8_t manufacturer = (data_high >> 28) & 0xF;
if (manufacturer == 0xF) {
// Extract fields
decode_data2 = 0; // Not used
if (callback) {
callback(this);
}
}
}
parser_step = SuzukiDecoderStepReset;
}
// Short LOW pulses are ignored - stay in this state
}
break;
}
}
uint16_t header_count = 0;
uint32_t data_high = 0;
uint32_t data_low = 0;
uint8_t data_count_bit = 0;
};
+236
View File
@@ -0,0 +1,236 @@
#pragma once
#include "subcarbase.hpp"
typedef enum {
VwDecoderStepReset = 0,
VwDecoderStepFoundSync,
VwDecoderStepFoundStart1,
VwDecoderStepFoundStart2,
VwDecoderStepFoundStart3,
VwDecoderStepFoundData,
} VwDecoderStep;
class FProtoSubCarVW : public FProtoSubCarBase {
public:
FProtoSubCarVW() {
sensorType = FPC_VW;
te_short = 500;
te_long = 1000;
te_delta = 130;
min_count_bit_for_found = 80;
}
uint8_t vw_get_bit_index(uint8_t bit) {
uint8_t bit_index = 0;
if (bit < 72 && bit >= 8) {
// use generic.data (bytes 1-8)
bit_index = bit - 8;
} else {
// use data_2
if (bit >= 72) {
bit_index = bit - 64; // byte 0 = type
}
if (bit < 8) {
bit_index = bit; // byte 9 = check digit
}
bit_index |= 0x80; // mark for data_2
}
return bit_index;
}
void vw_add_bit(bool level) {
if (data_count_bit >= min_count_bit_for_found) {
return;
}
uint8_t bit_index_full = min_count_bit_for_found - 1 - data_count_bit;
uint8_t bit_index_masked = vw_get_bit_index(bit_index_full);
uint8_t bit_index = bit_index_masked & 0x7F;
if (bit_index_masked & 0x80) {
// use data_2
if (level) {
decode_data2 |= (1ULL << bit_index);
} else {
decode_data2 &= ~(1ULL << bit_index);
}
} else {
// use data
if (level) {
decode_data |= (1ULL << bit_index);
} else {
decode_data &= ~(1ULL << bit_index);
}
}
data_count_bit++;
if (data_count_bit >= min_count_bit_for_found) {
if (callback) {
callback(this);
}
}
}
void subghz_protocol_decoder_vw_reset() {
parser_step = VwDecoderStepReset;
data_count_bit = 0;
decode_data = 0;
decode_data2 = 0;
manchester_state = ManchesterStateMid1;
}
bool vw_manchester_advance(
ManchesterState state,
ManchesterEvent event,
ManchesterState* next_state,
bool* data) {
bool result = false;
ManchesterState new_state = ManchesterStateMid1;
if (event == ManchesterEventReset) {
new_state = ManchesterStateMid1;
} else if (state == ManchesterStateMid0 || state == ManchesterStateMid1) {
if (event == ManchesterEventShortHigh) {
new_state = ManchesterStateStart1;
} else if (event == ManchesterEventShortLow) {
new_state = ManchesterStateStart0;
} else {
new_state = ManchesterStateMid1;
}
} else if (state == ManchesterStateStart1) {
if (event == ManchesterEventShortLow) {
new_state = ManchesterStateMid1;
result = true;
if (data)
*data = true;
} else if (event == ManchesterEventLongLow) {
new_state = ManchesterStateStart0;
result = true;
if (data)
*data = true;
} else {
new_state = ManchesterStateMid1;
}
} else if (state == ManchesterStateStart0) {
if (event == ManchesterEventShortHigh) {
new_state = ManchesterStateMid0;
result = true;
if (data)
*data = false;
} else if (event == ManchesterEventLongHigh) {
new_state = ManchesterStateStart1;
result = true;
if (data)
*data = false;
} else {
new_state = ManchesterStateMid1;
}
}
*next_state = new_state;
return result;
}
void feed(bool level, uint32_t duration) {
uint32_t te_med = (te_long + te_short) / 2;
uint32_t te_end = te_long * 5;
ManchesterEvent event = ManchesterEventReset;
switch (parser_step) {
case VwDecoderStepReset:
if (DURATION_DIFF(duration, te_short) < te_delta) {
parser_step = VwDecoderStepFoundSync;
}
break;
case VwDecoderStepFoundSync:
if (DURATION_DIFF(duration, te_short) < te_delta) {
// Stay - sync pattern repeats ~43 times
break;
}
if (level && DURATION_DIFF(duration, te_long) < te_delta) {
parser_step = VwDecoderStepFoundStart1;
break;
}
parser_step = VwDecoderStepReset;
break;
case VwDecoderStepFoundStart1:
if (!level && DURATION_DIFF(duration, te_short) < te_delta) {
parser_step = VwDecoderStepFoundStart2;
break;
}
parser_step = VwDecoderStepReset;
break;
case VwDecoderStepFoundStart2:
if (level && DURATION_DIFF(duration, te_med) < te_delta) {
parser_step = VwDecoderStepFoundStart3;
break;
}
parser_step = VwDecoderStepReset;
break;
case VwDecoderStepFoundStart3:
if (DURATION_DIFF(duration, te_med) < te_delta) {
// Stay - med pattern repeats
break;
}
if (level && DURATION_DIFF(duration, te_short) < te_delta) {
// Start data collection
vw_manchester_advance(
manchester_state,
ManchesterEventReset,
&manchester_state,
NULL);
vw_manchester_advance(
manchester_state,
ManchesterEventShortHigh,
&manchester_state,
NULL);
data_count_bit = 0;
decode_data = 0;
decode_data2 = 0;
parser_step = VwDecoderStepFoundData;
break;
}
parser_step = VwDecoderStepReset;
break;
case VwDecoderStepFoundData:
if (DURATION_DIFF(duration, te_short) < te_delta) {
event = level ? ManchesterEventShortHigh : ManchesterEventShortLow;
}
if (DURATION_DIFF(duration, te_long) < te_delta) {
event = level ? ManchesterEventLongHigh : ManchesterEventLongLow;
}
// Last bit can be arbitrarily long
if (data_count_bit == min_count_bit_for_found - 1 &&
!level && duration > te_end) {
event = ManchesterEventShortLow;
}
if (event == ManchesterEventReset) {
subghz_protocol_decoder_vw_reset();
} else {
bool new_level;
if (vw_manchester_advance(
manchester_state,
event,
&manchester_state,
&new_level)) {
vw_add_bit(new_level);
}
}
break;
}
}
ManchesterState manchester_state = ManchesterStateMid1;
};
+54
View File
@@ -0,0 +1,54 @@
/*
Base class for all weather protocols.
This and most of the weather protocols uses code from Flipper XTreme codebase ( https://github.com/Flipper-XFW/Xtreme-Firmware/tree/dev/lib/subghz ). Thanks for their work!
For comments in a protocol implementation check w-nexus-th.hpp
*/
#ifndef __FPROTO_SCARBASE_H__
#define __FPROTO_SCARBASE_H__
#include "fprotogeneral.hpp"
#include "subcartypes.hpp"
#include <string>
// default values to indicate 'no value'
class FProtoSubCarBase;
typedef void (*SubCarProtocolDecoderBaseRxCallback)(FProtoSubCarBase* instance);
class FProtoSubCarBase {
public:
FProtoSubCarBase() {}
virtual ~FProtoSubCarBase() {}
virtual void feed(bool level, uint32_t duration) = 0; // need to be implemented on each protocol handler.
void setCallback(SubCarProtocolDecoderBaseRxCallback cb) { callback = cb; } // this is called when there is a hit.
// General data holder, these will be passed
uint8_t sensorType = FPC_Invalid;
uint16_t data_count_bit = 0;
uint64_t decode_data = 0;
uint64_t decode_data2 = 0;
protected:
// Helper functions to keep it as compatible with flipper as we can, so adding new protos will be easy.
void subghz_protocol_blocks_add_bit(uint8_t bit) {
decode_data = decode_data << 1 | bit;
decode_count_bit++;
}
// inner logic stuff, also for flipper compatibility.
uint32_t te_short = UINT32_MAX;
uint32_t te_long = UINT32_MAX;
uint32_t te_delta = UINT32_MAX;
uint32_t min_count_bit_for_found = UINT32_MAX;
SubCarProtocolDecoderBaseRxCallback callback = NULL;
uint8_t parser_step = 0;
uint32_t te_last = 0;
uint32_t decode_count_bit = 0;
//
};
#endif

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