BLE Tx App / BLE Rx Filtering. (#1543)

BLE TX app creation
BLE RX and TX app improvements
This commit is contained in:
Netro
2023-11-01 06:46:41 -04:00
committed by GitHub
parent 62307b93d7
commit dceb7255b0
19 changed files with 1402 additions and 34 deletions

View File

@@ -30,6 +30,7 @@
#include "baseband_api.hpp"
#include "string_format.hpp"
#include "portapack_persistent_memory.hpp"
#include "ui_textentry.hpp"
using namespace portapack;
using namespace modems;
@@ -214,15 +215,32 @@ BLERxView::BLERxView(NavigationView& nav)
&check_log,
&label_sort,
&options_sort,
&button_message,
&recent_entries_view,
&recent_entries_filter_view,
&recent_entry_detail_view});
recent_entry_detail_view.hidden(true);
recent_entries_filter_view.hidden(true);
recent_entries_view.on_select = [this](const BleRecentEntry& entry) {
nav_.push<BleRecentEntryDetailView>(entry);
};
recent_entries_filter_view.on_select = [this](const BleRecentEntry& entry) {
nav_.push<BleRecentEntryDetailView>(entry);
};
button_message.on_select = [this, &nav](Button&) {
text_prompt(
nav,
filterBuffer,
64,
[this](std::string& buffer) {
on_switch_table(buffer);
});
};
field_frequency.set_step(0);
check_log.set_value(logging);
@@ -244,20 +262,27 @@ BLERxView::BLERxView(NavigationView& nav)
case 0:
sortEntriesBy(
recent, [](const BleRecentEntry& entry) { return entry.macAddress; }, true);
sortEntriesBy(
filterEntries, [](const BleRecentEntry& entry) { return entry.macAddress; }, true);
break;
case 1:
sortEntriesBy(
recent, [](const BleRecentEntry& entry) { return entry.dbValue; }, true);
sortEntriesBy(
filterEntries, [](const BleRecentEntry& entry) { return entry.dbValue; }, true);
break;
case 2:
sortEntriesBy(
recent, [](const BleRecentEntry& entry) { return entry.timestamp; }, false);
sortEntriesBy(
filterEntries, [](const BleRecentEntry& entry) { return entry.timestamp; }, false);
break;
default:
break;
}
recent_entries_view.set_dirty();
recent_entries_filter_view.set_dirty();
};
options_channel.set_selected_index(0, true);
@@ -319,8 +344,6 @@ void BLERxView::on_data(BlePacketData* packet) {
break;
}
// str_console += to_string_dec_uint(value);
str_console += " Len:";
str_console += to_string_dec_uint(packet->size);
@@ -335,7 +358,7 @@ void BLERxView::on_data(BlePacketData* packet) {
int i;
for (i = 0; i < packet->dataLen; i++) {
str_console += " " + to_string_hex(packet->data[i], 2);
str_console += to_string_hex(packet->data[i], 2);
}
str_console += "\n";
@@ -345,9 +368,60 @@ void BLERxView::on_data(BlePacketData* packet) {
// Start of Packet stuffing.
// Masking off the top 2 bytes to avoid invalid keys.
auto& entry = ::on_packet(recent, macAddressEncoded & 0xFFFFFFFFFFFF);
updateEntry(packet, entry);
// Log at End of Packet.
if (logger && logging) {
logger->log_raw_data(str_console);
}
}
void BLERxView::on_switch_table(const std::string value) {
filter = value;
if (!value.empty()) {
removeEntriesWithoutKey(recent, filterEntries, [&value](const BleRecentEntry& entry) {
return entry.dataString.find(value) == std::string::npos;
});
recent_entries_view.set_dirty();
recent_entries_filter_view.hidden(false);
recent_entries_view.hidden(true);
} else {
recent_entries_view.hidden(false);
recent_entries_filter_view.hidden(true);
}
recent_entries_view.set_dirty();
recent_entries_filter_view.set_dirty();
}
void BLERxView::set_parent_rect(const Rect new_parent_rect) {
View::set_parent_rect(new_parent_rect);
const Rect content_rect{0, header_height, new_parent_rect.width(), new_parent_rect.height() - header_height};
recent_entries_view.set_parent_rect(content_rect);
recent_entry_detail_view.set_parent_rect(content_rect);
recent_entries_filter_view.set_parent_rect(content_rect);
}
BLERxView::~BLERxView() {
receiver_model.disable();
baseband::shutdown();
}
void BLERxView::updateEntry(const BlePacketData* packet, BleRecentEntry& entry) {
std::string data_string;
int i;
for (i = 0; i < packet->dataLen; i++) {
data_string += to_string_hex(packet->data[i], 2);
}
entry.dbValue = packet->max_dB;
entry.timestamp = to_string_timestamp(rtc_time::now());
entry.dataString = data_string;
entry.packetData.type = packet->type;
entry.packetData.size = packet->size;
@@ -370,48 +444,31 @@ void BLERxView::on_data(BlePacketData* packet) {
case 0:
sortEntriesBy(
recent, [](const BleRecentEntry& entry) { return entry.macAddress; }, true);
sortEntriesBy(
filterEntries, [](const BleRecentEntry& entry) { return entry.macAddress; }, true);
break;
case 1:
sortEntriesBy(
recent, [](const BleRecentEntry& entry) { return entry.dbValue; }, true);
sortEntriesBy(
filterEntries, [](const BleRecentEntry& entry) { return entry.dbValue; }, true);
break;
case 2:
sortEntriesBy(
recent, [](const BleRecentEntry& entry) { return entry.timestamp; }, false);
sortEntriesBy(
filterEntries, [](const BleRecentEntry& entry) { return entry.timestamp; }, false);
break;
default:
break;
}
recent_entries_view.set_dirty();
on_switch_table(filter);
// TODO: Crude hack, should be a more formal listener arrangement...
if (entry.key() == recent_entry_detail_view.entry().key()) {
recent_entry_detail_view.set_entry(entry);
}
// Log at End of Packet.
if (logger && logging) {
logger->log_raw_data(str_console);
}
}
void BLERxView::set_parent_rect(const Rect new_parent_rect) {
View::set_parent_rect(new_parent_rect);
const Rect content_rect{0, header_height, new_parent_rect.width(), new_parent_rect.height() - header_height};
recent_entries_view.set_parent_rect(content_rect);
recent_entry_detail_view.set_parent_rect(content_rect);
}
BLERxView::~BLERxView() {
receiver_model.disable();
baseband::shutdown();
}
// BleRecentEntry
// void BleRecentEntry::update(const BlePacketData * packet)
// {
// }
} /* namespace ui */

View File

@@ -77,6 +77,7 @@ struct BleRecentEntry {
int dbValue;
BlePacketData packetData;
std::string timestamp;
std::string dataString;
BleRecentEntry()
: BleRecentEntry{0} {
@@ -87,14 +88,13 @@ struct BleRecentEntry {
: macAddress{macAddress},
dbValue{},
packetData{},
timestamp{} {
timestamp{},
dataString{} {
}
Key key() const {
return macAddress;
}
// void update(const BlePacketData * packet);
};
using BleRecentEntries = RecentEntries<BleRecentEntry>;
@@ -151,6 +151,8 @@ class BLERxView : public View {
private:
void on_data(BlePacketData* packetData);
void on_switch_table(const std::string value);
void updateEntry(const BlePacketData* packet, BleRecentEntry& entry);
NavigationView& nav_;
RxRadioState radio_state_{
@@ -165,6 +167,9 @@ class BLERxView : public View {
uint32_t prev_value{0};
uint8_t channel_number = 37;
std::string filterBuffer{};
std::string filter{};
static constexpr auto header_height = 12 + 2 * 16;
OptionsField options_channel{
@@ -209,6 +214,10 @@ class BLERxView : public View {
{"dB", 1},
{"Recent", 2}}};
Button button_message{
{22 * 8, 3 * 8, 4 * 8, 16},
"Filter"};
Console console{
{0, 4 * 16, 240, 240}};
@@ -223,6 +232,7 @@ class BLERxView : public View {
// {"Time", 8}}};
BleRecentEntries recent{};
BleRecentEntries filterEntries{};
const RecentEntriesColumns columns{{
{"Mac Address", 20},
@@ -231,6 +241,7 @@ class BLERxView : public View {
BleRecentEntry entry_{};
BleRecentEntriesView recent_entries_view{columns, recent};
BleRecentEntriesView recent_entries_filter_view{columns, filterEntries};
BleRecentEntryDetailView recent_entry_detail_view{nav_, entry_};
MessageHandlerRegistration message_handler_packet{

View File

@@ -0,0 +1,351 @@
/*
* Copyright (C) 2014 Jared Boone, ShareBrained Technology, Inc.
* Copyright (C) 2017 Furrtek
* Copyright (C) 2023 TJ Baginski
*
* 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 "ble_tx_app.hpp"
#include "ui_fileman.hpp"
#include "ui_modemsetup.hpp"
#include "audio.hpp"
#include "baseband_api.hpp"
#include "io_file.hpp"
#include "modems.hpp"
#include "portapack_persistent_memory.hpp"
#include "rtc_time.hpp"
#include "string_format.hpp"
using namespace portapack;
using namespace modems;
namespace fs = std::filesystem;
void BLELoggerTx::log_raw_data(const std::string& data) {
log_file.write_entry(data);
}
bool hasValidHexPairs(const std::string& str, int totalPairs) {
int validPairs = 0;
for (int i = 0; i < totalPairs * 2; i += 2) {
char c1 = str[i];
char c2 = str[i + 1];
if (!(std::isxdigit(c1) && std::isxdigit(c2))) {
return false; // Return false if any pair is invalid.
}
validPairs++;
}
return (validPairs == totalPairs);
}
std::vector<std::string> splitIntoStrings(const char* input) {
std::vector<std::string> result;
int length = std::strlen(input);
int start = 0;
while (start < length) {
int remaining = length - start;
int chunkSize = (remaining > 30) ? 30 : remaining;
result.push_back(std::string(input + start, chunkSize));
start += chunkSize;
}
return result;
}
uint32_t stringToUint32(const std::string& str) {
size_t pos = 0;
uint32_t result = 0;
while (pos < str.size() && std::isdigit(str[pos])) {
int digit = str[pos] - '0';
// Check for overflow before adding the next digit
if (result > (UINT32_MAX - digit) / 10) {
return 0;
}
result = result * 10 + digit;
pos++;
}
// Check if there are any non-digit characters left
if (pos < str.size()) {
return 0;
}
return result;
}
void readUntilSpace(File& file, char* result, std::size_t maxBufferSize) {
std::size_t bytesRead = 0;
while (true) {
char ch;
File::Result<File::Size> readResult = file.read(&ch, 1);
if (readResult.is_ok() && readResult.value() > 0) {
if (ch == ' ') {
// Found a space character, stop reading
break;
} else if (bytesRead < maxBufferSize) {
// Append the character to the result if there's space
result[bytesRead++] = ch;
} else {
// Buffer is full, break to prevent overflow
break;
}
} else {
break; // End of file or error
}
}
// Null-terminate the result string
result[bytesRead] = '\0';
}
static std::uint64_t 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;
}
namespace ui {
void BLETxView::focus() {
field_frequency.focus();
}
bool BLETxView::is_active() const {
return (bool)is_running;
}
void BLETxView::file_error() {
nav_.display_modal("Error", "File read error.");
}
void BLETxView::toggle() {
if (is_active()) {
stop();
} else {
start();
}
}
void BLETxView::start() {
if (!is_active()) {
// Check if file is present before continuing.
File data_file;
auto error = data_file.open(file_path);
if (error) {
file_error();
check_loop.set_value(false);
return;
} else {
// Send first or single packet.
progressbar.set_max(packet_count);
button_play.set_bitmap(&bitmap_stop);
baseband::set_btletx(channel_number, macAddress, advertisementData);
transmitter_model.enable();
is_running = true;
}
} else {
// Send next packet.
baseband::set_btletx(channel_number, macAddress, advertisementData);
}
if ((packet_counter % 10) == 0) {
text_packets_sent.set(to_string_dec_uint(packet_counter));
}
packet_counter--;
progressbar.set_value(packet_count - packet_counter);
}
void BLETxView::stop() {
transmitter_model.disable();
progressbar.set_value(0);
button_play.set_bitmap(&bitmap_play);
check_loop.set_value(false);
text_packets_sent.set(to_string_dec_uint(packet_count));
packet_counter = packet_count;
is_running = false;
}
void BLETxView::on_tx_progress(const bool done) {
if (done) {
if (check_loop.value() && (packet_counter != 0) && is_active()) {
if ((timer_count % timer_period) == 0) {
start();
}
} else {
if (is_active()) {
stop();
}
}
timer_count++;
}
}
BLETxView::BLETxView(NavigationView& nav)
: nav_{nav} {
baseband::run_image(portapack::spi_flash::image_tag_btle_tx);
add_children({&button_open,
&text_filename,
&progressbar,
&field_frequency,
&tx_view, // now it handles previous rfgain, rfamp.
&check_loop,
&button_play,
&label_speed,
&options_speed,
&options_channel,
&label_packets_sent,
&text_packets_sent,
&label_mac_address,
&text_mac_address,
&label_data_packet,
&console});
field_frequency.set_step(0);
button_play.on_select = [this](ImageButton&) {
this->toggle();
};
options_channel.on_change = [this](size_t, int32_t i) {
field_frequency.set_value(get_freq_by_channel_number(i));
channel_number = i;
};
options_speed.on_change = [this](size_t, int32_t i) {
timer_period = i;
};
options_speed.set_selected_index(0);
button_open.on_select = [this, &nav](Button&) {
auto open_view = nav.push<FileLoadView>(".TXT");
open_view->on_changed = [this](std::filesystem::path new_file_path) {
on_file_changed(new_file_path);
};
};
}
void BLETxView::on_file_changed(const fs::path& new_file_path) {
file_path = fs::path(u"/") + new_file_path;
{ // Get the size of the data file.
File data_file;
auto error = data_file.open(file_path);
if (error) {
file_error();
file_path = "";
return;
}
readUntilSpace(data_file, macAddress, mac_address_size_str);
readUntilSpace(data_file, advertisementData, max_packet_size_str);
readUntilSpace(data_file, packetCount, max_packet_count_str);
uint64_t macAddressSize = strlen(macAddress);
uint64_t advertisementDataSize = strlen(advertisementData);
uint64_t packetCountSize = strlen(packetCount);
packet_count = stringToUint32(packetCount);
packet_counter = packet_count;
// Verify Data.
if ((macAddressSize == mac_address_size_str) && (advertisementDataSize < max_packet_size_str) && (packetCountSize < max_packet_count_str) &&
hasValidHexPairs(macAddress, macAddressSize / 2) && hasValidHexPairs(advertisementData, advertisementDataSize / 2) && (packet_count > 0) && (packet_count < UINT32_MAX)) {
text_packets_sent.set(to_string_dec_uint(packet_count));
std::string formattedMacAddress = to_string_formatted_mac_address(macAddress);
text_mac_address.set(formattedMacAddress);
std::vector<std::string> strings = splitIntoStrings(advertisementData);
console.clear(true);
for (const std::string& str : strings) {
console.writeln(str);
}
text_filename.set(truncate(file_path.filename().string(), 12));
} else {
// file_error();
file_path = "";
return;
}
}
}
void BLETxView::on_data(uint32_t value, bool is_data) {
std::string str_console = "";
if (is_data) {
str_console += (char)(value);
}
console.write(str_console);
}
void BLETxView::set_parent_rect(const Rect new_parent_rect) {
View::set_parent_rect(new_parent_rect);
const Rect content_rect{0, header_height, new_parent_rect.width(), new_parent_rect.height() - header_height};
console.set_parent_rect(content_rect);
}
BLETxView::~BLETxView() {
transmitter_model.disable();
baseband::shutdown();
}
} /* namespace ui */

View File

@@ -0,0 +1,207 @@
/*
* Copyright (C) 2014 Jared Boone, ShareBrained Technology, Inc.
* Copyright (C) 2017 Furrtek
* Copyright (C) 2023 TJ Baginski
*
* 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 __BLE_TX_APP_H__
#define __BLE_TX_APP_H__
#include "ui.hpp"
#include "ui_navigation.hpp"
#include "ui_receiver.hpp"
#include "ui_transmitter.hpp"
#include "ui_freq_field.hpp"
#include "ui_record_view.hpp"
#include "app_settings.hpp"
#include "radio_state.hpp"
#include "replay_thread.hpp"
#include "log_file.hpp"
#include "utility.hpp"
#include "recent_entries.hpp"
#include <string>
#include <memory>
class BLELoggerTx {
public:
Optional<File::Error> append(const std::string& filename) {
return log_file.append(filename);
}
void log_raw_data(const std::string& data);
private:
LogFile log_file{};
};
namespace ui {
class BLETxView : public View {
public:
BLETxView(NavigationView& nav);
~BLETxView();
void set_parent_rect(const Rect new_parent_rect) override;
void paint(Painter&) override{};
void focus() override;
bool is_active() const;
void toggle();
void start();
void stop();
void handle_replay_thread_done(const uint32_t return_code);
void file_error();
std::string title() const override { return "BLE TX"; };
private:
void on_data(uint32_t value, bool is_data);
void on_tx_progress(const bool done);
void on_file_changed(const std::filesystem::path& new_file_path);
NavigationView& nav_;
TxRadioState radio_state_{
2'402'000'000 /* frequency */,
4'000'000 /* bandwidth */,
4'000'000 /* sampling rate */
};
app_settings::SettingsManager settings_{
"ble_tx_app", app_settings::Mode::TX};
uint8_t console_color{0};
uint32_t prev_value{0};
std::filesystem::path file_path{};
uint8_t channel_number = 37;
char macAddress[13] = "010203040506";
char advertisementData[63] = "00112233445566778899AABBCCDDEEFF";
char packetCount[11] = "0";
bool is_running = false;
uint64_t timer_count{0};
uint64_t timer_period{256};
bool repeatLoop = false;
uint32_t packet_count{0};
uint32_t packet_counter{0};
static constexpr uint8_t mac_address_size_str{12};
static constexpr uint8_t max_packet_size_str{62};
static constexpr uint8_t max_packet_count_str{10};
static constexpr uint32_t max_packet_count{UINT32_MAX};
static constexpr auto header_height = 8 * 16;
Button button_open{
{0 * 8, 0 * 16, 10 * 8, 2 * 16},
"Open file"};
Text text_filename{
{11 * 8, 0 * 16, 12 * 8, 16},
"-"};
ProgressBar progressbar{
{11 * 8, 1 * 16, 12 * 8, 16}};
TxFrequencyField field_frequency{
{0 * 8, 2 * 16},
nav_};
TransmitterView2 tx_view{
{11 * 8, 2 * 16},
/*short_ui*/ true};
Checkbox check_loop{
{21 * 8, 2 * 16},
4,
"Loop",
true};
ImageButton button_play{
{28 * 8, 2 * 16, 2 * 8, 1 * 16},
&bitmap_play,
Color::green(),
Color::black()};
Labels label_speed{
{{0 * 8, 6 * 8}, "Speed:", Color::light_grey()}};
OptionsField options_speed{
{7 * 8, 6 * 8},
3,
{{"1 ", 256},
{"2 ", 128},
{"3 ", 64},
{"4 ", 32},
{"5 ", 16}}};
OptionsField options_channel{
{11 * 8, 6 * 8},
5,
{{"Ch.37 ", 37},
{"Ch.38", 38},
{"Ch.39", 39}}};
Labels label_packets_sent{
{{0 * 8, 10 * 8}, "Packets Left:", Color::light_grey()}};
Text text_packets_sent{
{13 * 8, 5 * 16, 10 * 8, 16},
"-"};
Labels label_mac_address{
{{0 * 8, 12 * 8}, "Mac Address:", Color::light_grey()}};
Text text_mac_address{
{12 * 8, 6 * 16, 20 * 8, 16},
"-"};
Labels label_data_packet{
{{0 * 8, 14 * 8}, "Packet Data:", Color::light_grey()}};
Console console{
{0, 7 * 16, 240, 240}};
std::string str_log{""};
bool logging{true};
bool logging_done{false};
std::unique_ptr<BLELoggerTx> logger{};
MessageHandlerRegistration message_handler_packet{
Message::ID::AFSKData,
[this](Message* const p) {
const auto message = static_cast<const AFSKDataMessage*>(p);
this->on_data(message->value, message->is_data);
}};
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);
}};
};
} /* namespace ui */
#endif /*__UI_AFSK_RX_H__*/