diff options
| author | BEAST <macbook@Macbooks-MacBook-Pro-2.local> | 2026-11-16 19:23:09 +0530 |
|---|---|---|
| committer | BEAST <macbook@Macbooks-MacBook-Pro-2.local> | 2026-11-16 19:23:09 +0530 |
| commit | 7764125350e66e464dded24ca8cf69a7e1ecef8d (patch) | |
| tree | e01f8b3a15fe905d6e5ccc3da6822df238b49030 /RobotFirmware/lib | |
Add local project files
Diffstat (limited to 'RobotFirmware/lib')
21 files changed, 1563 insertions, 0 deletions
diff --git a/RobotFirmware/lib/HexaNRL/build-manifest.json b/RobotFirmware/lib/HexaNRL/build-manifest.json new file mode 100644 index 0000000..13da83a --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/build-manifest.json @@ -0,0 +1,72 @@ +{ + "source_lib": "RobotFirmware\\lib\\HexaNRL", + "sdk_version": "1.4.1", + "built_from_commit": "036661d7fa9340e198bf3f6d376121ae8c214f59", + "built_at": "2026-10-10T14:36:33.316861Z", + "harvested_from_project": "RobotFirmware", + "harvested_env": "robot", + "cxx_path": "C:\\Users\\thein\\.platformio\\packages\\toolchain-xtensa-esp32s3\\bin\\xtensa-esp32s3-elf-g++.exe", + "cxx_flags": [ + "-std=gnu++17", + "-fexceptions", + "-fno-rtti", + "-Os", + "-mlongcalls", + "-ffunction-sections", + "-fdata-sections", + "-Wno-error=unused-function", + "-Wno-error=unused-variable", + "-Wno-error=deprecated-declarations", + "-Wno-unused-parameter", + "-Wno-sign-compare", + "-ggdb", + "-freorder-blocks", + "-Wwrite-strings", + "-fstack-protector", + "-fstrict-volatile-bitfields", + "-Wno-error=unused-but-set-variable", + "-fno-jump-tables", + "-fno-tree-switch-conversion", + "-MMD", + "-g0", + "-fno-rtti", + "-fno-exceptions", + "-fno-asynchronous-unwind-tables" + ], + "defines": [ + "PLATFORMIO=60200", + "ARDUINO_ESP32S3_DEV", + "ARDUINO_USB_MODE=1", + "ARDUINO_RUNNING_CORE=1", + "ARDUINO_EVENT_RUNNING_CORE=1", + "CONFIG_FREERTOS_HZ=1000", + "CORE_DEBUG_LEVEL=3", + "ARDUINO_USB_MODE=1", + "ARDUINO_USB_CDC_ON_BOOT=1", + "HAVE_CONFIG_H", + "MBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\"", + "UNITY_INCLUDE_CONFIG_H", + "WITH_POSIX", + "_GNU_SOURCE", + "IDF_VER=\"v4.4.7-dirty\"", + "ESP_PLATFORM", + "_POSIX_READER_WRITER_LOCKS", + "ARDUINO_ARCH_ESP32", + "ESP32", + "F_CPU=240000000L", + "ARDUINO=10812", + "ARDUINO_VARIANT=\"esp32s3\"", + "ARDUINO_BOARD=\"Espressif ESP32-S3-DevKitC-1-N8 (8 MB QD, No PSRAM)\"", + "ARDUINO_PARTITION_partitions" + ], + "hardening": { + "extra_cxx_flags": [ + "-g0", + "-fno-rtti", + "-fno-exceptions", + "-fno-asynchronous-unwind-tables" + ], + "symbols_stripped": true, + "strings_encrypted": true + } +}
\ No newline at end of file diff --git a/RobotFirmware/lib/HexaNRL/lib/xtensa-esp32s3/libHexaNRL_static.a b/RobotFirmware/lib/HexaNRL/lib/xtensa-esp32s3/libHexaNRL_static.a Binary files differnew file mode 100644 index 0000000..d3f8f1e --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/lib/xtensa-esp32s3/libHexaNRL_static.a diff --git a/RobotFirmware/lib/HexaNRL/library.json b/RobotFirmware/lib/HexaNRL/library.json new file mode 100644 index 0000000..d2e9cfe --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/library.json @@ -0,0 +1,7 @@ +{ + "name": "HexaNRL", + "build": { + "libArchive": false, + "srcFilter": ["+<*>"] + } +} diff --git a/RobotFirmware/lib/HexaNRL/src/BoardPins.h b/RobotFirmware/lib/HexaNRL/src/BoardPins.h new file mode 100644 index 0000000..1a01d07 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/BoardPins.h @@ -0,0 +1,92 @@ +#pragma once + +// ============================================================ +// BoardPins.h — NRL board pin assignments +// ============================================================ +// Use these constants when declaring hardware in your OpMode. +// +// Example: +// HexaDCMotor leftMotor {{ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM }}; +// HexaServo arm {{ .signalPin = SERVO_1, .startAngle = 90.0f }}; + +// Drive motors +constexpr int MOTOR_L_DIR = 5; +constexpr int MOTOR_L_PWM = 10; +constexpr int MOTOR_R_DIR = 11; +constexpr int MOTOR_R_PWM = 12; + +// Servo signal pins +constexpr int SERVO_1 = 39; +constexpr int SERVO_2 = 40; +constexpr int SERVO_3 = 41; +constexpr int SERVO_4 = 42; + +// I2C bus 0 — IMU (LSM6DSOX, default Wire) +constexpr int I2C_SDA = 47; +constexpr int I2C_SCL = 48; + +// I2C bus 1 — OLED display (SH1106, on Wire1) +// Production PCB wires the OLED to its own bus, separate from the IMU. +constexpr int OLED_SDA = 6; +constexpr int OLED_SCL = 7; + +// MCP3008 8-channel SPI ADC — battery voltage + current sensing (HexaPower) +// Dedicated SPI bus; VREF = 5.0V on this board (NOT 3.3V). +// Channel map (as actually wired — verified by the 3-phase PowerTest): +// CH0 → battery voltage sensor +// CH1 → ACS712 #1 (MAIN / total battery current) +// CH2 → ACS712 #2 (DC-motor branch current) +// CH3..CH7 → external ADC breakout connectors +// No dedicated servo sensor — servo current is derived as CH1 − CH2. +constexpr int MCP3008_CS = 8; +constexpr int MCP3008_SCK = 14; +constexpr int MCP3008_MISO = 9; +constexpr int MCP3008_MOSI = 13; + +// Misc +constexpr int BUZZER_PIN = 21; // passive buzzer — use tone(BUZZER_PIN, freq) +constexpr int BUTTON_PIN = 4; // tactile button — LOW when pressed +constexpr int BOOT_PIN = 0; // ESP32-S3 BOOT strap button — LOW when pressed +constexpr int LED_STATUS_PIN = 38; // NeoPixel status LED (WS2812B, 1 pixel) + +// General-purpose digital breakout (7 pins). The PCB silkscreens the first +// 4 as encoder headers (J21/J22) and the last 3 as D1-D3 — all 7 are wired +// as plain GPIO with no encoder-specific logic. +constexpr int DIGITAL_1 = 1; +constexpr int DIGITAL_2 = 2; +constexpr int DIGITAL_3 = 15; +constexpr int DIGITAL_4 = 16; +constexpr int DIGITAL_5 = 35; +constexpr int DIGITAL_6 = 36; +constexpr int DIGITAL_7 = 37; + +// Bench-test-only 3rd/4th motor channels — the production board only wires +// MOTOR_L/MOTOR_R above; these reuse the spare DIGITAL_1-4 GPIO breakout so a +// bench test can exercise all 4 HexaDCMotor LEDC channels (motors use LEDC +// channels 4-7). Wire an extra motor driver to these pins for testing only. +constexpr int MOTOR_3_DIR = DIGITAL_1; +constexpr int MOTOR_3_PWM = DIGITAL_2; +constexpr int MOTOR_4_DIR = DIGITAL_3; +constexpr int MOTOR_4_PWM = DIGITAL_4; + +// External digital-I/O headers as silkscreened D1–D3 (same pins as DIGITAL_5–7). +// Use these names when driving the external DIO connectors (e.g. "IO Test"). +constexpr int DIGITAL_D1 = 35; // J14 PIN2 +constexpr int DIGITAL_D2 = 36; // J15 PIN2 +constexpr int DIGITAL_D3 = 37; // J16 PIN2 + +// External ADC breakout connectors → MCP3008 channels CH3–CH7. These are ADC +// channel numbers (not GPIO pins) — read via power.readChannelVoltage(ADC_EXT_1) +// or power.readRaw(ADC_EXT_1). CH0–CH2 are reserved for battery/current sensing. +constexpr int ADC_EXT_1 = 3; +constexpr int ADC_EXT_2 = 4; +constexpr int ADC_EXT_3 = 5; +constexpr int ADC_EXT_4 = 6; +constexpr int ADC_EXT_5 = 7; + +// External UART1 breakout (JST-XH). The QC jig fits a TX<->RX loopback jumper +// here so the self-test can verify the port end to end — see _qcRunUartLoopback +// in NRLRunner.cpp. Without the jumper QC:UART_OK cannot pass, and the test says +// so ("NO DATA - check loopback jumper") rather than failing silently. +constexpr int UART1_TX = 17; +constexpr int UART1_RX = 18; diff --git a/RobotFirmware/lib/HexaNRL/src/DriveActions.h b/RobotFirmware/lib/HexaNRL/src/DriveActions.h new file mode 100644 index 0000000..5168b9c --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/DriveActions.h @@ -0,0 +1,125 @@ +#pragma once +#include "TankDrive.h" +#include "NRLAction.h" +#include "NRLComms.h" +#include "DriveTuning.h" +#include <cmath> +#include <vector> +#include <memory> + +// ============================================================ +// DriveActions — student-friendly motion primitives +// ============================================================ +// Wraps TankDrive + the gyro heading already tracked by NRLComms +// into named, chainable ActionPtrs that plug straight into +// runAction()/runBlocking() — no hand-written wait_until/instant +// glue needed per opmode. +// +// This hardware has no wheel encoders, so straight-line moves are +// open-loop (speed * time, tune DriveTuning::msPerInch per robot) +// while turns are closed-loop on NRLComms::getHeading(). +// +// Single-shot usage: +// static TankDrive drive(leftMotor, rightMotor); +// static DriveActions driveActions(drive); +// ... +// runAction(driveActions.turn(90)); +// +// Fluent chain usage: +// runAction(driveActions.auto_() +// .driveInches(24) +// .turn(90) +// .driveInches(12) +// .turn(-90) +// .build()); +// +// Every method body lives in DriveActions.cpp (the prebuilt .a) — this +// header is declarations only, so the drive/turn control logic can't be +// read or edited from source. + +class DriveActions { +public: + explicit DriveActions(TankDrive& drive, DriveTuning tuning = DriveTuning{}) + : _drive(drive), _tuning(tuning) {} + + void setTuning(const DriveTuning& t); + const DriveTuning& tuning() const; + + // Relative turn: positive degrees = clockwise/right, negative = counter- + // clockwise/left, measured from whatever NRLComms's heading is right now + // (zeroes it first). This is the primitive most autos should use — it + // composes correctly step-to-step regardless of what "0" currently means. + ActionPtr turn(float degrees, int speed = -1) const; + + // Absolute turn: target is an absolute heading in the current zero-frame + // (does NOT re-zero — use for a known fixed/field-relative heading). + ActionPtr turnTo(float targetHeadingDeg, int speed = -1) const; + + // Open-loop timed straight drive. speed sign controls direction + // (positive = forward, negative = reverse); -1 is reserved as the + // "use DriveTuning::driveSpeed" sentinel. + ActionPtr driveForMs(unsigned long ms, int speed = -1) const; + + // CLOSED-LOOP distance drive. Sign of `inches` sets the direction; `speed` + // overrides the magnitude (-1 = use tuning().driveSpeed). + // + // Drives until a FUSED estimate of distance traveled reaches the target: + // fused = w·imu + (1-w)·model (w = tuning.distFuseImuWeight) + // where `imu` is NRLComms' accel-integrated distance (senses real motion → + // robust to battery/surface) and `model` is the speed×time prediction + // (stable fallback). A hard time cap (distTimeoutScale × the speed×time + // estimate) guarantees it stops even if the IMU reading goes bad. Falls + // back to pure open-loop time if the IMU never calibrates. + // + // For pure open-loop time (no IMU), use driveForMs() instead. + ActionPtr driveInches(float inches, int speed = -1) const; + + ActionPtr stopAll() const; + + // Wait for the gyro bias calibration (~0.5 s) to finish before moving on. + // Put this FIRST in an auto routine if you call resetHeading() in init(): + // it keeps the robot still until calibration completes so the bias estimate + // (and therefore every later turn) stays accurate. + ActionPtr waitForHeadingReady() const; + + // ---- Fluent builder ---------------------------------------------- + class Builder { + public: + explicit Builder(const DriveActions& owner) : _owner(owner) {} + + Builder& turn(float degrees, int speed = -1); + Builder& turnTo(float targetHeadingDeg, int speed = -1); + Builder& driveForMs(unsigned long ms, int speed = -1); + Builder& driveInches(float inches, int speed = -1); + Builder& sleepMs(unsigned long ms); + Builder& waitForHeadingReady(); + Builder& stopAll(); + + ActionPtr build(); + + private: + const DriveActions& _owner; + std::vector<ActionPtr> _steps; + }; + + Builder auto_() const; + +private: + TankDrive& _drive; + DriveTuning _tuning; + + // Shared by turn()/turnTo(). Spins toward the target in a FIXED direction, + // easing the speed down within turnSlowdownDeg of the target so the chassis + // doesn't coast past it, then fires a short reverse brake pulse to cancel + // the leftover momentum. + // + // Sign safety: for a relative turn() we measure progress as fabs(heading) + // after zeroing, so it works no matter which way the gyro's sign runs (the + // command direction is fixed, exactly like the original hand-written turn). + // turnTo() uses signed progress toward an absolute heading. + // + // The turn sets a responsive ramp on TankDrive and does its OWN soft-start + // (limiting how fast the command rises) so deceleration near the target is + // not blocked by a slow inrush ramp left over from a forward drive. + ActionPtr _turnAction(float targetDeg, int speed, bool zeroFirst) const; +}; diff --git a/RobotFirmware/lib/HexaNRL/src/DriveTuning.h b/RobotFirmware/lib/HexaNRL/src/DriveTuning.h new file mode 100644 index 0000000..b53bba1 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/DriveTuning.h @@ -0,0 +1,53 @@ +#pragma once + +// ============================================================ +// DriveTuning — tunable constants for DriveActions primitives +// ============================================================ +// No encoders exist on this hardware, so straight-line distance is +// open-loop (speed * time, empirically tuned per robot) while turns +// are closed-loop on the gyro heading (NRLComms::getHeading()). +// +// Override per-robot via DriveActions::setTuning() if your chassis +// needs different values — don't edit the defaults here. +struct DriveTuning { + int driveSpeed = 255; // default PWM (0..255) for driveForMs()/driveInches() + int turnSpeed = 255; // MAX PWM (0..255) for turn()/turnTo() while far from target + + // Turns slow down as they approach the target so the chassis doesn't coast + // past it (momentum overshoot). Within `turnSlowdownDeg` of the target the + // speed eases from turnSpeed down to turnMinSpeed; the turn stops once it is + // within `turnToleranceDeg`, then fires a brief reverse brake pulse + // (`turnBrakeMs`) to cancel the remaining momentum. + int turnMinSpeed = 80; // PWM floor near the target (must still overcome friction) + // Lowered from 110: at 110 the chassis was still + // moving fast at the target and coasted ~14° past + // (90° turn ended near 104°). Arrive slower → less + // momentum to brake. Raise if a turn stalls short. + float turnSlowdownDeg = 60.0f; // start slowing this many degrees before the target + // (wider than 40° → longer, gentler deceleration) + float turnToleranceDeg = 2.0f; // stop once within this many degrees of the target + unsigned long turnBrakeMs = 200; // reverse brake pulse after reaching target (0 = off) + // Lengthened from 120ms to cancel more residual spin. + + float msPerInch = 18.0f; // ms to travel 1 inch AT driveSpeed — TUNE per robot + // (starting estimate; recalibrate: drive a known + // time at driveSpeed, measure inches, ms / inches) + unsigned long turnTimeoutMs = 4000; // safety cutoff if a turn never reaches target + + // driveInches() is CLOSED-LOOP: it drives until a FUSED distance estimate + // reaches the target. The estimate blends the IMU-measured distance (senses + // real motion → robust to battery voltage / surface) with the speed×time + // model (stable fallback). Weight the IMU high — it tracks reality far better + // than time when the battery state changes; the model is mainly a sanity + // anchor. distTimeoutScale × the nominal speed×time is the hard cap so a bad + // IMU reading can never drive forever. + float distFuseImuWeight = 0.85f; // 0 = time only … 1 = IMU only + float distTimeoutScale = 2.5f; // max drive time = this × the speed×time estimate + + // driveInches() eases its speed down within driveSlowdownIn of the target + // (like turns) so the bot arrives slowly and barely coasts past it. The + // floor must still overcome friction. driveInches owns its ramp + soft-start, + // so it does NOT depend on the opmode's setRampRate(). + int driveMinSpeed = 110; // PWM floor near the target + float driveSlowdownIn = 10.0f; // start slowing this many inches before the target +}; diff --git a/RobotFirmware/lib/HexaNRL/src/Gamepad.h b/RobotFirmware/lib/HexaNRL/src/Gamepad.h new file mode 100644 index 0000000..5419aeb --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/Gamepad.h @@ -0,0 +1,86 @@ +#pragma once +#include "NRLGamepad.h" +#include <functional> + +// ============================================================ +// Gamepad — object-oriented gamepad interface +// ============================================================ +// Wraps the static NRLGamepad globals with named accessors, +// built-in edge detection, and optional button bindings. +// +// Global instance: gamepad1 (declared in RobotConfig) +// Updated automatically at the top of each 100Hz TELEOP tick. +// +// Usage: +// drive.drive(gamepad1.leftY(), gamepad1.rightX()); +// if (gamepad1.justPressed(BTN_DPAD_RIGHT)) runAction(sequential({ ... })); +// ^ justPressed fires on the press only — that is what keeps runAction() +// from queuing a fresh copy of the sequence 50 times a second. +// gamepad1.onPress(BTN_DPAD_DOWN, []{ gripper.setPosition(90); }); // in init() + +class Gamepad { +public: + // ---------------------------------------------------------- + // Axis accessors (-1.0 to +1.0) + // ---------------------------------------------------------- + float leftX() const; + float leftY() const; + float rightX() const; + float rightY() const; + + // ---------------------------------------------------------- + // Button state + // ---------------------------------------------------------- + bool pressed(uint16_t btn) const; + bool justPressed(uint16_t btn) const; + bool justReleased(uint16_t btn) const; + + // ---------------------------------------------------------- + // Button bindings — register once in init(), not in loop() + // For sequences use justPressed in loop() instead. + // ---------------------------------------------------------- + static constexpr uint8_t MAX_BINDINGS = 8; + + void onPress(uint16_t btn, std::function<void()> cb); + void onRelease(uint16_t btn, std::function<void()> cb); + + // ---------------------------------------------------------- + // Called by NRLRunner at top of each 100Hz TELEOP tick. + // Not for student use. + // ---------------------------------------------------------- + void snapshot(); + + // ---------------------------------------------------------- + // reset() — Clear snapshots and bindings for OpMode restart. + // Called by NRLRunner when starting a new OpMode. + // Prevents stale button state from previous runs. + // ---------------------------------------------------------- + void reset(); + + // ---------------------------------------------------------- + // ignoreHeldButtons() — Called by NRLRunner on the first tick + // of a run. Buttons already held at that moment (the X that + // pressed START) are invisible until released once, so they + // cannot fire justPressed()/onPress() as the run begins. + // Not for student use. + // ---------------------------------------------------------- + void ignoreHeldButtons(); + +private: + struct Snap { float lx=0, ly=0, rx=0, ry=0; uint16_t buttons=0; }; + Snap _curr, _prev; // buttons = what pressed() reports + uint16_t _edgeCurr = 0, _edgePrev = 0; // what justPressed()/justReleased() compare + uint16_t _raw = 0; // last raw buttons read + uint16_t _heldAtStart = 0; // hidden from pressed() AND edges until released + uint16_t _heldThroughOutage = 0; // hidden from edges only until released + uint32_t _staleSeq = 0; // packetSeq seen while input was stale + bool _awaitPacket = false; // stale ended, no real packet yet + + struct Binding { uint16_t btn=0; std::function<void()> cb; }; + Binding _press[MAX_BINDINGS]; + Binding _release[MAX_BINDINGS]; + + void _setBind(Binding (&arr)[MAX_BINDINGS], uint16_t btn, std::function<void()> cb); +}; + +extern Gamepad gamepad1; diff --git a/RobotFirmware/lib/HexaNRL/src/NRL.h b/RobotFirmware/lib/HexaNRL/src/NRL.h new file mode 100644 index 0000000..69b0f8c --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/NRL.h @@ -0,0 +1,64 @@ +#pragma once + +// ============================================================ +// NRL.h — student umbrella include +// ============================================================ +// One line gives you everything you need: +// +// #include "NRL.h" +// +// Declare your hardware at file-scope (above your class), +// initialise in init(), then use in loop(): +// +// static HexaDCMotor leftMotor {{ .dirPin = MOTOR_L_DIR, .pwmPin = MOTOR_L_PWM }}; +// static HexaDCMotor rightMotor{{ .dirPin = MOTOR_R_DIR, .pwmPin = MOTOR_R_PWM, .flipped = true }}; +// static HexaServo arm {{ .signalPin = SERVO_1, .startAngle = 90.0f }}; +// static HexaServo gripper {{ .signalPin = SERVO_2, .startAngle = 15.0f }}; +// static HexaIMU imu { hexaImuConfig() }; // on-board IMU (Wire) +// static HexaOLED myOled { hexaOledConfig() }; // on-board OLED (Wire1) +// static TankDrive drive(leftMotor, rightMotor); +// static DriveActions driveActions(drive); +// +// Gamepad (always available, no declaration needed): +// gamepad1.leftY() — axis -1.0 to +1.0 +// gamepad1.justPressed(BTN_DPAD_RIGHT) — true on the tick of press +// +// User LED (always available, no declaration needed): +// userLed.setSolid(255, 0, 0) — solid red +// userLed.setBlink(0, 255, 0, 500) — blink green, 500ms period +// userLed.setPulse(0, 0, 255, 1000) — breathe blue, 1s cycle +// userLed.setOff() — turn off +// +// Battery voltage (always available, no declaration needed): +// power.getBatteryVoltage() — robot pack voltage (V) +// power.isBatteryLow() — true when the pack is low +// +// Rail current — read directly from `power` (always available, no declaration +// needed). There is ONE ACS712 per rail, not one per motor/servo, so this is +// the whole rail's current regardless of how many motors/servos you declared: +// power.getMainCurrent() — total battery current (A) +// power.getMotorCurrent() — DC-motor branch current (A) +// power.getServoCurrent() — servo rail current (A, derived: main − motor) +// +// Telemetry: +// telemetry.addData("key", value) + +// Hardware types +#include "HexaDCMotor.h" // DC motor driver +#include "HexaServo.h" // servo driver +#include "HexaOLED.h" // 128×64 OLED display +#include "HexaIMU.h" // LSM6DSOX IMU (accel + gyro + heading) +#include "HexaPower.h" // MCP3008 ADC — battery voltage + ACS712 current +#include "TankDrive.h" // differential drive helper +#include "DriveTuning.h" // DriveTuning struct (speed/msPerInch/timeout defaults) +#include "DriveActions.h" // DriveActions — turn(), driveInches(), auto_() chaining +#include "Gamepad.h" // gamepad1 object + +// Framework internals +#include "BoardPins.h" // MOTOR_L_DIR, SERVO_1, I2C_SDA … pin constants +#include "RobotConfig.h" // botOled, gamepad1 (framework globals) +#include "NRLGamepad.h" // BTN_X/A/B/Y, BTN_DPAD_*, BTN_RB/LB/LT/RT constants, NRLGamepad raw statics +#include "NRLComms.h" // NRLComms::sendTelemetry("key", value) +#include "NRLAction.h" // instant(), sequential(), parallel(), sleep_ms(), wait_until() +#include "NRLOpMode.h" // NRLOpMode base class, init()/start()/loop()/stop(), runAction() +#include "OpModeRegistry.h" // REGISTER_OPMODE macro diff --git a/RobotFirmware/lib/HexaNRL/src/NRLAction.h b/RobotFirmware/lib/HexaNRL/src/NRLAction.h new file mode 100644 index 0000000..cf9e5f0 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/NRLAction.h @@ -0,0 +1,56 @@ +#pragma once +#include <functional> +#include <memory> +#include <vector> +#include <initializer_list> + +// ============================================================ +// NRLAction — composable action system +// ============================================================ +// +// Actions are single units of work that may span multiple ticks. +// Each call to run() advances the action by one step and returns: +// false — still in progress, call run() again next tick +// true — complete, move on +// +// Build sequences with the factory functions below: +// +// instant([]{ /* code */ }) — runs once, done immediately +// sequential({ a, b, c }) — runs a, then b, then c +// parallel({ a, b, c }) — runs a, b, c at the same time +// sleep_ms(500) — waits 500 ms +// wait_until([]{ return condition; }) — waits until condition is true +// +// Example (in run() or loop()): +// +// runBlocking(sequential({ +// instant([]{ leftMotor.setSpeed(150); rightMotor.setSpeed(150); }), +// sleep_ms(2000), +// instant([]{ leftMotor.setSpeed(0); rightMotor.setSpeed(0); }), +// })); + +class Action { +public: + virtual ~Action() = default; + virtual bool run() = 0; // returns true when complete + virtual void reset(); // rewind to start; called by repeat() between cycles +}; + +using ActionPtr = std::shared_ptr<Action>; + + +// ============================================================ +// Factory functions — user-facing API +// ============================================================ +// The concrete Action subclasses and every function body live in +// NRLAction.cpp (the prebuilt .a) — not in this header. Only these +// declarations are visible, so the action engine can't be read or +// edited from source. + +ActionPtr instant(std::function<void()> fn); +ActionPtr sequential(std::initializer_list<ActionPtr> actions); +ActionPtr sequential(std::vector<ActionPtr> actions); // used by DriveActions::Builder +ActionPtr parallel(std::initializer_list<ActionPtr> actions); +ActionPtr sleep_ms(unsigned long ms); +ActionPtr wait_until(std::function<bool()> cond); +ActionPtr repeat(ActionPtr inner); diff --git a/RobotFirmware/lib/HexaNRL/src/NRLComms.h b/RobotFirmware/lib/HexaNRL/src/NRLComms.h new file mode 100644 index 0000000..4f1527b --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/NRLComms.h @@ -0,0 +1,222 @@ +#pragma once +#include <Arduino.h> +#include <WiFi.h> +#include <esp_now.h> +#include <esp_wifi.h> +#include <esp_idf_version.h> + +// ============================================================ +// Per-project identity — stamped by the generator +// (-DNRL_TEAM_NUMBER / -DNRL_TEAM_NAME / -DNRL_WIFI_CHANNEL). +// Fallbacks live here (not in a .cpp) so every translation unit +// that includes this header — incl. NRLRunner.cpp's OLED screens — +// sees them, and keep the un-stamped base template building unchanged. +// ============================================================ +#ifndef NRL_TEAM_NUMBER +#define NRL_TEAM_NUMBER 0 +#endif +#ifndef NRL_TEAM_NAME +#define NRL_TEAM_NAME "NRL Team" +#endif +#ifndef NRL_WIFI_CHANNEL +#define NRL_WIFI_CHANNEL 1 +#endif + +// The wire protocol — packet type IDs (PKT_*) and on-wire struct layouts — is +// INTERNAL and deliberately not part of this header. It lives in +// _internal/NRLPackets.h, which is compiled into libHexaNRL_static.a but never +// shipped in the student kit, so the protocol can't be read or altered. Only +// NRLComms.cpp / NRLRunner.cpp (inside the .a) include it. Opmodes use the +// NRLComms class API below and never touch packets. + +// Telemetry capacity knobs — kept PUBLIC because the student-facing telemetry +// buffer (NRLTelemetry.h) sizes its storage from these. The matching on-wire +// NRLTelemetryPacket that packs NRL_TELEM_BATCH_MAX entries lives in +// _internal/NRLPackets.h. Raising NRL_TELEM_MAX_ENTRIES later (e.g. to 100) is +// a one-line change rather than a hunt through hardcoded array sizes. +#define NRL_TELEM_MAX_ENTRIES 64 // buffer capacity on both bot and controller +#define NRL_TELEM_BATCH_MAX 8 // entries packed into one ESP-NOW telemetry packet + +// ============================================================ +// NRLComms — ESP-NOW layer on the Robot +// ============================================================ +class NRLComms { +public: + // Team identity is handed in from RobotMain.ino at boot. That file is + // compiled inside the student's project, so it sees the per-project + // -DNRL_TEAM_NUMBER / -DNRL_TEAM_NAME / -DNRL_WIFI_CHANNEL stamp — which + // this prebuilt .a, built once from the unstamped template, cannot. Call + // once before any status is shown or sent. baseChannel is the stamped + // radio channel used as the NVS resync baseline. + static void begin(int teamNumber, const char* teamName, uint8_t baseChannel); + static void sendAdvertise(); + static void sendStatus(uint8_t stateId, uint8_t loopOverrun = 0); + // Sends up to NRL_TELEM_BATCH_MAX key/value pairs in ONE ESP-NOW packet. + // items[i].key/val must be null-terminated, matching NRLTelemetryPacket's + // field widths (key<=11 chars, val<=15 chars). + struct TelemetryItem { const char* key; const char* val; }; + static void sendTelemetryBatch(const TelemetryItem* items, uint8_t count); + static void sendServoState(); + static void releaseCalibServos(); + static void sendMotorState(); + static void releaseCalibMotors(); + static void sendIMUState(); + static void tickCalibIMU(); // call from main loop — defers I2C out of ISR context + static void tickCalibServoMotor(); // call from main loop — defers calib servo/motor I2C+esp_now_send out of ISR context + static void tickHeading(); // call from main loop — reads IMU + integrates heading at ~100 Hz + static void tickPairing(); + + // Heading API — usable from any OpMode + static float getHeading(); // degrees since last resetHeading() / zeroHeading() + static bool isHeadingReady(); // true once bias calibration (~0.5 s) is complete + static void zeroHeading(); // set heading to 0°, keep existing bias (use before a turn) + static void resetHeading(); // full reset: zero heading + re-collect bias (robot must be still) + + // Distance API — accel double-integration. TEACHING/DEMO ONLY: it drifts + // (tilt couples gravity in; bias grows as t²). Shares the heading bias + // calibration window — gate on isHeadingReady() before trusting it. + static float getDistanceInches(); // inches since last resetDistance() + static void resetDistance(); // zero velocity + distance, keep bias + static bool isPaired(); + static bool isReconnecting(); + + // QC: true once a 0xFE QC-Station ping has been received (i.e. QC:COMMS_OK + // was emitted). Read by the robot's QC self-test so the OLED "PASS" verdict + // agrees with the flash station's COMMS milestone instead of showing PASS + // while ESP-NOW comms silently failed. + static bool qcCommsOk(); + // True when the gamepad values must not be trusted: either we are not PAIRED + // at all, or no controller packet has arrived for STALE_INPUT_MS. Derived + // from _pairState/_lastCtrlMs rather than a cached flag, so it cannot drift + // out of step with the staleness handling in tickPairing(). + static bool isInputStale(); + + // ── Link quality, per run ─────────────────────────────────────────────── + // Reset by resetLinkStats() when an OpMode starts. dropoutCount() counts + // PAIRED -> RECONNECTING transitions; longestSilentMs() is the worst gap + // between controller packets, which shows a link degrading long BEFORE it + // trips the dropout threshold. + static void resetLinkStats(); + static uint32_t dropoutCount(); + static uint32_t longestSilentMs(); + +#ifdef NRL_LINK_FAULT_INJECTION + // ── Bench fault injection (env robot-linktest only) ───────────────────── + // Simulates a total RF blackout for ms milliseconds WITHOUT touching the + // radio: incoming controller packets stop refreshing _lastCtrlMs, and + // outgoing STATUS is suppressed. Both watchdogs therefore fire exactly as + // they would in a real dropout — the robot goes RECONNECTING and the + // controller buzzes — but deterministically and repeatably, which shielding + // and distance are not. Compiled out of the shipping build. + static void debugBlackout(uint32_t ms); + static bool debugBlackoutActive(); + + // Watchdog-race probe. debugBlackout() can never reproduce the field exit: + // it SUPPRESSES packets, so _lastCtrlMs only ever ages. The real fault is the + // opposite - the ESP-NOW callback (core 0) stamping _lastCtrlMs with a time + // NEWER than the `now` tickPairing() (core 1) sampled a few microseconds + // earlier. This arms exactly that state for the next PAIRED tick, so the + // interleave that happens by chance on a field happens here on demand. + static void debugRaceArm(); + + // Airtime probe. Sends `frames` ESP-NOW frames of `payloadBytes` back to + // back and reports how long the RADIO actually took, as one + // machine-parseable AIRTIME: line for dev-docs/bench/airtime.py. + // + // Times send-COMPLETION callbacks, not esp_now_send() returns: send() only + // queues the frame, so timing it measures the queue rather than the air. + // Nothing else in this firmware registers a send callback, so the probe + // installs its own and removes it again afterwards. + // + // Why it exists: no PHY rate is configured anywhere (no + // esp_wifi_config_espnow_rate, no esp_now_set_peer_rate_config), so ESP-NOW + // runs at whatever the IDF default is. At 1 Mbps a 235-byte telemetry frame + // costs ~2 ms of air; at 24 Mbps under 0.1 ms. That gap dwarfs every other + // airtime lever, so it must be measured before any constant is tuned. + // + // Sweep payloadBytes to tell air-limited from queue-limited: if per-frame + // time grows with size we are measuring the air; if it is flat we are + // measuring the queue and the number means nothing. + static void debugAirtimeProbe(uint16_t payloadBytes, uint16_t frames); +#endif + + // Active ESP-NOW channel (runtime — may differ from the -DNRL_WIFI_CHANNEL + // default after the controller pushes a PKT_CHANNEL_CHANGE). Used by the OLED. + static uint8_t channel(); + + // Team identity for OLED / status rendering (set by begin(), above). + static int teamNumber(); + static const char* teamName(); + + // Authenticated pairing (called from button handler in NRLRunner) + static void enterPairAdvertising(); // bot button held 3s → start 3s scan window + static void cycleCandidate(); // short press → next controller in list + static void acceptCandidate(); // hold 1s → accept selected, send response + static void cancelPairing(); // hold 3s → abandon, restore previous state + + // State queries for OLED rendering + static bool isUnpaired(); + static bool isPairAdvertising(); + static bool isPairSelecting(); + static uint8_t candidateCount(); + static uint8_t selectedIdx(); + static uint16_t selectedCode(); + +private: + enum class PairState : uint8_t { + UNPAIRED, // no saved MAC — idle, waiting for explicit button pairing action + SCANNING, + RECONNECTING, + PAIRED, + PAIR_ADVERTISING, // 3s collection window: gathering controllers' pair requests + PAIR_SELECTING // operator browses candidate list and confirms the correct code + }; + + struct PairCandidate { uint8_t mac[6]; uint16_t code; }; + +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) + static void onReceive(const esp_now_recv_info_t* info, const uint8_t* data, int len); +#else + static void onReceive(const uint8_t* mac, const uint8_t* data, int len); +#endif + + // Team identity, handed in via begin() from the student-compiled RobotMain.ino + // (see begin() above). Defaults mirror the NRLComms.h fallback macros so an + // un-stamped/legacy build still renders something sane. + static int _teamNumber; + static char _teamName[24]; + static uint8_t _baseChannel; + + // Runtime ESP-NOW channel + a deferred change request. onReceive() (ESP-NOW + // callback context) only sets _chanReqPending; tickPairing() applies it on the + // main loop so the NVS write + esp_wifi_set_channel never run inside the ISR. + static uint8_t _channel; + static volatile bool _chanReqPending; + static volatile uint8_t _chanReqValue; + static void _applyChannel(uint8_t ch, bool persist); // set radio + peers (+ NVS) + static void _persistChannelIfChanged(); // save _channel to NVS if different + + static bool _peerAdded; + static PairState _pairState; + static volatile uint32_t _lastCtrlMs; + static uint32_t _reconnStart; + static uint8_t controllerMAC[6]; + static const uint8_t _broadcastMAC[6]; + + // Candidate list for PAIR_ADVERTISING / PAIR_SELECTING + static PairCandidate _candidates[4]; + static uint8_t _candidateCount; + static uint8_t _selectedIdx; + static uint32_t _pairAdvStart; // start of PAIR_ADVERTISING window + static uint32_t _pairSelStart; // start of PAIR_SELECTING timeout + + static void _addBroadcastPeer(); + static void _addUnicastPeer(const uint8_t* mac); + static void _removePeer(const uint8_t* mac); + static void _becomePaired(const uint8_t* mac); + static void _becomeScanning(); + static void _sendAdvertiseTo(const uint8_t* dest); + static void _saveMAC(); + static void _clearSavedMAC(); + static bool _isValidMAC(const uint8_t* mac); +}; diff --git a/RobotFirmware/lib/HexaNRL/src/NRLGamepad.h b/RobotFirmware/lib/HexaNRL/src/NRLGamepad.h new file mode 100644 index 0000000..231af4e --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/NRLGamepad.h @@ -0,0 +1,81 @@ +#pragma once +#include <stdint.h> +#include <freertos/FreeRTOS.h> +#include <freertos/task.h> + +// ============================================================ +// NRLGamepad — gamepad state accessible inside user loop() +// ============================================================ +// Values are updated by NRLComms::onReceive() when GAMEPAD +// packets arrive from the Controller at ~100Hz while an OpMode runs +// (T_GAMEPAD = 10ms); ~20Hz keepalives otherwise. +// +// Usage in OpMode: +// float spd = NRLGamepad::leftY * 255; +// if (NRLGamepad::buttons & BTN_X) { ... } + +// Button bitmask constants (must match Controller firmware) +// Face buttons, D-pad, bumpers, and toggles. +// +// BIT 2 IS INTENTIONALLY UNUSED — there is no B button on this board. The V1 +// production PCB has 7 tactile buttons; the Controller's BTN_BIT[] skips bit 2, +// so nothing can ever set it, and there is deliberately no constant for it. +// Do NOT renumber the constants below to close the gap — bit positions are the +// wire contract with the Controller firmware, and moving Y off bit 3 would +// silently mis-map every button. +// +// BTN_Y is FREE while an OpMode runs. It used to be the BACK/STOP button, but +// exit moved to the LT toggle: on SCR_CODE_RUNNING the Controller skips its +// whole nav block (ControllerMain.ino "if (curScreen != SCR_CODE_RUNNING)"), so +// Y never reaches handleBack() and is forwarded in the gamepad packet like any +// other button. Y is still BACK in the menus, and it dismisses the TeleOp +// exit-confirm popup — so while that popup is up, a Y press does both. +#define BTN_X (1 << 0) +#define BTN_A (1 << 1) +// (1 << 2) — no B button on this board; bit left unused +#define BTN_Y (1 << 3) // free during a run; BACK in menus / dismisses exit popup +#define BTN_DPAD_RIGHT (1 << 4) // free always +#define BTN_DPAD_DOWN (1 << 5) // free during run (UI: scroll down when idle) +#define BTN_DPAD_UP (1 << 6) // free during run (UI: scroll up when idle) +#define BTN_DPAD_LEFT (1 << 7) +#define BTN_RB (1 << 8) // right bumper (GP40) +#define BTN_LB (1 << 9) // left bumper (GP39) +#define BTN_LT (1 << 10) // left toggle (GP42) +#define BTN_RT (1 << 11) // right toggle (GP41) + +struct NRLGamepad { + static volatile float leftX; + static volatile float leftY; + static volatile float rightX; + static volatile float rightY; + static volatile uint16_t buttons; + + // Counts real GAMEPAD packets: update() bumps it, clear() and + // clearIfNoPacketSince() don't. Lets a reader tell controller data from the + // zeros NRLComms writes while input is stale. + static volatile uint32_t packetSeq; + + // Spinlock protecting the fields above. + // Both update() (WiFi task, core 0) and read() (main task, core 1) must hold it. + static portMUX_TYPE mux; + + // Called by NRLComms on every received GAMEPAD packet (WiFi task context). + static void update(float lx, float ly, float rx, float ry, uint16_t btns); + + // Zero every field. Not a packet, so packetSeq is left alone. + static void clear(); + + // Zero every field unless a packet arrived after packetSeq read `seq`. The + // stale-input path uses this so it can never overwrite a packet that landed + // between its silence check and the write. + static void clearIfNoPacketSince(uint32_t seq); + + // Atomically copy all five fields — use this instead of reading fields directly. + static void read(float& lx, float& ly, float& rx, float& ry, uint16_t& btns); + // Same, plus packetSeq from the same instant. + static void read(float& lx, float& ly, float& rx, float& ry, uint16_t& btns, uint32_t& seq); + + static bool pressed(uint16_t btn); +}; + +// Definitions live in NRLComms.cpp to avoid multiple-definition errors diff --git a/RobotFirmware/lib/HexaNRL/src/NRLOpMode.h b/RobotFirmware/lib/HexaNRL/src/NRLOpMode.h new file mode 100644 index 0000000..404616d --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/NRLOpMode.h @@ -0,0 +1,173 @@ +#pragma once +#include "NRLAction.h" +#include "NRLTelemetry.h" +#include <freertos/FreeRTOS.h> +#include <freertos/task.h> +#include <vector> + +// ============================================================ +// ABI guard +// ============================================================ +// A student opmode is compiled against THIS header; NRLRunner (compiled +// into libHexaNRL_static.a) calls into it through NRLOpMode's vtable -- +// a fixed slot per virtual, in declaration order. If the header a student +// kit ships and the .a it ships were built from different versions of this +// class layout (a virtual added/removed/reordered, a data member changed), +// the two sides disagree about which slot is which. That is NOT a compile +// or link error -- virtual calls resolve at runtime -- so the failure is a +// silently wrong function called, or a jump into garbage. On a robot, that +// surfaces as a field failure, not a build failure. +// +// Bump NRL_ABI_VERSION whenever you change anything that could shift the +// layout of a class living on both sides of the header/.a boundary -- +// NRLOpMode most of all. REGISTER_OPMODE (OpModeRegistry.h), which every +// student opmode calls, references a version-named symbol that only the +// matching .a defines (see NRLOpMode.cpp). A stale .a then fails to LINK, +// with an error naming the missing symbol, instead of failing silently on +// the field. +#define NRL_ABI_VERSION 1 +#define _NRL_ABI_CONCAT2(a, b) a##b +#define _NRL_ABI_CONCAT(a, b) _NRL_ABI_CONCAT2(a, b) +#define NRL_ABI_MARKER _NRL_ABI_CONCAT(nrl_abi_v, NRL_ABI_VERSION) + +extern "C" void NRL_ABI_MARKER(); + +// ============================================================ +// NRLOpMode — Base class for all student programs +// ============================================================ +// +// Override the hooks you need: +// init() — once when INIT is pressed. Set up hardware here. +// start() — once when the match starts, right before the first loop(). +// Queue an AUTO routine here and it runs exactly once. +// loop() — 100Hz. TELEOP: for 2:30; AUTO: for 60 seconds. +// stop() — once on STOP. Motors do NOT stop automatically — +// always call drive.stop() (or motor.stop()) here. +// +// Actions: +// runAction(a) — queue an action. It advances one step per tick and +// removes itself when finished. Actions ADD to the +// queue: starting one does not cancel another, so +// several can run side by side. +// cancelActions() — drop every queued action right now +// isActionRunning() — true while any queued action is still going +// +// Action helpers available everywhere: +// instant([]{ ... }) — one-shot hardware command +// sequential({ a, b, c }) — chain actions in order +// parallel({ a, b, c }) — run actions at the same time +// sleep_ms(500) — wait 500 ms +// wait_until([]{ return ...; }) — wait for a sensor condition +// +// AUTO — queue it once in start(), then leave it alone: +// +// void start() override { +// runAction(sequential({ +// instant([]{ drive.drive(0.6f, 0.0f); }), // drive forward +// sleep_ms(2000), // for 2 seconds +// instant([]{ drive.stop(); }), // then stop +// })); +// } +// +// TELEOP — fire from a button edge, never every tick: +// +// void loop() override { +// drive.drive(gamepad1.leftY(), gamepad1.rightX()); // loop() owns the drive +// if (gamepad1.justPressed(BTN_X)) runAction(armSequence()); // action owns the arm +// } +// +// Control each piece of hardware in ONE place — either loop() or an action, +// not both. Each tick runs your actions FIRST, then loop(), so anything +// loop() sets every tick overwrites what an action just set and the action +// looks like it did nothing. Above, loop() owns the drive and the action owns +// the arm, so they never collide. +// +// If you truly need both to control the same part, skip the loop() control +// while a sequence is playing: +// +// if (!isActionRunning()) arm.setPosition(90.0f + gamepad1.rightY() * 90.0f); +// +// Writing sequences inline like the examples above is the RIGHT way to start +// and stays fine for most robots. When an OpMode grows — loop() too long to +// scan, or the same sequence used twice — you can move sequences into named +// functions (examples/ExampleSeq.h) and mechanisms into classes with named +// states (examples/ExampleSubsystem.h). Both are optional; neither changes +// what the robot does. +// +// RULES: +// - No delay() anywhere — use sleep_ms() or runBlocking() instead +// - No new/malloc inside loop() — allocate members in init() or as class fields +// - Don't call runAction() every tick. Queue it in start(), or on a button +// edge with justPressed(). The queue holds 8 actions; past that the extra +// ones are dropped and a warning is printed to serial. +// - cancelActions() empties the queue but does NOT stop hardware — follow it +// with drive.stop() / setPosition() for anything that was moving. + +class NRLOpMode { +public: + virtual ~NRLOpMode() = default; + + NRLTelemetry telemetry; // call telemetry.addData("key", value) inside loop() + + virtual void init() {} // optional: setup before START + virtual void start() {} // optional: runs once when the match starts, before the first loop() + virtual void loop() {} // called at 100Hz — TELEOP: for 2:30 then exits; AUTO: for 60 seconds then exits + virtual void stop() {} // optional: cleanup on STOP — motors do NOT stop automatically; always call drive.stop() here + + // -------------------------------------------------------- + // runBlocking(action) + // Executes action to completion, blocking the caller. + // Checks the stop signal and 60-second AUTO deadline every tick. + // Use inside run() for AUTO sequences. + // -------------------------------------------------------- + void runBlocking(ActionPtr action); + + // -------------------------------------------------------- + // runAction(action) + // Adds a non-blocking action to the queue. It advances one step per + // tick and drops out of the queue on its own when it finishes. + // Queuing an action does NOT cancel the ones already running — up to + // 8 can be in flight together. + // Queue it in start() (AUTO) or on a button edge (TELEOP); calling it + // every tick just refills the queue with copies that never finish. + // -------------------------------------------------------- + void runAction(ActionPtr action); + + // -------------------------------------------------------- + // cancelActions() + // Drops every queued action immediately. Hardware is left exactly as + // the actions last set it — follow with drive.stop() if you want the + // robot to hold still. + // -------------------------------------------------------- + void cancelActions(); + + // -------------------------------------------------------- + // isActionRunning() + // True while any queued action is still in progress. + // -------------------------------------------------------- + bool isActionRunning() const; + + // Called by NRLRunner each tick — not for student use + void _advanceAction(); + + // Called by NRLRunner before init() — not for student use + void _bindStopFlag(volatile bool* flag); + + // Called by NRLRunner on CMD_START for AUTO — not for student use + void _setAutoDeadline(uint32_t deadlineMs); + +private: + // Queue depth. Deep enough for any realistic set of concurrent sequences, + // shallow enough that a runaway runAction()-every-tick loop is caught and + // reported instead of eating the heap. + static constexpr uint8_t MAX_ACTIONS = 8; + + void _warnQueueFull(); + + std::vector<ActionPtr> _actions; // in flight + std::vector<ActionPtr> _pending; // queued since the last tick + bool _advancing = false; // inside the _advanceAction() run pass + bool _cancelRequested = false; // cancelActions() called from an action + volatile bool* _stopFlag = nullptr; + uint32_t _autoDeadlineMs = 0; +}; diff --git a/RobotFirmware/lib/HexaNRL/src/NRLPublic.h b/RobotFirmware/lib/HexaNRL/src/NRLPublic.h new file mode 100644 index 0000000..d1a9e46 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/NRLPublic.h @@ -0,0 +1,18 @@ +#pragma once + +// ============================================================ +// NRLPublic — the robot entry-point API used by RobotMain.ino +// ============================================================ +// RobotMain.ino calls these two functions and nothing else from the +// framework's execution engine. The engine itself (NRLRunner, the match +// state machine, the ESP-NOW command handling) is internal and compiled +// into the prebuilt .a — its headers are NOT shipped, so the run loop and +// state machine can't be read or edited. Students never call these; their +// code lives in opmodes/. + +// One-time setup: ESP-NOW init + advertise (call in setup()). The team identity +// is passed in from RobotMain.ino because that file is compiled inside the +// student's project, so it sees the per-project -DNRL_TEAM_NUMBER / +// -DNRL_TEAM_NAME / -DNRL_WIFI_CHANNEL stamp — the prebuilt engine .a cannot. +void nrl_begin(int teamNumber, const char* teamName, int wifiChannel); +void nrl_tick(); // run the active OpMode one 100Hz step (call in loop()) diff --git a/RobotFirmware/lib/HexaNRL/src/NRLTelemetry.h b/RobotFirmware/lib/HexaNRL/src/NRLTelemetry.h new file mode 100644 index 0000000..0520ff5 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/NRLTelemetry.h @@ -0,0 +1,72 @@ +#pragma once +#include <Arduino.h> +#include "NRLComms.h" // NRL_TELEM_MAX_ENTRIES, NRL_TELEM_BATCH_MAX + +// ============================================================ +// NRLTelemetry — student-facing telemetry buffer +// +// Usage inside loop(): +// telemetry.addData("speed", drive.getSpeed()); // float +// telemetry.addData("status", "locked"); // string +// // telemetry.update(); ← optional; auto-fires at end of each tick +// +// Up to NRL_TELEM_MAX_ENTRIES distinct keys are tracked by name. Sending the +// same key twice updates the existing entry rather than adding a new line. +// +// Real dedup + paced batched sends: addData() only marks a key "pending" +// when its formatted value actually changes. Each flush packs up to +// NRL_TELEM_BATCH_MAX pending entries into ONE ESP-NOW packet (round-robin +// across the buffer) instead of one packet per key — this both keeps each +// tick's esp_now_send() call count low (avoids overrunning ESP-NOW's +// pending-TX queue, which used to silently drop whichever keys landed last +// in a big one-packet-per-key burst) and scales the buffer well past 8 +// entries without multiplying packet count 1:1 with key count. +// ============================================================ + +class NRLTelemetry { +public: + void addData(const char* key, float value); + void addData(const char* key, const char* value); + void update(); // flush up to BATCHES_PER_TICK batches of pending entries now + + // Called by NRLRunner — not for student use + void _autoFlush(); // paced flush, called once per loop tick + void _clear(); // resets all entries on OpMode stop +private: + struct Entry { + char key[12] = {}; + char val[16] = {}; + bool used = false; + bool pending = false; // val changed since last successful send + }; + // MUST be default-initialised: an OpMode that declares its own constructor + // (e.g. OLEDLiveDemo) is default-initialised by `new T()`, which would leave + // this buffer indeterminate — stale `used`/`pending` flags then get sent as + // garbled telemetry. The `= {}` (plus the per-field defaults above) makes the + // buffer clean regardless of how the enclosing OpMode is constructed. + Entry _buf[NRL_TELEM_MAX_ENTRIES] = {}; + uint16_t _cursor = 0; + + // Batch packets sent per flush call — keeps esp_now_send() calls/tick low + // regardless of total buffered key count. + // + // Was 2. _autoFlush() runs every 10ms tick, so 2 allowed up to 200 telemetry + // packets/s, and a 226-byte batch costs 2879us of air at the measured 1 Mbps + // (dev-docs/bench/AIRTIME_RESULTS.md) — 57.6% of the channel for ONE pair at + // worst case, by far the largest single consumer. 1 halves that ceiling. + // + // Safe because _cursor persists across calls and round-robins the whole + // buffer: halving the batches halves the refresh RATE but never starves a + // key, which is the failure that would look like the old telemetry-freeze + // bug (that one was an uninitialised _buf, not batching — see the comment + // above the Entry array). + // + // Only entries whose value actually CHANGED are pending, so a well-behaved + // OpMode never approaches the ceiling; this bounds the worst case rather + // than slowing the common one. + static constexpr uint8_t BATCHES_PER_TICK = 1; + + Entry* _find(const char* key); + Entry* _findOrAlloc(const char* key); + void _sendPending(); // sends up to BATCHES_PER_TICK batches of pending entries +}; diff --git a/RobotFirmware/lib/HexaNRL/src/NRLVersion.h b/RobotFirmware/lib/HexaNRL/src/NRLVersion.h new file mode 100644 index 0000000..6df3f98 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/NRLVersion.h @@ -0,0 +1,13 @@ +#pragma once +// ============================================================ +// NRLVersion.h — the NRL SDK version +// ============================================================ +// +// The one place the SDK version is set. The robot prints it at boot +// ("[NRL] SDK vX.Y.Z"), and the kitbuilder reads it from here for the +// build manifest and the release tag, so bump it here and nowhere else. +// +// The controller has its own version: ControllerFirmware/src/ControllerVersion.h. +// Which robot and controller versions ship together is in docs/COMPATIBILITY.md. + +#define NRL_SDK_VERSION "1.4.1" diff --git a/RobotFirmware/lib/HexaNRL/src/OpModeRegistry.h b/RobotFirmware/lib/HexaNRL/src/OpModeRegistry.h new file mode 100644 index 0000000..a904742 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/OpModeRegistry.h @@ -0,0 +1,83 @@ +#pragma once +#include <vector> +#include "NRLOpMode.h" + +// ============================================================ +// OpModeType — used by REGISTER_OPMODE and the ADVERTISE packet +// ============================================================ +enum class OpModeType { TELEOP, AUTO }; + + +// ============================================================ +// OpModeEntry — one registered OpMode +// ============================================================ +// factory: creates a fresh instance each time the OpMode is started. +// Fresh instance = clean member variable state every run. +struct OpModeEntry { + const char* name; + OpModeType type; + bool isExample; // true = built-in example, false = student code + int order; // lower = shown first; default 1000 (registration order) + NRLOpMode* (*factory)(); +}; + + +// ============================================================ +// OpModeRegistry — global list of all registered OpModes +// ============================================================ +// Uses a static local vector (Meyer's singleton) to avoid the +// static initialisation order fiasco across translation units. +class OpModeRegistry { +public: + static std::vector<OpModeEntry>& all() { + static std::vector<OpModeEntry> _list; + return _list; + } + + static void add(const char* name, OpModeType type, bool isExample, + NRLOpMode* (*factory)(), int order = 1000) { + all().push_back({ name, type, isExample, order, factory }); + } +}; + + +// ============================================================ +// OpModeRegistrar<T> — registers one OpMode via its constructor +// ============================================================ +// C++ guarantees static objects are constructed before setup(). +// So every REGISTER_OPMODE call runs at startup, before anything else. +template<typename T> +class OpModeRegistrar { +public: + OpModeRegistrar(const char* name, OpModeType type, bool isExample = false, + int order = 1000) { + // ABI guard: references a version-named symbol only a matching .a + // defines (see NRL_ABI_VERSION in NRLOpMode.h). Runs at static-init + // time, same as OpModeRegistry::add() below, so it can never be + // linker-GC'd away. + NRL_ABI_MARKER(); + OpModeRegistry::add(name, type, isExample, + []() -> NRLOpMode* { return new T(); }, order); + } +}; + + +// ============================================================ +// REGISTER_OPMODE — used internally by _impl/ wrappers +// REGISTER_OPMODE_EX — used by built-in example files +// ============================================================ +// +// _reg_##ClassName makes the variable name unique per class +// so multiple .cpp files don't clash with each other. +#define REGISTER_OPMODE(ClassName, DisplayName, Type) \ + static OpModeRegistrar<ClassName> _reg_##ClassName(DisplayName, OpModeType::Type, false) + +#define REGISTER_OPMODE_EX(ClassName, DisplayName, Type) \ + static OpModeRegistrar<ClassName> _reg_##ClassName(DisplayName, OpModeType::Type, true) + +// REGISTER_OPMODE_EX_AT — like REGISTER_OPMODE_EX but pins the menu slot. +// Order is a small integer: lower numbers appear first in the EXAMPLES menu. +// Only the four curriculum examples use this; everything else stays at the +// default order (1000) and is filtered out of the menu unless re-enabled. +#define REGISTER_OPMODE_EX_AT(ClassName, DisplayName, Type, Order) \ + static OpModeRegistrar<ClassName> _reg_##ClassName(DisplayName, OpModeType::Type, true, Order) diff --git a/RobotFirmware/lib/HexaNRL/src/RobotConfig.h b/RobotFirmware/lib/HexaNRL/src/RobotConfig.h new file mode 100644 index 0000000..9917dea --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/RobotConfig.h @@ -0,0 +1,96 @@ +#pragma once + +// ============================================================ +// RobotConfig.h — framework-level hardware (NRL internals) +// ============================================================ +// This file only declares hardware that the NRL framework +// itself requires (pairing OLED, button, gamepad). +// +// Your robot hardware (motors, servos, IMU …) goes at the +// top of your own opmode file — see "Writing Your Code" in README.md. + +#include <Wire.h> +#include <Adafruit_NeoPixel.h> +#include "HexaOLED.h" +#include "HexaIMU.h" +#include "Gamepad.h" +#include "BoardPins.h" +#include "HexaLED.h" +#include "HexaPower.h" + +// ── Board-aware hardware presets ───────────────────────────────────────────── +// Construct the on-board OLED / IMU without hard-coding which I2C bus, address, +// or pins they use. Prefer these over a raw HexaOLEDConfig{}/HexaIMUConfig{} so +// you can't accidentally point a device at the wrong bus (the #1 way to get a +// blank OLED or an "IMU not found"): +// +// HexaOLED oled{ hexaOledConfig() }; // OLED on Wire1 / OLED_SDA,OLED_SCL +// HexaIMU imu { hexaImuConfig() }; // IMU on Wire / I2C_SDA, I2C_SCL +// +// (camelCase functions — the PascalCase HexaOLEDConfig / HexaIMUConfig names are +// the driver config structs these return.) +inline HexaOLEDConfig hexaOledConfig() { + return HexaOLEDConfig{ .i2cAddr = 0x3C, .wire = &Wire1, + .sdaPin = OLED_SDA, .sclPin = OLED_SCL }; +} +inline HexaIMUConfig hexaImuConfig() { + return HexaIMUConfig{ .i2cAddr = 0x6B, .wire = &Wire, + .sdaPin = I2C_SDA, .sclPin = I2C_SCL }; +} + +extern HexaOLED botOled; // SSD1306 128×64 — used by pairing UI (do not rename) +extern Gamepad gamepad1; // controller input — updated 50× per second +extern Adafruit_NeoPixel nrlLedStrip; // shared 2-pixel strip on LED_STATUS_PIN (NRL internal) +extern HexaLED botLed; // pixel 0 — framework status (do not use in student code) +extern HexaLED userLed; // pixel 1 — student-controlled RGB LED +extern HexaPower power; // MCP3008 ADC — battery voltage + motor/servo current + +// Called from RobotMain.ino setup() — initialises framework hardware only +void robotHardwareBegin(); + +// Boot diagnostics, captured in robotHardwareBegin(). nrlBootCount() counts +// resets since the last true power-up (>1 means something restarted the MCU); +// nrlLastResetReason() is an esp_reset_reason_t. See RobotConfig.cpp. +uint32_t nrlBootCount(); +uint32_t nrlLastResetReason(); + +// True when the SECOND-STAGE BOOTLOADER hung and was watchdog-reset before this +// boot finally succeeded. Emits "QC:BOOT_RETRY" so the flash station can fail +// the board on it. +// +// Why this exists. The bootloader configures the CPU clock before it initialises +// the console, and part of that is waiting for the BBPLL to report calibration +// complete. That wait has no timeout. On a board whose crystal or analog supply +// is marginal, calibration sometimes fails to converge: the bootloader hangs, +// the watchdog resets the chip, and the ROM retries. The application never runs +// on those attempts, so it cannot log them - and the board looks perfectly +// healthy the moment it does come up. A controller failed exactly this way after +// passing its factory test, and by then the failure was permanent. +// +// Two hardware facts outlive the failed attempts and let us reconstruct them: +// the reset reason is latched in hardware, and RTC_NOINIT RAM holds its magic +// only while power is maintained. So "the application has never run since power +// was applied, yet the previous reset was a watchdog" can only mean something +// hung before the application existed - i.e. the bootloader. That is distinct +// from an app-level watchdog (magic valid) and from a clean start (POWERON). +// +// LIMIT, stated because it bounds how hard to lean on this: a brownout deep +// enough to drop the RTC domain below its retention voltage also scrambles the +// magic, so a watchdog reset following such a brownout would read as a retry. +// Unlikely but not impossible - treat it as a strong reason to investigate a +// board, not as proof on its own. It is still the only early warning available +// for a fault that otherwise gives none until the board stops booting entirely. +bool nrlBootloaderRetried(); + +// Human-readable form of nrlLastResetReason(), used by the end-of-run summary so +// a mid-run reset can be correlated with the run that was in progress. +const char* nrlLastResetReasonName(); + +// Same reason as a bare token ("POWERON", "BROWNOUT", "PANIC", "TASK_WDT", ...) +// short enough for one OLED row. The robot's idle status screen shows it with +// the boot count, so a bot that rebooted mid-match says why without a laptop. +const char* nrlLastResetReasonShort(); + +// Prints the boot reason / boot count. Must be called AFTER Serial.begin() and +// the USB CDC enumeration delay - see RobotConfig.cpp. +void nrlPrintBootDiagnostics(); diff --git a/RobotFirmware/lib/HexaNRL/src/TankDrive.h b/RobotFirmware/lib/HexaNRL/src/TankDrive.h new file mode 100644 index 0000000..987139a --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/TankDrive.h @@ -0,0 +1,87 @@ +#pragma once +#include "HexaDCMotor.h" +#include <algorithm> + +// ============================================================ +// TankDrive — differential drive helper +// ============================================================ +// Wraps left/right motors with differential kinematics. +// +// Kinematics: +// Left motor = (forward + turn) * scale +// Right motor = (forward - turn) * scale +// +// Two-stick usage (left Y = forward, right X = turn): +// drive.drive(gamepad1.leftY(), gamepad1.rightX()); +// +// Single-stick usage (left stick only): +// drive.drive(gamepad1.leftY(), gamepad1.leftX()); +// +// drive() sets a COMMAND that the robot holds until you change it, so it +// works whether you call it every tick (TELEOP) or once from an action: +// instant([]{ drive.drive(0.6f, 0.0f); }), // still driving next tick +// sleep_ms(2000), +// instant([]{ drive.stop(); }), + +class TankDrive { +public: + TankDrive(HexaDCMotor& left, HexaDCMotor& right) + : _left(left), _right(right) {} + + ~TankDrive(); + + // Set the drive command. + // forward: -1.0 (back) to +1.0 (fwd) + // turn: -1.0 (left) to +1.0 (right) + // The command is held until changed. Motor output ramps toward it at + // _maxDelta per tick (see setRampRate) to limit reversal current spikes. + void drive(float forward, float turn); + + // Stop now — zeroes the command AND the output, no ramp. + void stop(); + + // Scale: 0.0–1.0 (use for slow/fast mode toggle) + void setScale(float scale); + float getScale() const; + + // Max motor output change per tick. At the 100Hz robot loop, 0.1 spreads a + // full reversal (-1→+1) over ~200ms — softening the dI/dt current spike + // that couples into the servo rail. Raise toward 0.2 for snappier driving, + // 1.0+ disables ramping. Lower = smoother/quieter but less responsive. + void setRampRate(float maxDeltaPerTick); + + // Ramp every registered TankDrive one step toward its command and write + // the motors. Called by NRLRunner after loop(); not for student use. + static void tickAll(); + + // Zero every registered drive - command AND output. Called by NRLRunner when + // controller input goes stale during a TELEOP run. Not for student use. + static void stopAll(); + + // Clear the drive registry. Called by NRLRunner after the OpMode is + // deleted so stale pointers don't linger between runs. A file-static + // TankDrive re-registers on its next drive() call. + static void clearRegistry(); + +private: + HexaDCMotor& _left; + HexaDCMotor& _right; + float _scale = 1.0f; + float _maxDelta = 0.1f; // ramp limit per tick (~100ms 0→full, ~200ms full reversal at 100Hz) + float _curL = 0.0f; // output actually written to the motors + float _curR = 0.0f; + float _targetL = 0.0f; // commanded output, held until drive()/stop() + float _targetR = 0.0f; + + void _register(); + void _tick(); + + static constexpr uint8_t MAX_DRIVES = 4; + static TankDrive* s_registry[MAX_DRIVES]; + static uint8_t s_count; + + static float _stepToward(float cur, float target, float maxD); +}; + +// Declare your own instance at file-scope in your opmode: +// TankDrive drive(leftMotor, rightMotor); diff --git a/RobotFirmware/lib/HexaNRL/src/examples/ExampleSeq.h b/RobotFirmware/lib/HexaNRL/src/examples/ExampleSeq.h new file mode 100644 index 0000000..f112497 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/examples/ExampleSeq.h @@ -0,0 +1,69 @@ +#pragma once +#include "NRL.h" +#include "ExampleSubsystem.h" + +// ============================================================ +// ExampleSeq.h — ADVANCED: the named-sequence pattern +// ============================================================ +// You do NOT need this to write a working OpMode, and you should not +// start here. Write your sequences inline first: +// +// if (gamepad1.justPressed(BTN_X)) { +// runAction(sequential({ +// instant([]{ arm.setPosition(0); }), +// sleep_ms(400), +// instant([]{ gripper.setPosition(90); }), +// })); +// } +// +// That is the right shape for most robots, and it reads top to bottom. +// GRADUATE TO THIS FILE when one of those becomes true: +// - loop() has grown long enough that the buttons are hard to find +// - you use the same sequence from more than one place +// - two people are editing the same OpMode and colliding +// +// Pattern: +// Collect related sequences in a namespace. +// Each function takes subsystem references and returns an ActionPtr. +// Same idea as INITSeq / ShooterSeq / ServoSeq in AG_2026. +// +// Then in your OpMode: +// #include "examples/ExampleSeq.h" +// static ExampleSubsystem sub; +// +// void start() override { // AUTO: queue once +// runAction(ExampleSeq::initAll(sub)); +// } +// +// void loop() override { // TELEOP: on a button edge +// if (gamepad1.justPressed(BTN_X)) runAction(ExampleSeq::pickUp(sub)); +// } + +namespace ExampleSeq { + + // Move all subsystems to their safe starting position + inline ActionPtr initAll(ExampleSubsystem& sub) { + return parallel({ + sub.command(ExampleSubsystem::INIT), + // add more subsystems here + }); + } + + // Grab sequence: lower arm, wait, close gripper + inline ActionPtr pickUp(ExampleSubsystem& sub) { + return sequential({ + sub.command(ExampleSubsystem::GRAB), + sleep_ms(400), + instant([]{ gripper.setPosition(0); }), + }); + } + + // Release sequence: open gripper, raise arm + inline ActionPtr release(ExampleSubsystem& sub) { + return sequential({ + instant([]{ gripper.setPosition(180); }), + sleep_ms(200), + sub.command(ExampleSubsystem::RELEASE), + }); + } +} diff --git a/RobotFirmware/lib/HexaNRL/src/examples/ExampleSubsystem.h b/RobotFirmware/lib/HexaNRL/src/examples/ExampleSubsystem.h new file mode 100644 index 0000000..b85a3c8 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/examples/ExampleSubsystem.h @@ -0,0 +1,41 @@ +#pragma once +#include "NRL.h" + +// ============================================================ +// ExampleSubsystem.h — optional subsystem pattern +// ============================================================ +// You do NOT need to use this. If your code is simple, put +// everything directly in your own opmode file. +// +// Use this pattern when you want to group hardware belonging +// to one mechanism (arm, intake, shooter, etc.) into its own +// class with named states — the same way AG_2026 works. +// +// Pattern: +// 1. Define an enum for the states your mechanism can be in +// 2. Write update() to switch hardware based on the state +// 3. Expose command() to return an Action for use in sequences +// +// Then in your OpMode: +// #include "examples/ExampleSubsystem.h" +// ExampleSubsystem mySub; +// runBlocking(mySub.command(ExampleSubsystem::GRAB)); + +class ExampleSubsystem { +public: + enum State { INIT, GRAB, RELEASE }; + + // Update hardware immediately + void update(State s) { + switch (s) { + case INIT: arm.setPosition(90); break; + case GRAB: arm.setPosition(0); break; + case RELEASE: arm.setPosition(180); break; + } + } + + // Return an Action that can be used in sequential() / parallel() + ActionPtr command(State s) { + return instant([this, s]() { update(s); }); + } +}; diff --git a/RobotFirmware/lib/HexaNRL/src/examples/platformio.ini b/RobotFirmware/lib/HexaNRL/src/examples/platformio.ini new file mode 100644 index 0000000..d1cc8d6 --- /dev/null +++ b/RobotFirmware/lib/HexaNRL/src/examples/platformio.ini @@ -0,0 +1,53 @@ +[platformio]
+src_dir = src
+default_envs = robot
+
+[env:robot]
+platform = espressif32@^6.4.0
+board = esp32-s3-devkitc-1
+framework = arduino
+extra_scripts = pre:link_prebuilt.py
+monitor_speed = 115200
+board_build.partitions = partitions.csv
+
+; Compile opmodes/ alongside src/ — students only ever open opmodes/
+build_src_filter = +<**/*> +<../opmodes/**/*>
+
+; FreeRTOS at 1000Hz ticks — gives 1ms resolution for vTaskDelayUntil
+build_unflags = -std=gnu++11 -std=c++11
+
+build_flags =
+ -DNRL_TEAM_NUMBER=205
+ -DNRL_WIFI_CHANNEL=1
+ "-DNRL_TEAM_NAME=\"Pixel Pokers\""
+ -DCONFIG_FREERTOS_HZ=1000
+ -DCORE_DEBUG_LEVEL=3
+ -std=gnu++17
+ -DARDUINO_USB_MODE=1
+ -DARDUINO_USB_CDC_ON_BOOT=1
+
+; NOTE: no licence-related build flag belongs in this file, and none is read
+; from it. This file is copied verbatim into every generated student project and
+; ships in the public kit, so treat everything in it as public.
+;
+; Licence behaviour is fixed at kit-build time by the keys compiled into
+; libHexaNRL_static.a -- it is not configurable from here, and adding a flag
+; would not change it.
+
+lib_deps =
+ Preferences
+ adafruit/Adafruit NeoPixel
+ adafruit/Adafruit LSM6DS
+ adafruit/Adafruit Unified Sensor
+
+; RobotFirmware/lib = runner, comms, gamepad, NRL umbrella, RobotConfig
+; Root lib/Hexa* = hardware drivers (HexaServos, HexaOLED, HexaIMU, HexaHAL,
+; HexaLED, HexaPower)
+lib_extra_dirs =
+ lib
+ ../lib/HexaServos
+ ../lib/HexaOLED
+ ../lib/HexaIMU
+ ../lib/HexaHAL
+ ../lib/HexaLED
+ ../lib/HexaPower
|
