From 95bca66dad83dd55e7e7983579c025335f03a6cc Mon Sep 17 00:00:00 2001 From: TurbulentGoat <131882443+TurbulentGoat@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:17:17 +0800 Subject: [PATCH 1/4] Add RF analyzer tools, BLE glasses detector, ProtoPirate model DB, and WiFi sniffer fix - RF: sub-GHz auto-classifier (Analyze), rolling-code analyzer, remote analyzer (peak find + AM/FM), car-model database + custom radio profiles - BLE: smart/Meta glasses detector (Glasses Detect) - ProtoPirate: car-model selector + custom CC1101 register profiles - WiFi sniffer: RAM guard, static queue, STA+promiscuous mode, reduced buffers (fixes OOM/reboot on no-PSRAM boards) --- src/core/menu_items/BleMenu.cpp | 2 + src/core/menu_items/RFMenu.cpp | 6 + src/modules/ble/ble_glasses.cpp | 236 +++++++++++++++++++++++++ src/modules/ble/ble_glasses.h | 24 +++ src/modules/rf/protocols/rf_models.cpp | 72 ++++++++ src/modules/rf/protocols/rf_models.h | 32 ++++ src/modules/rf/rf_analyze.cpp | 169 ++++++++++++++++++ src/modules/rf/rf_analyze.h | 10 ++ src/modules/rf/rf_classify.cpp | 100 +++++++++++ src/modules/rf/rf_classify.h | 44 +++++ src/modules/rf/rf_protopirate.cpp | 46 ++++- src/modules/rf/rf_remote_analyzer.cpp | 134 ++++++++++++++ src/modules/rf/rf_remote_analyzer.h | 11 ++ src/modules/rf/rf_rolling.cpp | 157 ++++++++++++++++ src/modules/rf/rf_rolling.h | 11 ++ src/modules/rf/rf_scan.h | 5 + src/modules/wifi/sniffer.cpp | 52 ++++-- 17 files changed, 1091 insertions(+), 20 deletions(-) create mode 100644 src/modules/ble/ble_glasses.cpp create mode 100644 src/modules/ble/ble_glasses.h create mode 100644 src/modules/rf/protocols/rf_models.cpp create mode 100644 src/modules/rf/protocols/rf_models.h create mode 100644 src/modules/rf/rf_analyze.cpp create mode 100644 src/modules/rf/rf_analyze.h create mode 100644 src/modules/rf/rf_classify.cpp create mode 100644 src/modules/rf/rf_classify.h create mode 100644 src/modules/rf/rf_remote_analyzer.cpp create mode 100644 src/modules/rf/rf_remote_analyzer.h create mode 100644 src/modules/rf/rf_rolling.cpp create mode 100644 src/modules/rf/rf_rolling.h diff --git a/src/core/menu_items/BleMenu.cpp b/src/core/menu_items/BleMenu.cpp index ed144ba653..433a89c2ea 100644 --- a/src/core/menu_items/BleMenu.cpp +++ b/src/core/menu_items/BleMenu.cpp @@ -3,6 +3,7 @@ #include "core/utils.h" #include "modules/badusb_ble/ducky_typer.h" #include "modules/ble/ble_common.h" +#include "modules/ble/ble_glasses.h" #include "modules/ble/ble_ninebot.h" #include "modules/ble/ble_spam.h" #if !defined(LITE_VERSION) @@ -27,6 +28,7 @@ void BleMenu::optionsMenu() { #if !defined(LITE_VERSION) options.push_back({"Media Cmds", [=]() { MediaCommands(hid_ble, true); }}); options.push_back({"BLE Scan", ble_scan}); + options.push_back({"Glasses Detect", ble_glasses_detector}); options.push_back({"iBeacon", [=]() { ibeacon("Bruce", "e4c159a0-8c82-11e6-bdf4-0800200c9a66", 0x004C); }}); diff --git a/src/core/menu_items/RFMenu.cpp b/src/core/menu_items/RFMenu.cpp index 5812d0d602..e4776901cb 100644 --- a/src/core/menu_items/RFMenu.cpp +++ b/src/core/menu_items/RFMenu.cpp @@ -3,9 +3,12 @@ #include "core/settings.h" #include "core/utils.h" #include "modules/rf/record.h" +#include "modules/rf/rf_analyze.h" #include "modules/rf/rf_bruteforce.h" #include "modules/rf/rf_jammer.h" #include "modules/rf/rf_listen.h" +#include "modules/rf/rf_remote_analyzer.h" +#include "modules/rf/rf_rolling.h" #include "modules/rf/rf_scan.h" #include "modules/rf/rf_send.h" #include "modules/rf/rf_spectrum.h" @@ -26,10 +29,13 @@ void RFMenu::optionsMenu() { {"RSSI Spectrum", rf_CC1101_rssi }, // @Pirata {"SquareWave Spec", rf_SquareWave }, // @Pirata {"Spectogram", rf_waterfall }, // dev_eclipse + {"Remote Analyzer", rf_remote_analyzer }, // ProtoPirate remote analyzer (peak find + AM/FM) + {"Analyze", rf_analyze }, // auto classify modulation + decode #if defined(RF_LISTEN_H) {"Listen", rf_listen }, // dev_eclipse #endif {"Bruteforce", rf_bruteforce }, // dev_eclipse + {"Rolling Code", rf_rolling_code }, // rolling-code analyzer {"Jammer", [=]() { RFJammer(true); } }, #endif {"Config", [this]() { configMenu(); }}, diff --git a/src/modules/ble/ble_glasses.cpp b/src/modules/ble/ble_glasses.cpp new file mode 100644 index 0000000000..f498981919 --- /dev/null +++ b/src/modules/ble/ble_glasses.cpp @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#include "ble_glasses.h" + +#include "ble_common.h" +#include "core/display.h" +#include "core/mykeyboard.h" +#include + +namespace { + +// Confidence levels for a match. +constexpr uint8_t CONF_HIGH = 3; +constexpr uint8_t CONF_MED = 2; +constexpr uint8_t CONF_LOW = 1; + +struct GlassesMatch { + String name; + String address; + int rssi = 0; + String vendor; + uint8_t confidence = 0; +}; + +// Bluetooth SIG company (manufacturer) IDs used by smart-glasses makers. +struct CompanyEntry { + uint16_t id; + const char *label; +}; +const CompanyEntry kCompanies[] = { + {0x01AB, "Meta Platforms"}, + {0x058E, "Meta Technologies"}, + {0x0D53, "Luxottica (Ray-Ban/Oakley)"}, + {0x03C2, "Snap (Spectacles)"}, + {0x05D6, "Jieli (Rogbird/ViewPro)"}, +}; + +// Plaintext product names broadcast during pairing (lowercased substrings). +const char *kNameHints[] = { + "ray-ban", "rayban", "oakley", "spectacles", "heycyan", "visionpro", + "meta view", "meta", "stories", "echo frames", "vuzix", "rokid", + "xreal", "nreal", "smart glasses", +}; + +const char *companyLabel(uint16_t id) { + for (const auto &c : kCompanies) + if (c.id == id) return c.label; + return nullptr; +} + +// Lowercase copy of a std::string (ASCII only). +String lower(const std::string &s) { + String out; + out.reserve(s.size()); + for (unsigned char c : s) + if (c >= 'A' && c <= 'Z') out += (char)(c + 32); + else out += (char)c; + return out; +} + +bool contains(const String &hay, const char *needle) { return hay.indexOf(needle) >= 0; } + +// Truncate a string to fit `maxChars`, appending "..." when clipped. +String fit(const String &s, int maxChars) { + if (maxChars < 4) return s.substring(0, maxChars); + if ((int)s.length() <= maxChars) return s; + return s.substring(0, maxChars - 3) + "..."; +} + +// Try to match a single advertised device as smart glasses. +bool matchDevice(const NimBLEAdvertisedDevice *dev, GlassesMatch &out) { + if (!dev) return false; + + const String name = lower(dev->getName()); + uint16_t company = 0; + bool hasCompany = false; + + if (dev->haveManufacturerData()) { + const std::string md = dev->getManufacturerData(); + if (md.size() >= 2) { + company = (uint8_t)md[0] | ((uint8_t)md[1] << 8); + hasCompany = true; + // Meta camera glasses embed an ASCII tag right after the company id. + const String tag = lower(md.substr(2)); + if (contains(tag, "meta_rb_glass")) { + out.vendor = "Meta Ray-Ban"; + out.confidence = CONF_HIGH; + } + } + } + + // Highest confidence: a registered smart-glasses company ID. + if (out.confidence < CONF_HIGH && hasCompany) { + const char *label = companyLabel(company); + if (label) { + out.vendor = label; + out.confidence = CONF_HIGH; + } + } + + // Fixed service UUIDs (Google/Eddystone on Meta frames, HeyCyan SDK). + if (out.confidence < CONF_HIGH) { + if (dev->isAdvertisingService(NimBLEUUID("FEAA")) || + dev->isAdvertisingService(NimBLEUUID("7905fff0-b5ce-4e99-a40f-4b1e122d00d0"))) { + out.vendor = "Smart glasses (UUID)"; + out.confidence = CONF_MED; + } + } + + // Plaintext name match (easy to spoof, so lower confidence). + if (out.confidence < CONF_MED) { + for (const char *hint : kNameHints) { + if (contains(name, hint)) { + out.vendor = String("Name: ") + hint; + out.confidence = CONF_LOW; + break; + } + } + } + + if (out.confidence == 0) return false; + + out.name = dev->getName().empty() ? String("") : String(dev->getName().c_str()); + out.address = dev->getAddress().toString().c_str(); + out.rssi = dev->getRSSI(); + return true; +} + +const char *confLabel(uint8_t c) { + if (c >= CONF_HIGH) return "HIGH"; + if (c >= CONF_MED) return "MED"; + return "LOW"; +} + +int textMaxChars() { + const int w = tftWidth - 2 * BORDER_PAD_X; + const int cw = LW * FP; + return (w / cw) - 1; +} + +void drawResult(const std::vector &matches, bool scanning) { + drawMainBorderWithTitle("Glasses Detector"); + const int x = BORDER_PAD_X; + const int lh = LH * FP + 6; + int y = BORDER_PAD_Y + FM * LH + 6; + const int maxChars = textMaxChars(); + tft.setTextSize(FP); + + if (matches.empty()) { + tft.setTextColor(bruceConfig.priColor, bruceConfig.bgColor); + tft.drawString(scanning ? "Scanning..." : "Scanning... none found", x, y, 1); + } else { + tft.setTextColor(TFT_RED, bruceConfig.bgColor); + tft.drawString(fit(String("! ") + matches.size() + " possible glasses", maxChars), x, y, 1); + y += lh + 2; + + const size_t max = matches.size() > 5 ? 5 : matches.size(); + for (size_t i = 0; i < max; i++) { + const auto &m = matches[i]; + if (y + lh > tftHeight - 14) break; + tft.setTextColor(bruceConfig.priColor, bruceConfig.bgColor); + tft.drawString(fit(m.name, maxChars), x, y, 1); + y += lh; + tft.setTextColor(blendColors(bruceConfig.bgColor, bruceConfig.priColor, 170), bruceConfig.bgColor); + tft.drawString( + fit(String(m.vendor) + " " + m.rssi + "dBm [" + confLabel(m.confidence) + "]", maxChars), + x, y, 1 + ); + y += lh + 2; + } + } + + tft.setTextColor(blendColors(bruceConfig.bgColor, bruceConfig.priColor, 150), bruceConfig.bgColor); + tft.drawString(fit("[SEL] menu [ESC] back", maxChars), x, tftHeight - LH * FP - 8, 1); +} + +} // namespace + +void ble_glasses_detector() { +#if !defined(LITE_VERSION) + if (!ble_scan_setup() || pBLEScan == nullptr) { + displayError("Failed to init BLE scan"); + return; + } + + // No-PSRAM board: keep the retained device set small. Duplicate reports are + // irrelevant for detection and are the main source of RAM churn. + pBLEScan->setDuplicateFilter(true); + + bool exit = false; + std::vector matches; + + while (!exit) { + // One full scan (same flow as ble_scan), then wait for input instead of + // tight-looping the radio — that's what exhausted the heap before. + matches.clear(); + drawResult(matches, true); // "Scanning..." + + pBLEScan->clearResults(); + BLEScanResults found = pBLEScan->getResults(scanTime * 1000, false); + + const int count = found.getCount(); + for (int i = 0; i < count; i++) { + GlassesMatch m; + if (matchDevice(found.getDevice(i), m)) matches.push_back(m); + } + + drawResult(matches, false); + if (!matches.empty() && bruceConfigPins.buzzer > 0) + tone((uint8_t)bruceConfigPins.buzzer, 2000, 80); + + // Block on user input so we don't keep allocating scan results. + bool rescan = false; + while (!rescan && !exit) { + if (check(SelPress)) { + int action = 0; + options = { + {"Rescan", [&]() { action = 0; }}, + {"Back to menu", [&]() { action = 1; }}, + }; + loopOptions(options, MENU_TYPE_SUBMENU, "Glasses Detector"); + options.clear(); + if (action == 1) exit = true; + else rescan = true; + } + if (check(EscPress)) exit = true; + vTaskDelay(pdMS_TO_TICKS(20)); + } + } + + if (pBLEScan) pBLEScan->stop(); + stopBLEStack(); + returnToMenu = true; +#else + displayError("Not available on Launcher version"); +#endif +} diff --git a/src/modules/ble/ble_glasses.h b/src/modules/ble/ble_glasses.h new file mode 100644 index 0000000000..d5ea99e9b8 --- /dev/null +++ b/src/modules/ble/ble_glasses.h @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#ifndef __BLE_GLASSES_H__ +#define __BLE_GLASSES_H__ + +// Scans for camera-equipped smart glasses (Meta Ray-Ban, Oakley Meta, Snap +// Spectacles, and similar) by matching their BLE advertisement fingerprints: +// Bluetooth SIG manufacturer (company) IDs, the "META_RB_GLASS" manufacturer +// data string, known product names, and fixed service UUIDs. +// +// Fingerprints sourced from public research (ZuckOff, yj_nearbyglasses): +// - 0x01AB Meta Platforms, Inc. (formerly Facebook) +// - 0x058E Meta Platforms Technologies, LLC +// - 0x0D53 Luxottica Group S.p.A (manufactures Meta Ray-Bans/Oakley) +// - 0x03C2 Snapchat, Inc. (Snap Spectacles) +// - 0x05D6 Zhuhai Jieli Technology Co (Rogbird VisionPro / Rollme VistaView) +// - 0xFEAA Google/Eddystone service UUID (seen on Meta frames) +// - 7905FFF0-B5CE-4E99-A40F-4B1E122D00D0 HeyCyan smart-glasses SDK UUID +// +// Detection is heuristic: a match means "camera-capable hardware of a known +// maker is in BLE range", NOT that recording is happening. False positives +// are possible (e.g. a VR headset from the same vendor). +void ble_glasses_detector(); + +#endif diff --git a/src/modules/rf/protocols/rf_models.cpp b/src/modules/rf/protocols/rf_models.cpp new file mode 100644 index 0000000000..61e7c41778 --- /dev/null +++ b/src/modules/rf/protocols/rf_models.cpp @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#include "rf_models.h" + +#include "../rf_utils.h" // ELECHOUSE_cc1101, setMHZ +#include "rf_fsk_receive_profile.h" +#include "rf_presets.h" + +// Raw CC1101 register dump for the Honda "custom" preset, taken verbatim from +// ProtoPirate's models.txt (Flipper CustomPresetData, registers 0x00..0x2D). +static const uint8_t kHondaRegisters[] = { + 0x02, 0x0D, 0x0B, 0x06, 0x08, 0x32, 0x07, 0x04, 0x14, 0x00, 0x13, 0x02, + 0x12, 0x07, 0x11, 0x36, 0x10, 0xE9, 0x15, 0x32, 0x18, 0x18, 0x19, 0x16, + 0x1D, 0x92, 0x1C, 0x40, 0x1B, 0x03, 0x20, 0xFB, 0x22, 0x10, 0x21, 0x56, + 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +static const CarModel kModels[] = { + {"433.92 Mhz AM650", 433920000, "Ook650Async", nullptr, 0}, + {"433.92 Mhz FM476", 433920000, "2FSKDev476Async", nullptr, 0}, + {"315 Mhz AM650", 315000000, "Ook650Async", nullptr, 0}, + {"315 Mhz FM476", 315000000, "2FSKDev476Async", nullptr, 0}, + {"Ford 433.92 Mhz AM", 433920000, "Ook650Async", nullptr, 0}, + {"Ford 433.92 Mhz FM", 433920000, "2FSKDev476Async", nullptr, 0}, + {"Honda 433.92 Mhz FM", 433920000, "Custom", kHondaRegisters, sizeof(kHondaRegisters)}, + {"Honda 315 Mhz FM", 315000000, "Custom", kHondaRegisters, sizeof(kHondaRegisters)}, + {"KIA 433.92 Mhz AM", 433920000, "Ook650Async", nullptr, 0}, + {"KIA 433.92 Mhz FM", 433920000, "2FSKDev476Async", nullptr, 0}, + {"Mitsubishi Outlander", 433920000, "2FSKDev476Async", nullptr, 0}, + {"VAG 434.42 Mhz AM", 434420000, "Ook650Async", nullptr, 0}, +}; + +int car_model_count() { return (int)(sizeof(kModels) / sizeof(kModels[0])); } + +const CarModel *car_model_at(int index) { + if (index < 0 || index >= car_model_count()) return nullptr; + return &kModels[index]; +} + +bool car_model_apply(const CarModel *model) { + if (!model) return false; + + ELECHOUSE_cc1101.setSidle(); + + if (model->registers && model->registerCount) { + // Custom preset: write the raw register dump (0x00..0x2D), then restore + // the frequency (the dump's FREQ bytes are overridden by the model's). + for (uint8_t i = 0; i < model->registerCount; i++) + ELECHOUSE_cc1101.SpiWriteReg(i, model->registers[i]); + setMHZ(model->freqHz / 1000000.0f); + } else { + const RfPreset *preset = rf_find_preset(String(model->preset)); + const auto fsk = rf_apply_fsk_receive_profile( + model->preset, + [](uint8_t a, uint8_t v) { return ELECHOUSE_cc1101.SpiWriteReg(a, v); }, + [](uint8_t a) { return ELECHOUSE_cc1101.SpiReadReg(a); }); + if (fsk == RfFskReceiveProfileResult::NotFsk && preset) { + ELECHOUSE_cc1101.setModulation(preset->modulation); + ELECHOUSE_cc1101.setDeviation(preset->deviation ? preset->deviation : 1.58f); + ELECHOUSE_cc1101.setRxBW(preset->rxBW ? preset->rxBW : 270.83f); + ELECHOUSE_cc1101.setDRate(preset->dataRate ? preset->dataRate : 10.f); + ELECHOUSE_cc1101.setPktFormat(3); + setMHZ(model->freqHz / 1000000.0f); + } else if (fsk == RfFskReceiveProfileResult::Failed) { + return false; + } else { + // FSK profile applied; set frequency explicitly. + setMHZ(model->freqHz / 1000000.0f); + } + } + + ELECHOUSE_cc1101.SetRx(); + return true; +} diff --git a/src/modules/rf/protocols/rf_models.h b/src/modules/rf/protocols/rf_models.h new file mode 100644 index 0000000000..6ec6de4b5b --- /dev/null +++ b/src/modules/rf/protocols/rf_models.h @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// +// Part of Bruce (AGPL-3.0-or-later). Car-model database and custom radio +// profiles, ported from ProtoPirate (GPL-3.0-or-later), (C) RocketGod and the +// ProtoPirate contributors. See PROTOPIRATE_LICENSE and THIRD_PARTY.md. +// +// The "models database" is a small named list of receiver configurations: +// each entry binds a human name to a frequency and a radio preset. Entries +// using a *custom* preset carry a raw CC1101 register dump (Flipper +// "CustomPresetData" format, registers 0x00..0x2D) instead of a named preset. +#pragma once + +#include + +struct CarModel { + const char *name; + uint32_t freqHz; + const char *preset; // Bruce preset name, or "Custom" + const uint8_t *registers; // raw CC1101 registers (nullptr unless Custom) + uint8_t registerCount; +}; + +// Total number of models in the database. +int car_model_count(); + +// Model at index (0..count-1). Returns nullptr for out-of-range. +const CarModel *car_model_at(int index); + +// Apply a model's frequency + preset (or raw registers) to the CC1101. +// The radio must already be initialised (initRfModule). Returns false on +// failure. +bool car_model_apply(const CarModel *model); diff --git a/src/modules/rf/rf_analyze.cpp b/src/modules/rf/rf_analyze.cpp new file mode 100644 index 0000000000..22ce09d045 --- /dev/null +++ b/src/modules/rf/rf_analyze.cpp @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#include "rf_analyze.h" + +#include "core/display.h" +#include "core/type_convertion.h" +#include "protocols/rf_decoder.h" +#include "protocols/rf_fsk_receive_profile.h" +#include "protocols/rf_protocol_engine.h" +#include "rf_classify.h" +#include "rf_utils.h" +#include "structs.h" + +namespace { + +// Top of the report area, just below the title bar (matches rf_spectrum.cpp). +int report_top() { return BORDER_PAD_Y + 8 * FM + 2; } +uint16_t dim_color() { return blendColors(bruceConfig.bgColor, bruceConfig.priColor, 170); } + +void draw_report( + const RfClassifyResult &cls, const RfCodes &code, bool decoded, bool fskMode, float freq, bool have +) { + const uint16_t fg = bruceConfig.priColor; + const uint16_t bg = bruceConfig.bgColor; + const int x = BORDER_PAD_X; + const int lh = 8 * FP; + int y = report_top(); + + tft.setTextSize(FP); + tft.fillRect(0, y - 2, tftWidth, tftHeight - (y - 2), bg); + + auto line = [&](const String &s, uint16_t c) { + if (y + lh > tftHeight - 4) return; + tft.setTextColor(c, bg); + tft.drawString(s, x, y, 1); + y += lh; + }; + + if (!have) { + line("Waiting for a signal...", fg); + line(String(freq, 3) + " MHz", dim_color()); + line("[Sel] frequency [Esc] exit", dim_color()); + return; + } + + const char *mod = cls.modulation == RfClassifyMod::OOK ? "ASK/OOK" + : cls.modulation == RfClassifyMod::FSK ? "2-FSK (continuous)" + : "Unknown"; + line("RX: " + String(fskMode ? "2-FSK" : "ASK/OOK") + " @ " + String(freq, 3) + " MHz", dim_color()); + line("Modulation: " + String(mod) + " [" + String((int)(cls.confidence * 100)) + "%]", fg); + + if (cls.modulation == RfClassifyMod::OOK) + line("TE: " + String(cls.teUs) + "us bits: " + String(cls.bitCount), dim_color()); + else if (cls.modulation == RfClassifyMod::FSK) + line("Baud: " + String(cls.baud) + " sym/s", dim_color()); + + line("Pulses: " + String(cls.pulseCount) + " duty: " + String((int)(cls.dutyCycle * 100)) + "%", + dim_color()); + + if (decoded && code.protocol != "") { + String info = "Decoded: " + String(code.protocol); + if (code.fix != 0 && code.mf_name != "" && code.mf_name != "Unknown") + info += " (" + code.mf_name + ")"; + else if (code.key != 0) { + char hex[24]; + decimalToHexString(code.key, hex); + info += " key:" + String(hex); + } + line(info, fg); + } else { + line("Decoded: none", dim_color()); + } + + line("[Sel] frequency [Esc] exit", dim_color()); +} + +} // namespace + +void rf_analyze() { +#if !defined(LITE_VERSION) + if (bruceConfigPins.rfModule != CC1101_SPI_MODULE) { + displayError("Analyze needs a CC1101!", true); + return; + } + + float freq = bruceConfigPins.rfFreq; + if (!initRfModule("rx", freq)) { + displayError("CC1101 not found!", true); + return; + } + + // Configure the CC1101 async RX for OOK (false) or 2-FSK (true). + auto setMode = [&](bool fsk) { + ELECHOUSE_cc1101.setSidle(); + if (fsk) { + rf_apply_fsk_receive_profile( + "2FSKDev238Async", + [](uint8_t a, uint8_t v) { return ELECHOUSE_cc1101.SpiWriteReg(a, v); }, + [](uint8_t a) { return ELECHOUSE_cc1101.SpiReadReg(a); }); + } else { + ELECHOUSE_cc1101.setModulation(2); // ASK/OOK + ELECHOUSE_cc1101.setDeviation(1.58f); + ELECHOUSE_cc1101.setRxBW(270.83f); + ELECHOUSE_cc1101.setDRate(10.f); + ELECHOUSE_cc1101.setPktFormat(3); + } + ELECHOUSE_cc1101.SetRx(); + }; + + RfRxSession rx; + bool fskMode = false; + setMode(false); + if (!rx.begin(true)) { + deinitRfModule(); + return; + } + + drawMainBorderWithTitle("RF Auto Classify"); + + RfClassifyResult cls; + RfCodes code; + bool have = false, decoded = false; + unsigned long modeSince = millis(); + const unsigned long MODE_DWELL_MS = 600; // flip OOK<->FSK when idle this long + + draw_report(cls, code, false, fskMode, freq, false); + + while (1) { + if (check(EscPress)) break; + + std::vector durations; + if (rx.poll(durations)) { + cls = rf_classify(durations); + code = RfCodes{}; + decoded = cls.pulseCount >= 6 && + rf_protocol_decode_capture( + durations, (uint32_t)(freq * 1000000.0f), + fskMode ? "2FSKDev238Async" : "Ook270Async", code); + have = true; + modeSince = millis(); // keep this mode while a signal is present + draw_report(cls, code, decoded, fskMode, freq, have); + } else if (millis() - modeSince > MODE_DWELL_MS) { + // Quiet: flip the RX mode so both modulations get a listen window. + fskMode = !fskMode; + setMode(fskMode); + rx.end(); + rx.begin(true); + modeSince = millis(); + } + + if (setMHZMenu()) { + freq = bruceConfigPins.rfFreq; + setMode(fskMode); + rx.end(); + rx.begin(true); + modeSince = millis(); + drawMainBorderWithTitle("RF Auto Classify"); + draw_report(cls, code, decoded, fskMode, freq, have); + } + + vTaskDelay(pdMS_TO_TICKS(10)); + } + + rx.end(); + deinitRfModule(); + returnToMenu = true; +#else + displayError("Not available on Launcher version"); +#endif +} diff --git a/src/modules/rf/rf_analyze.h b/src/modules/rf/rf_analyze.h new file mode 100644 index 0000000000..8a4ade279d --- /dev/null +++ b/src/modules/rf/rf_analyze.h @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#ifndef __RF_ANALYZE_H__ +#define __RF_ANALYZE_H__ + +// "Analyze" feature: captures a sub-GHz signal, auto-detects its modulation +// (ASK/OOK vs 2-FSK) and symbol timing, then runs the protocol decoder to +// suggest what it is. CC1101 required. +void rf_analyze(); + +#endif diff --git a/src/modules/rf/rf_classify.cpp b/src/modules/rf/rf_classify.cpp new file mode 100644 index 0000000000..b84d428c28 --- /dev/null +++ b/src/modules/rf/rf_classify.cpp @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#include "rf_classify.h" + +#include + +namespace { + +// Median of an int vector (sorts a copy). Returns 0 when empty. +int median_of(std::vector v) { + if (v.empty()) return 0; + std::sort(v.begin(), v.end()); + const size_t n = v.size(); + if (n & 1u) return v[n / 2]; + return (int)(((long)v[n / 2 - 1] + (long)v[n / 2]) / 2); +} + +float clamp01(float v) { return v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v); } + +} // namespace + +RfClassifyResult rf_classify(const std::vector &durations) { + RfClassifyResult r; + + // Collect absolute widths, splitting into HIGH (carrier) and LOW (gap) + // halves. The RMT RX stream alternates HIGH / LOW, so sign is meaningful. + std::vector absv, highs, lows; + long long sumHigh = 0, sumTotal = 0; + absv.reserve(durations.size()); + for (int d : durations) { + if (d == 0) continue; + const int a = d < 0 ? -d : d; + if (a < 4) continue; // drop sub-4us glitches / ringing + absv.push_back(a); + sumTotal += a; + if (d > 0) { + highs.push_back(a); + sumHigh += a; + } else { + lows.push_back(a); + } + } + + r.pulseCount = (int)absv.size(); + if (absv.size() < 6) return r; // too few pulses: UNKNOWN + + r.dutyCycle = sumTotal ? (float)((double)sumHigh / (double)sumTotal) : 0.0f; + r.minUs = *std::min_element(absv.begin(), absv.end()); + r.maxUs = *std::max_element(absv.begin(), absv.end()); + r.medianUs = median_of(absv); + + const int medHigh = median_of(highs); + const int medLow = median_of(lows); + + // Spread: how far the longest pulse sits from the typical pulse. OOK has a + // sync pulse / long off-gaps (spread >> 1); FSK is tightly clustered. + const float spread = r.medianUs > 0 ? (float)r.maxUs / (float)r.medianUs : 1.0f; + const float hlRatio = + (medHigh > 0 && medLow > 0) + ? (float)std::max(medHigh, medLow) / (float)std::min(medHigh, medLow) + : 1.0f; + + if (spread >= 4.0f || (medHigh > 0 && medLow >= 3 * medHigh)) { + // Clear OOK signature: long sync/gap pulses dominate the spread. + r.modulation = RfClassifyMod::OOK; + r.confidence = clamp01(0.55f + (spread - 4.0f) * 0.05f); + } else if (spread < 2.5f && hlRatio < 2.5f && r.dutyCycle >= 0.30f && + r.dutyCycle <= 0.70f) { + // Continuous, balanced square wave => 2-FSK/GFSK/MSK. + r.modulation = RfClassifyMod::FSK; + r.confidence = spread < 1.8f ? 0.9f : 0.7f; + } else { + // Ambiguous: default to OOK (the scan/RX default) with low confidence. + r.modulation = RfClassifyMod::OOK; + r.confidence = 0.4f; + } + + if (r.modulation == RfClassifyMod::OOK) { + // Base pulse period from the HIGH bursts, dropping sync outliers. + int te = medHigh > 0 ? medHigh : r.minUs; + if (medHigh > 0) { + std::vector trimmed; + for (int a : highs) + if (a <= medHigh * 3) trimmed.push_back(a); + if (!trimmed.empty()) te = median_of(trimmed); + } + r.teUs = std::max(20, te); + // Payload transitions: pulses within 0.5x..2.2x of the base period. + int bits = 0; + for (int a : absv) + if (a >= r.teUs / 2 && a <= r.teUs * 2.2f) bits++; + r.bitCount = bits; + } else if (r.modulation == RfClassifyMod::FSK) { + // Each level of the demodulated square wave is ~one symbol period. + const int period = std::max(4, r.medianUs); + r.baud = (int)(1000000.0f / (float)period); + r.bitCount = r.pulseCount; // continuous stream: transitions ~= symbols + } + + return r; +} diff --git a/src/modules/rf/rf_classify.h b/src/modules/rf/rf_classify.h new file mode 100644 index 0000000000..fe0677505d --- /dev/null +++ b/src/modules/rf/rf_classify.h @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// +// Part of Bruce (AGPL-3.0-or-later). +// +// Sub-GHz modulation auto-classifier. Operates purely on a captured pulse +// train (signed microsecond durations, HIGH > 0 / LOW < 0 as returned by the +// RMT RX session) and estimates the modulation family and the symbol timing +// without touching the radio or any protocol decoder. +// +// The heuristics mirror the classical structure of demodulated sub-GHz +// bitstreams: +// - ASK/OOK : bursts of carrier (short highs) separated by long off gaps, +// typically with a sync pulse. Large max/median pulse spread +// and a low duty cycle. +// - 2-FSK : a continuous square wave (both mark and space are carrier), +// so pulse widths cluster tightly around one symbol period and +// the duty cycle is ~50%. +#pragma once + +#include +#include + +// Classification result families. +enum class RfClassifyMod : uint8_t { + UNKNOWN = 0, // too few pulses to say anything + OOK = 1, // ASK/OOK + FSK = 2, // 2-FSK / GFSK / MSK continuous bitstream +}; + +struct RfClassifyResult { + RfClassifyMod modulation = RfClassifyMod::UNKNOWN; + float confidence = 0.0f; // 0..1 + int teUs = 0; // OOK: base pulse period (µs) + int baud = 0; // FSK: estimated symbol rate (symbols/s) + int bitCount = 0; // estimated payload transitions + float dutyCycle = 0.0f; // high-time fraction 0..1 + int pulseCount = 0; + int minUs = 0; // shortest pulse seen + int medianUs = 0; // median pulse width + int maxUs = 0; // longest pulse seen +}; + +// Classify a captured pulse train. Pure function: no globals, no radio, no UI. +RfClassifyResult rf_classify(const std::vector &durations); diff --git a/src/modules/rf/rf_protopirate.cpp b/src/modules/rf/rf_protopirate.cpp index 52617f133d..4cfe303ffa 100644 --- a/src/modules/rf/rf_protopirate.cpp +++ b/src/modules/rf/rf_protopirate.cpp @@ -8,6 +8,7 @@ #include "protocols/rf_decode_limits.h" #include "protocols/rf_protocol_engine.h" #include "protocols/rf_keeloq.h" // keeloq_engine_keystore_load/free +#include "protocols/rf_models.h" // car-model database + custom radio profiles #include "rf_scan.h" #include #include @@ -160,6 +161,7 @@ class ProtoPirate { const char *labels[4] = {"AM650", "FM476", "AM270", "FM238"}; int frequencyIndex = 1, presetIndex = -1; bool hopping = false, receiveRequested = false; + bool customActive = false; // a custom (raw-register) model preset is applied size_t historyBytes = 0; size_t historyMemoryBytes() const { size_t bytes = 0; @@ -575,10 +577,13 @@ class ProtoPirate { "Unmatched: " + String(misses) + (history.empty() ? " SEL: settings" : " SEL: signal"), rows, selected, scrollOffset, 12, &displayState ); - String raw = rfReceiveSignal(frequencies[fi], timeout, true, true, presets[pi], true, &receiveSession); + String raw = rfReceiveSignal( + frequencies[fi], timeout, true, true, + customActive ? String("") : String(presets[pi]), true, &receiveSession + ); if (EscPress) continue; // preserve Back for the list's exit handler if (!raw.isEmpty()) { - if (field(raw, "Bruce_RX_Preset") != presets[pi]) { + if (!customActive && field(raw, "Bruce_RX_Preset") != presets[pi]) { displayError("Receive profile mismatch", true); return; } @@ -648,6 +653,30 @@ class ProtoPirate { if (receiveRequested) return; } } + void chooseModel() { + std::vector names; + for (int i = 0; i < car_model_count(); i++) names.push_back(car_model_at(i)->name); + drawCaptureBackground(); + int n = choose("Car model", names, 0, MENU_TYPE_REGULAR); + if (n < 0) return; + const CarModel *m = car_model_at(n); + if (!m) return; + + // Set the frequency (and, for custom models, apply the raw registers now). + frequencies.clear(); + frequencies.push_back(m->freqHz / 1000000.0f); + frequencyIndex = 0; + hopping = false; + + customActive = (m->registers && m->registerCount); + if (customActive) { + presetIndex = 0; + if (initRfModule("rx", m->freqHz / 1000000.0f)) car_model_apply(m); + } else { + presetIndex = !strcmp(m->preset, "2FSKDev476Async") ? 1 : 0; + } + } + void settings() { for (;;) { drawCaptureBackground(); @@ -656,10 +685,11 @@ class ProtoPirate { {"Frequency: " + String(frequencies[frequencyIndex]) + " MHz", "Preset: " + String(presetIndex < 0 ? "Auto" : labels[presetIndex]), "Frequency hopping: " + String(hopping ? "ON" : "OFF"), + "Car model...", "Back"}, 0, MENU_TYPE_REGULAR ); - if (action < 0 || action == 3) return; + if (action < 0 || action == 4) return; if (action == 0) { std::vector list; for (float f : frequencies) list.push_back(String(f) + " MHz"); @@ -673,7 +703,11 @@ class ProtoPirate { MENU_TYPE_REGULAR ); if (n >= 0) presetIndex = n - 1; - } else hopping = !hopping; + } else if (action == 2) { + hopping = !hopping; + } else { + chooseModel(); + } } } @@ -720,8 +754,8 @@ class ProtoPirate { "Native Bruce UI and one shared RF engine.\nRocketGod ProtoPirate 4.0 / 4c9afe58\n\n" "Same codecs are used by RF Scan, file handling and the JS app.\n" "Sending always requires confirmation. Encoding does not prove receiver acceptance.\n" - "Custom radio profiles, encrypted ProtoPirate keystores, model database, remote analyzer " - "and brute-force recovery are not ported." + "Car-model database + custom radio profiles: ported.\n" + "Encrypted ProtoPirate keystores, remote analyzer and brute-force recovery are not ported." ); } deinitRfModule(); diff --git a/src/modules/rf/rf_remote_analyzer.cpp b/src/modules/rf/rf_remote_analyzer.cpp new file mode 100644 index 0000000000..0f021e8d49 --- /dev/null +++ b/src/modules/rf/rf_remote_analyzer.cpp @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#include "rf_remote_analyzer.h" + +#include "core/display.h" +#include "rf_utils.h" +#include "structs.h" + +namespace { + +constexpr float kTrigger = -90.0f; // dBm threshold for a "found" carrier +constexpr float kAmDrop = 6.0f; // dB drop on both sides => steep (AM) peak +constexpr uint32_t kFineStepHz = 20000; +constexpr uint32_t kFineSpanHz = 300000; +constexpr int kFinePoints = 31; // 600 kHz / 20 kHz + 1 + +int row_top() { return BORDER_PAD_Y + 8 * FM + 2; } +uint16_t dim() { return blendColors(bruceConfig.bgColor, bruceConfig.priColor, 170); } + +float rssiAt(float mhz) { + setMHZ(mhz); + tft.drawPixel(0, 0, 0); // shared SPI with TFT: keep the bus sane + vTaskDelay(pdMS_TO_TICKS(4)); + return (float)ELECHOUSE_cc1101.getRssi(); +} + +// Redraw only the result region (below the title) when the content changed. +void drawResult(bool found, float freq, float rssi, bool isAm) { + const int y0 = row_top() - 2; + tft.fillRect(0, y0, tftWidth, tftHeight - y0 - (LH * FP + 10), bruceConfig.bgColor); + tft.setTextSize(FP); + int y = row_top(); + const int lh = LH * FP + 6; + + tft.setTextColor(bruceConfig.priColor, bruceConfig.bgColor); + if (!found) { + tft.drawString("No carrier above " + String((int)kTrigger) + " dBm", BORDER_PAD_X, y, 1); + y += lh; + } else { + tft.drawString("Signal: " + String(freq, 3) + " MHz", BORDER_PAD_X, y, 1); + y += lh; + tft.drawString("RSSI: " + String((int)rssi) + " dBm", BORDER_PAD_X, y, 1); + y += lh; + tft.drawString( + isAm ? "Modulation: AM (ASK/OOK)" : "Modulation: FM / wide", BORDER_PAD_X, y, 1); + y += lh; + } + + tft.setTextColor(dim(), bruceConfig.bgColor); + tft.drawString("Scanning...", BORDER_PAD_X, y, 1); +} + +} // namespace + +void rf_remote_analyzer() { +#if !defined(LITE_VERSION) + if (bruceConfigPins.rfModule != CC1101_SPI_MODULE) { + displayError("Remote analyzer needs a CC1101!", true); + return; + } + if (!initRfModule("rx", 433.92)) { + displayError("CC1101 not found!", true); + return; + } + + // Draw the static frame once — redrawing it each pass is what caused the + // text to flicker on and off. + drawMainBorderWithTitle("Remote Analyzer"); + tft.setTextSize(FP); + tft.setTextColor(dim(), bruceConfig.bgColor); + tft.drawString("[ESC] back", BORDER_PAD_X, tftHeight - LH * FP - 8, 1); + + const int freqCount = sizeof(subghz_frequency_list) / sizeof(subghz_frequency_list[0]); + + // Cache the displayed result so the screen is only touched when it changes. + String lastKey = ""; + + while (!check(EscPress)) { + // ---- Coarse scan: strongest carrier across the band ---- + float bestFreq = 0, bestRssi = -127.0f; + for (int i = 0; i < freqCount && !check(EscPress); i++) { + const float f = subghz_frequency_list[i]; + const float r = rssiAt(f); + if (r > bestRssi) { + bestRssi = r; + bestFreq = f; + } + } + if (check(EscPress)) break; + + bool found = bestRssi > kTrigger; + float fineFreq = bestFreq, fineRssi = bestRssi; + bool isAm = false; + + // ---- Fine scan: pinpoint ±300 kHz, classify peak shape ---- + if (found) { + float sweep[kFinePoints]; + int idx = 0; + float peakRssi = -999.0f; + int peakIdx = 0; + const uint32_t center = (uint32_t)(bestFreq * 1000000.0f); + for (uint32_t f = center - kFineSpanHz; f < center + kFineSpanHz && !check(EscPress); + f += kFineStepHz) { + const float r = rssiAt(f / 1000000.0f); + sweep[idx] = r; + if (r > peakRssi) { + peakRssi = r; + peakIdx = idx; + } + idx++; + } + const float left = peakIdx > 0 ? sweep[peakIdx - 1] : peakRssi; + const float right = peakIdx + 1 < idx ? sweep[peakIdx + 1] : peakRssi; + isAm = (peakRssi - left > kAmDrop) && (peakRssi - right > kAmDrop); + fineRssi = peakRssi; + fineFreq = (center - kFineSpanHz + (uint32_t)peakIdx * kFineStepHz) / 1000000.0f; + } + + // Only repaint when the result actually changed (no flicker on stable signals). + String key = String(found) + "|" + String((int)(fineFreq * 1000)) + "|" + + String((int)fineRssi) + "|" + String(isAm); + if (key != lastKey) { + lastKey = key; + drawResult(found, fineFreq, fineRssi, isAm); + } + + vTaskDelay(pdMS_TO_TICKS(150)); + } + + deinitRfModule(); + returnToMenu = true; +#else + displayError("Not available on Launcher version"); +#endif +} diff --git a/src/modules/rf/rf_remote_analyzer.h b/src/modules/rf/rf_remote_analyzer.h new file mode 100644 index 0000000000..1647af1d1b --- /dev/null +++ b/src/modules/rf/rf_remote_analyzer.h @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#ifndef __RF_REMOTE_ANALYZER_H__ +#define __RF_REMOTE_ANALYZER_H__ + +// "Remote analyzer" (ported from ProtoPirate's RemoteAnalyzer worker): sweeps +// the sub-GHz band for the strongest carrier, pinpoints it with a fine sweep, +// and classifies it as AM (ASK/OOK, steep peak) vs FM/unknown (broad peak). +// CC1101 required. +void rf_remote_analyzer(); + +#endif diff --git a/src/modules/rf/rf_rolling.cpp b/src/modules/rf/rf_rolling.cpp new file mode 100644 index 0000000000..df9f39c0f2 --- /dev/null +++ b/src/modules/rf/rf_rolling.cpp @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#include "rf_rolling.h" + +#include "core/display.h" +#include "core/type_convertion.h" +#include "protocols/rf_decoder.h" +#include "protocols/rf_protocol_engine.h" +#include "rf_scan.h" // rf_try_keeloq +#include "rf_utils.h" +#include "structs.h" + +namespace { + +struct RollingEntry { + uint32_t serial = 0; + uint8_t btn = 0; + uint32_t cnt = 0; + String mfr; + unsigned long ms = 0; +}; + +void hex4(uint32_t v, char *out, size_t n) { snprintf(out, n, "%04lX", (unsigned long)(v & 0xFFFF)); } +void hex8(uint32_t v, char *out, size_t n) { snprintf(out, n, "%08lX", (unsigned long)v); } + +void draw_rolling(const std::vector &hist) { + drawMainBorderWithTitle("Rolling Code"); + const int x = BORDER_PAD_X; + const int lh = LH * FP + 6; + int y = BORDER_PAD_Y + FM * LH + 6; + tft.setTextSize(FP); + + if (hist.empty()) { + tft.setTextColor(bruceConfig.priColor, bruceConfig.bgColor); + tft.drawString("Press the remote...", x, y, 1); + tft.drawString("(captures KeeLoq / rolling codes)", x, y + lh, 1); + return; + } + + const RollingEntry &last = hist.back(); + + // Verdict: compare the last two distinct counters. + String verdict = "Fixed code (counter unchanged)"; + if (hist.size() >= 2) { + const RollingEntry &prev = hist[hist.size() - 2]; + if (prev.cnt != last.cnt) { + int32_t delta = (int32_t)(last.cnt - prev.cnt); + char d[16]; + snprintf(d, sizeof(d), "%+d", (int)delta); + verdict = String("Rolling: counter ") + d; + } + } + + tft.setTextColor(bruceConfig.priColor, bruceConfig.bgColor); + tft.drawString(verdict, x, y, 1); + y += lh + 2; + + char buf[24]; + tft.setTextColor(blendColors(bruceConfig.bgColor, bruceConfig.priColor, 170), bruceConfig.bgColor); + tft.drawString("Mfr: " + last.mfr, x, y, 1); + y += lh; + hex8(last.serial, buf, sizeof(buf)); + tft.drawString("Serial: " + String(buf), x, y, 1); + y += lh; + tft.drawString("Button: " + String(last.btn), x, y, 1); + y += lh; + hex4(last.cnt, buf, sizeof(buf)); + tft.drawString("Counter: " + String(buf) + " (" + String(last.cnt) + ")", x, y, 1); + y += lh + 2; + + // Recent counter history (most recent last). + const size_t shown = hist.size() > 4 ? hist.size() - 4 : 0; + String seq = "seq: "; + for (size_t i = shown; i < hist.size(); i++) { + hex4(hist[i].cnt, buf, sizeof(buf)); + if (i > shown) seq += " > "; + seq += buf; + } + tft.setTextColor(blendColors(bruceConfig.bgColor, bruceConfig.priColor, 120), bruceConfig.bgColor); + tft.drawString(seq, x, y, 1); +} + +} // namespace + +void rf_rolling_code() { +#if !defined(LITE_VERSION) + if (bruceConfigPins.rfModule != CC1101_SPI_MODULE) { + displayError("Rolling Code needs a CC1101!", true); + return; + } + float freq = bruceConfigPins.rfFreq; + if (!initRfModule("rx", freq)) { + displayError("CC1101 not found!", true); + return; + } + + RfRxSession rx; + if (!rx.begin()) { + deinitRfModule(); + return; + } + + std::vector hist; + draw_rolling(hist); + + while (1) { + if (check(EscPress)) break; + + std::vector durations; + if (rx.poll(durations)) { + RfCodes code; + if (rf_try_keeloq(durations, code)) { + RollingEntry e; + e.serial = code.serial; + e.btn = code.btn; + e.cnt = code.cnt; + e.mfr = code.mf_name.isEmpty() ? "Unknown" : code.mf_name; + e.ms = millis(); + // Skip exact duplicate frames (same press re-transmitted). + if (hist.empty() || hist.back().cnt != e.cnt || hist.back().btn != e.btn || + hist.back().serial != e.serial) { + hist.push_back(e); + if (hist.size() > 8) hist.erase(hist.begin()); + } + draw_rolling(hist); + } else if (rf_protocol_decode_capture( + durations, (uint32_t)(freq * 1000000.0f), "Ook270Async", code)) { + // Non-KeeLoq rolling/fixed code (e.g. Somfy, Nice, Came). + RollingEntry e; + e.serial = code.serial; + e.btn = code.btn; + e.cnt = code.cnt; + e.mfr = code.protocol; + e.ms = millis(); + if (hist.empty() || hist.back().cnt != e.cnt || hist.back().btn != e.btn || + hist.back().serial != e.serial) { + hist.push_back(e); + if (hist.size() > 8) hist.erase(hist.begin()); + } + draw_rolling(hist); + } + } + + if (setMHZMenu()) { + freq = bruceConfigPins.rfFreq; + rx.end(); + rx.begin(); + } + vTaskDelay(pdMS_TO_TICKS(10)); + } + + rx.end(); + deinitRfModule(); + returnToMenu = true; +#else + displayError("Not available on Launcher version"); +#endif +} diff --git a/src/modules/rf/rf_rolling.h b/src/modules/rf/rf_rolling.h new file mode 100644 index 0000000000..6f586e4dac --- /dev/null +++ b/src/modules/rf/rf_rolling.h @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +#ifndef __RF_ROLLING_H__ +#define __RF_ROLLING_H__ + +// Rolling-code analyzer. Captures KeeLoq (and other decodable) frames, extracts +// the manufacturer / serial / button / counter, and tracks the counter across +// successive presses to show whether the remote is rolling (counter advances) +// or fixed (counter unchanged). CC1101 required. +void rf_rolling_code(); + +#endif diff --git a/src/modules/rf/rf_scan.h b/src/modules/rf/rf_scan.h index 934af1c5e6..9646eec265 100644 --- a/src/modules/rf/rf_scan.h +++ b/src/modules/rf/rf_scan.h @@ -113,6 +113,11 @@ class RFScan { String capture_label(int index) const; }; +// Try to decode a KeeLoq frame and resolve its manufacturer/serial/button/counter +// (fills key/fix/encrypted/serial/btn + mf_name/cnt via the keystore). Shared by +// the scan path and the rolling-code analyzer. +bool rf_try_keeloq(const std::vector &durations, RfCodes &received); + void display_info( RfCodes received, int signals, bool ReadRAW = false, bool codesOnly = false, bool autoSave = false, const String &title = "", bool headless = false diff --git a/src/modules/wifi/sniffer.cpp b/src/modules/wifi/sniffer.cpp index 7cc72c48de..6546825f52 100644 --- a/src/modules/wifi/sniffer.cpp +++ b/src/modules/wifi/sniffer.cpp @@ -29,6 +29,7 @@ #include "FS.h" #include "core/display.h" #include "core/mykeyboard.h" +#include "core/radio_mem.h" #include "core/sd_functions.h" #include "core/wifi/webInterface.h" #include "core/wifi/wifi_common.h" @@ -781,10 +782,20 @@ static String currentModeString() { } } +// Static storage so the sniffer's queue never depends on heap fragmentation. +// The Cardputer has no PSRAM and the heap is easily fragmented after BLE/RF use, +// which made xQueueCreate() fail with "Sniffer queue error". +static StaticQueue_t snifferQueueStruct; +static uint8_t snifferQueueStorage[SNIFFER_QUEUE_DEPTH * sizeof(SnifferQueueItem)]; + static bool ensureSnifferBackend() { if (!fileMutex) { fileMutex = xSemaphoreCreateMutexStatic(&fileMutexBuffer); } if (!handshakeMutex) { handshakeMutex = xSemaphoreCreateMutexStatic(&handshakeMutexBuffer); } - if (!snifferQueue) { snifferQueue = xQueueCreate(SNIFFER_QUEUE_DEPTH, sizeof(SnifferQueueItem)); } + if (!snifferQueue) { + snifferQueue = xQueueCreateStatic( + SNIFFER_QUEUE_DEPTH, sizeof(SnifferQueueItem), snifferQueueStorage, &snifferQueueStruct + ); + } if (!snifferQueue) { return false; } if (!snifferWriterHandle) { #if SOC_CPU_CORES_NUM > 1 @@ -1138,6 +1149,14 @@ void sniffer_setup() { // Stop WebUI before setting WiFi mode for sniffer cleanlyStopWebUiForWiFiFeature(); + // Free any WiFi stack left over from a prior scan/connect so the sniffer's + // queue/task allocations have contiguous memory (no PSRAM on the Cardputer). + if (WiFi.getMode() != WIFI_MODE_NULL) { + wifiDisconnect(); + WiFi.mode(WIFI_OFF); + delay(150); + } + FS *Fs; int redraw = true; bool clearScreen = true; @@ -1180,25 +1199,30 @@ void sniffer_setup() { beaconRawCache.clear(); /* setup wifi */ + if (!radioHasMemForWifi()) { + displayError("Low RAM: free SD/BLE first", true); + return; + } ensureWifiPlatform(); nvs_flash_init(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + // The Cardputer has no PSRAM and only ~31 KB of contiguous DMA after boot, + // so the ESP-IDF defaults (16 static TX + 10 static RX buffers) don't fit. + // Match the Arduino core's reduced config, which does (this is why the + // "Connect to Wifi" scan works but the sniffer's default init did not). + cfg.static_tx_buf_num = 0; + cfg.dynamic_tx_buf_num = 32; + cfg.tx_buf_type = 1; + cfg.cache_tx_buf_num = 4; // can't be zero! + cfg.static_rx_buf_num = 4; + cfg.dynamic_rx_buf_num = 32; ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); - wifi_config_t wifi_config; - strlcpy((char *)wifi_config.ap.ssid, "BruceSniffer", sizeof(wifi_config.ap.ssid)); - strlcpy((char *)wifi_config.ap.password, "brucenet", sizeof(wifi_config.ap.password)); - wifi_config.ap.ssid_len = strlen("BruceSniffer"); - wifi_config.ap.channel = 1; // Channel - wifi_config.ap.authmode = WIFI_AUTH_WPA2_PSK; // auth mode - wifi_config.ap.ssid_hidden = 1; // 1 to hidden SSID, 0 to visivle - wifi_config.ap.max_connection = 2; // Max connections - wifi_config.ap.beacon_interval = 100; // beacon interval in ms - - // Configura o modo AP - ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP)); - ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config)); + // STA + promiscuous (same as the SDR feature) instead of AP mode: running an + // AP allocates the hostapd structures, which OOMs the PSRAM-less Cardputer + // (LoadProhibited inside ieee80211_hostap_attach). Capture doesn't need an AP. + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_start()); esp_wifi_set_promiscuous(true); esp_wifi_set_promiscuous_rx_cb(sniffer); From dc80c2e61502f3003f01e166e07aca58ca0355fb Mon Sep 17 00:00:00 2001 From: TurbulentGoat <131882443+TurbulentGoat@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:18:13 +0800 Subject: [PATCH 2/4] Fix border erasure in RF auto-classify and remote analyzer The content-clear fillRect() spanned the full screen width, erasing the left/right (and bottom, for Analyze) border. Restrict clearing to the content area inside the border. --- src/modules/rf/rf_analyze.cpp | 4 +++- src/modules/rf/rf_remote_analyzer.cpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/modules/rf/rf_analyze.cpp b/src/modules/rf/rf_analyze.cpp index 22ce09d045..60df5c0298 100644 --- a/src/modules/rf/rf_analyze.cpp +++ b/src/modules/rf/rf_analyze.cpp @@ -26,7 +26,9 @@ void draw_report( int y = report_top(); tft.setTextSize(FP); - tft.fillRect(0, y - 2, tftWidth, tftHeight - (y - 2), bg); + // Clear only the content area (inside the border), not the full screen, + // otherwise the left/right/bottom border gets erased. + tft.fillRect(BORDER_PAD_X, y - 2, tftWidth - 2 * BORDER_PAD_X, tftHeight - (y - 2) - 6, bg); auto line = [&](const String &s, uint16_t c) { if (y + lh > tftHeight - 4) return; diff --git a/src/modules/rf/rf_remote_analyzer.cpp b/src/modules/rf/rf_remote_analyzer.cpp index 0f021e8d49..1480001253 100644 --- a/src/modules/rf/rf_remote_analyzer.cpp +++ b/src/modules/rf/rf_remote_analyzer.cpp @@ -26,7 +26,7 @@ float rssiAt(float mhz) { // Redraw only the result region (below the title) when the content changed. void drawResult(bool found, float freq, float rssi, bool isAm) { const int y0 = row_top() - 2; - tft.fillRect(0, y0, tftWidth, tftHeight - y0 - (LH * FP + 10), bruceConfig.bgColor); + tft.fillRect(BORDER_PAD_X, y0, tftWidth - 2 * BORDER_PAD_X, tftHeight - y0 - (LH * FP + 10), bruceConfig.bgColor); tft.setTextSize(FP); int y = row_top(); const int lh = LH * FP + 6; From fbb81af20f67759d4897f18da831230236012bc6 Mon Sep 17 00:00:00 2001 From: TurbulentGoat <131882443+TurbulentGoat@users.noreply.github.com> Date: Sat, 14 Nov 2026 08:11:16 +0800 Subject: [PATCH 3/4] Fix evil portal reboot on no-PSRAM boards (Cardputer ADV) AP mode (hostapd) OOM'd against the ~31 KB of contiguous DMA left while Bruce's 64 KB SDR bank is fenced off. Release the SDR bank before starting the AP, free any prior WiFi stack, guard on radioHasMemForWifi(), and use max_connection=1 to shrink the station table. --- src/modules/wifi/evil_portal.cpp | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/modules/wifi/evil_portal.cpp b/src/modules/wifi/evil_portal.cpp index 59ed80ed9a..fd2446bbd2 100644 --- a/src/modules/wifi/evil_portal.cpp +++ b/src/modules/wifi/evil_portal.cpp @@ -2,6 +2,7 @@ #include "core/config.h" #include "core/display.h" #include "core/mykeyboard.h" +#include "core/radio_mem.h" #include "core/sd_functions.h" #include "core/utils.h" #include "core/wifi/webInterface.h" @@ -27,6 +28,24 @@ EvilPortal::EvilPortal( if (!setup()) return; cleanlyStopWebUiForWiFiFeature(); + + // Free any leftover WiFi stack (e.g. from a prior scan/connect) so the AP + + // web server allocations have room, and refuse cleanly if it won't fit. + // The Cardputer has no PSRAM, so AP mode is memory-tight (same OOM that + // affected the sniffer). + if (WiFi.getMode() != WIFI_MODE_NULL) { + WiFi.mode(WIFI_OFF); + delay(150); + } + // Release the SDR jammer's reserved 64 KB bank: AP mode (hostapd) needs far + // more contiguous DMA than the ~31 KB left while the bank is fenced off. + // (The SDR jammer will require a reboot afterwards.) + sdrBankReleaseForRadio(); + if (!radioHasMemForWifi()) { + displayError("Low RAM: reboot and retry", true); + return; + } + beginAP(); if (!_backgroundMode) { loop(); } } @@ -133,7 +152,10 @@ void EvilPortal::beginAP() { if (!WiFi.softAPConfig(apGateway, apGateway, IPAddress(255, 255, 255, 0))) { Serial.println("[PORTAL] softAPConfig failed"); } - if (!WiFi.softAP(apName, emptyString, _channel)) { + // max_connection=1: the Cardputer has no PSRAM and the AP hostapd allocation + // OOMs with the default (4). One client is enough for a captive portal and + // shrinks the station table. + if (!WiFi.softAP(apName, emptyString, _channel, 0, 1)) { Serial.printf("[PORTAL] softAP failed for SSID '%s' on ch%d\n", apName.c_str(), _channel); } wifiConnected = true; @@ -275,7 +297,7 @@ void EvilPortal::restartWiFi(bool reset) { _captiveHandler = nullptr; wifiDisconnect(); - WiFi.softAP(apName, emptyString, _channel); + WiFi.softAP(apName, emptyString, _channel, 0, 1); vTaskDelay(100 / portTICK_PERIOD_MS); setupRoutes(); From b6ef446a9f57cbdd0691bd28e553f6cfc39a35a1 Mon Sep 17 00:00:00 2001 From: TurbulentGoat <131882443+TurbulentGoat@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:19:00 +0800 Subject: [PATCH 4/4] fixing config issue --- src/core/config.cpp | 7 ++++- src/core/menu_items/ConfigMenu.cpp | 26 ++++++++-------- src/modules/pwnagotchi/pwnagotchi.cpp | 14 +++++++-- src/modules/pwnagotchi/pwnagotchi.h | 2 +- src/modules/pwnagotchi/pwngrid.cpp | 43 +++++++++++++++++++++++---- src/modules/pwnagotchi/pwngrid.h | 8 ++++- src/modules/pwnagotchi/spam.cpp | 14 +++++---- 7 files changed, 85 insertions(+), 29 deletions(-) diff --git a/src/core/config.cpp b/src/core/config.cpp index e7ceca143c..e3c7fcfadb 100644 --- a/src/core/config.cpp +++ b/src/core/config.cpp @@ -114,7 +114,12 @@ void BruceConfig::fromFile(bool checkFS) { // Deserialize the JSON document JsonDocument jsonDoc; if (deserializeJson(jsonDoc, file)) { - Serial.println("Failed to read config file, using default configuration"); + Serial.printf( + "Failed to read config file %s on %s (invalid JSON or read error), using default configuration\n", + filepath, + fs == &LittleFS ? "LittleFS" : "SD" + ); + file.close(); return; } file.close(); diff --git a/src/core/menu_items/ConfigMenu.cpp b/src/core/menu_items/ConfigMenu.cpp index 6e44fd4dc0..5adcca0b6b 100644 --- a/src/core/menu_items/ConfigMenu.cpp +++ b/src/core/menu_items/ConfigMenu.cpp @@ -63,16 +63,16 @@ void ConfigMenu::optionsMenu() { void ConfigMenu::displayUIMenu() { while (true) { std::vector