Compare commits
14 Commits
v1.1.0-bet
...
v1.1.0-rc1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9af6015aa3 | ||
|
|
9c2ac97158 | ||
|
|
e6934cdb18 | ||
|
|
636e1252dc | ||
|
|
b07e8c7dab | ||
|
|
c34e4c4dea | ||
|
|
59f8a7faa3 | ||
|
|
df338987b6 | ||
|
|
60679e097f | ||
|
|
0431425f38 | ||
|
|
cc20c5e6f2 | ||
|
|
e605b1cd3e | ||
|
|
26f3229b1e | ||
|
|
9ee0d99dd8 |
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "weevil"
|
name = "weevil"
|
||||||
version = "1.1.0-beta.1"
|
version = "1.1.0-rc1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = ["Eric Ratliff <eric@nxlearn.net>"]
|
authors = ["Eric Ratliff <eric@nxlearn.net>"]
|
||||||
description = "FTC robotics project generator - bores into complexity, emerges with clean code"
|
description = "FTC robotics project generator - bores into complexity, emerges with clean code"
|
||||||
@@ -56,6 +56,7 @@ which = "7.0"
|
|||||||
|
|
||||||
# Colors
|
# Colors
|
||||||
colored = "2.1"
|
colored = "2.1"
|
||||||
|
chrono = "0.4.43"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3.13"
|
tempfile = "3.13"
|
||||||
|
|||||||
689
README.md
689
README.md
@@ -26,19 +26,102 @@ This approach works against standard software engineering practices and creates
|
|||||||
- ✅ Generate all build/deploy scripts automatically
|
- ✅ Generate all build/deploy scripts automatically
|
||||||
- ✅ Enable proper version control workflows
|
- ✅ Enable proper version control workflows
|
||||||
- ✅ Are actually testable and maintainable
|
- ✅ Are actually testable and maintainable
|
||||||
|
- ✅ Work seamlessly with Android Studio
|
||||||
|
- ✅ Support proxy/air-gapped environments
|
||||||
|
- ✅ **Start from professional templates with working code** ⭐ NEW in v1.1.0!
|
||||||
|
|
||||||
Students focus on building robots, not navigating SDK internals.
|
Students focus on building robots, not navigating SDK internals.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## ⭐ What's New in v1.1.0
|
||||||
|
|
||||||
|
### Professional Templates - The Game Changer!
|
||||||
|
|
||||||
|
**Start with working, tested code instead of empty files!**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create with our professional testing showcase
|
||||||
|
weevil new my-robot --template testing
|
||||||
|
|
||||||
|
cd my-robot
|
||||||
|
./gradlew test # 45 tests pass in < 2 seconds ✓
|
||||||
|
```
|
||||||
|
|
||||||
|
**You get:**
|
||||||
|
- ✅ 3 complete, working subsystems
|
||||||
|
- ✅ Full hardware abstraction layer
|
||||||
|
- ✅ 45 passing tests demonstrating best practices
|
||||||
|
- ✅ Professional documentation (6 files)
|
||||||
|
- ✅ Real patterns used in competition
|
||||||
|
|
||||||
|
**Why this matters:** Most FTC teams start with empty projects and learn by trial-and-error on hardware. Now you can learn from professional code, run tests instantly on your PC, and modify working examples for your robot.
|
||||||
|
|
||||||
|
This is the kind of code students would write if they had years of experience. Now they can START with it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
|
### 🎯 Professional Templates (v1.1.0)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# List available templates
|
||||||
|
weevil new --list-templates
|
||||||
|
|
||||||
|
# Create with basic template (minimal)
|
||||||
|
weevil new my-robot
|
||||||
|
|
||||||
|
# Create with testing template (professional showcase)
|
||||||
|
weevil new my-robot --template testing
|
||||||
|
```
|
||||||
|
|
||||||
|
**Available Templates:**
|
||||||
|
|
||||||
|
| Template | Description | Files | Tests | Perfect For |
|
||||||
|
|----------|-------------|-------|-------|-------------|
|
||||||
|
| `basic` | Minimal starting point | ~10 | 1 | Starting from scratch |
|
||||||
|
| `testing` | Professional showcase | ~30 | 45 | Learning best practices |
|
||||||
|
|
||||||
|
**Testing Template Includes:**
|
||||||
|
|
||||||
|
**Subsystems** (3 complete implementations):
|
||||||
|
- `MotorCycler` - State machine for motor cycling with timing
|
||||||
|
- `WallApproach` - Sensor-based wall approach with deceleration
|
||||||
|
- `TurnController` - Gyro-based turning with angle wraparound
|
||||||
|
|
||||||
|
**Hardware Layer** (interfaces + implementations + mocks):
|
||||||
|
- Motor controllers with FTC wrappers
|
||||||
|
- Distance sensors with test mocks
|
||||||
|
- Gyro sensors with simulation
|
||||||
|
- Clean abstraction enabling unit testing
|
||||||
|
|
||||||
|
**Tests** (45 tests, < 2 second runtime):
|
||||||
|
- Unit tests for each subsystem
|
||||||
|
- Integration tests for system behaviors
|
||||||
|
- Mock-based testing (no hardware required!)
|
||||||
|
|
||||||
|
**Documentation** (professional quality):
|
||||||
|
- `DESIGN_AND_TEST_PLAN.md` - Complete architecture
|
||||||
|
- `TESTING_GUIDE.md` - How to write tests
|
||||||
|
- `TESTING_SHOWCASE.md` - What's included
|
||||||
|
- `SOLUTION.md` - Problem-solving patterns
|
||||||
|
- `ARCHITECTURE.md` - Design decisions
|
||||||
|
- `QUICKSTART.md` - Get started in 5 minutes
|
||||||
|
|
||||||
### 🎯 Clean Project Structure
|
### 🎯 Clean Project Structure
|
||||||
```
|
```
|
||||||
my-robot/
|
my-robot/
|
||||||
├── src/
|
├── src/
|
||||||
│ ├── main/java/robot/ # Your robot code lives here
|
│ ├── main/java/robot/ # Your robot code lives here
|
||||||
|
│ │ ├── hardware/ # Hardware interfaces (in testing template)
|
||||||
|
│ │ ├── subsystems/ # Robot subsystems (in testing template)
|
||||||
|
│ │ └── opmodes/ # OpModes
|
||||||
│ └── test/java/robot/ # Unit tests (run on PC!)
|
│ └── test/java/robot/ # Unit tests (run on PC!)
|
||||||
|
│ ├── hardware/ # Hardware mocks (in testing template)
|
||||||
|
│ └── subsystems/ # Subsystem tests (in testing template)
|
||||||
|
├── docs/ # Documentation (in testing template)
|
||||||
|
├── .idea/ # Android Studio integration
|
||||||
├── build.sh / build.bat # One command to build
|
├── build.sh / build.bat # One command to build
|
||||||
├── deploy.sh / deploy.bat # One command to deploy
|
├── deploy.sh / deploy.bat # One command to deploy
|
||||||
└── .weevil.toml # Project configuration
|
└── .weevil.toml # Project configuration
|
||||||
@@ -46,8 +129,12 @@ my-robot/
|
|||||||
|
|
||||||
### 🚀 Simple Commands
|
### 🚀 Simple Commands
|
||||||
```bash
|
```bash
|
||||||
|
# Set up development environment
|
||||||
|
weevil setup
|
||||||
|
|
||||||
# Create a new robot project
|
# Create a new robot project
|
||||||
weevil new awesome-robot
|
weevil new awesome-robot # Basic template
|
||||||
|
weevil new awesome-robot --template testing # Testing showcase
|
||||||
|
|
||||||
# Test your code (no robot required!)
|
# Test your code (no robot required!)
|
||||||
cd awesome-robot
|
cd awesome-robot
|
||||||
@@ -60,6 +147,9 @@ cd awesome-robot
|
|||||||
|
|
||||||
### 🔧 Project Management
|
### 🔧 Project Management
|
||||||
```bash
|
```bash
|
||||||
|
# Check system health
|
||||||
|
weevil doctor
|
||||||
|
|
||||||
# Upgrade project infrastructure
|
# Upgrade project infrastructure
|
||||||
weevil upgrade awesome-robot
|
weevil upgrade awesome-robot
|
||||||
|
|
||||||
@@ -69,15 +159,46 @@ weevil config awesome-robot --set-sdk /path/to/different/sdk
|
|||||||
|
|
||||||
# Check SDK status
|
# Check SDK status
|
||||||
weevil sdk status
|
weevil sdk status
|
||||||
|
|
||||||
|
# Remove installed components
|
||||||
|
weevil uninstall --dry-run
|
||||||
|
weevil uninstall
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 🌐 Proxy Support (v1.1.0)
|
||||||
|
Work behind corporate firewalls or in air-gapped environments:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Use HTTP proxy for all downloads
|
||||||
|
weevil --proxy http://proxy.company.com:8080 setup
|
||||||
|
weevil --proxy http://proxy.company.com:8080 new my-robot
|
||||||
|
|
||||||
|
# Bypass proxy (for local/direct connections)
|
||||||
|
weevil --no-proxy setup
|
||||||
|
|
||||||
|
# Proxy auto-detected from HTTPS_PROXY/HTTP_PROXY environment variables
|
||||||
|
export HTTPS_PROXY=http://proxy:8080
|
||||||
|
weevil setup # Uses proxy automatically
|
||||||
|
```
|
||||||
|
|
||||||
|
### 💻 Android Studio Integration (v1.1.0)
|
||||||
|
Projects work seamlessly with Android Studio:
|
||||||
|
- **One-click deployment** - Run configurations appear automatically
|
||||||
|
- **Clean file tree** - Internal directories hidden, only your code visible
|
||||||
|
- **No configuration needed** - Just open the project and hit Run
|
||||||
|
|
||||||
|
See [Android Studio Setup](#android-studio-setup) for details.
|
||||||
|
|
||||||
### ✨ Smart Features
|
### ✨ Smart Features
|
||||||
|
- **Professional templates** - Start with tested, working code ⭐ NEW!
|
||||||
- **Per-project SDK configuration** - Different projects can use different SDK versions
|
- **Per-project SDK configuration** - Different projects can use different SDK versions
|
||||||
- **Automatic Gradle wrapper** - No manual setup required
|
- **Automatic Gradle wrapper** - No manual setup required
|
||||||
- **Cross-platform** - Works on Linux, macOS, and Windows
|
- **Cross-platform** - Works on Linux, macOS, and Windows
|
||||||
- **Zero SDK modification** - Your SDK stays pristine
|
- **Zero SDK modification** - Your SDK stays pristine
|
||||||
- **Git-ready** - Projects initialize with proper `.gitignore`
|
- **Git-ready** - Projects initialize with proper `.gitignore`
|
||||||
- **Upgrade-safe** - Update build scripts without losing code
|
- **Upgrade-safe** - Update build scripts without losing code
|
||||||
|
- **System diagnostics** - `weevil doctor` checks your environment health
|
||||||
|
- **Selective uninstall** - Remove specific components without nuking everything
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -96,150 +217,272 @@ export PATH="$PATH:$(pwd)/target/release"
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
- Rust 1.70+ (for building)
|
- Rust 1.70+ (for building Weevil)
|
||||||
- Java 11+ (for running Gradle)
|
- Java 11+ (for running Gradle)
|
||||||
- Android SDK with platform-tools (for deployment)
|
- Android SDK with platform-tools (for deployment)
|
||||||
- FTC SDK (Weevil can download it for you)
|
- FTC SDK (Weevil can install it for you)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
### 1. Create Your First Project
|
### 1. Set Up Your Environment
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil setup
|
||||||
|
```
|
||||||
|
|
||||||
|
Weevil will:
|
||||||
|
- Download and install FTC SDK
|
||||||
|
- Download and install Android SDK (if needed)
|
||||||
|
- Set up Gradle wrapper
|
||||||
|
- Verify all dependencies
|
||||||
|
|
||||||
|
### 2. Create Your First Project
|
||||||
|
|
||||||
|
**Recommended: Start with the testing template**
|
||||||
|
```bash
|
||||||
|
weevil new my-robot --template testing
|
||||||
|
cd my-robot
|
||||||
|
```
|
||||||
|
|
||||||
|
**Or start minimal:**
|
||||||
```bash
|
```bash
|
||||||
weevil new my-robot
|
weevil new my-robot
|
||||||
cd my-robot
|
cd my-robot
|
||||||
```
|
```
|
||||||
|
|
||||||
Weevil will:
|
### 3. Run Tests (Testing Template)
|
||||||
- Download the FTC SDK if needed (or use existing)
|
|
||||||
- Generate your project structure
|
|
||||||
- Set up Gradle wrapper
|
|
||||||
- Initialize git repository
|
|
||||||
- Create example test files
|
|
||||||
|
|
||||||
### 2. Write Some Code
|
|
||||||
|
|
||||||
Create `src/main/java/robot/MyOpMode.java`:
|
|
||||||
|
|
||||||
```java
|
|
||||||
package robot;
|
|
||||||
|
|
||||||
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
|
|
||||||
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
|
|
||||||
|
|
||||||
@TeleOp(name="My OpMode")
|
|
||||||
public class MyOpMode extends LinearOpMode {
|
|
||||||
@Override
|
|
||||||
public void runOpMode() {
|
|
||||||
telemetry.addData("Status", "Initialized");
|
|
||||||
telemetry.update();
|
|
||||||
|
|
||||||
waitForStart();
|
|
||||||
|
|
||||||
while (opModeIsActive()) {
|
|
||||||
telemetry.addData("Status", "Running");
|
|
||||||
telemetry.update();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Test Locally (No Robot!)
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./gradlew test
|
./gradlew test
|
||||||
```
|
```
|
||||||
|
|
||||||
Write unit tests in `src/test/java/robot/` that run on your PC. No need to deploy to a robot for every code change!
|
Output:
|
||||||
|
```
|
||||||
|
BasicTest > testBasic() PASSED
|
||||||
|
MotorCyclerTest > testInitialState() PASSED
|
||||||
|
MotorCyclerTest > testCycleFromOnToOff() PASSED
|
||||||
|
... 42 more tests ...
|
||||||
|
|
||||||
### 4. Deploy to Robot
|
BUILD SUCCESSFUL in 1s
|
||||||
|
45 tests passed
|
||||||
```bash
|
|
||||||
# Build APK
|
|
||||||
./build.sh
|
|
||||||
|
|
||||||
# Deploy via USB
|
|
||||||
./deploy.sh --usb
|
|
||||||
|
|
||||||
# Deploy via WiFi
|
|
||||||
./deploy.sh --wifi -i 192.168.49.1
|
|
||||||
|
|
||||||
# Auto-detect (tries USB, falls back to WiFi)
|
|
||||||
./deploy.sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
**All tests run on your PC - no robot required!**
|
||||||
|
|
||||||
## Advanced Usage
|
### 4. Explore the Code (Testing Template)
|
||||||
|
|
||||||
### Multiple SDK Versions
|
|
||||||
|
|
||||||
Working with multiple SDK versions? No problem:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Create project with specific SDK
|
# Read the overview
|
||||||
weevil new experimental-bot --ftc-sdk /path/to/sdk-v11.0
|
cat QUICKSTART.md
|
||||||
|
|
||||||
# Later, switch SDKs
|
# Study a subsystem
|
||||||
weevil config experimental-bot --set-sdk /path/to/sdk-v11.1
|
cat src/main/java/robot/subsystems/WallApproach.java
|
||||||
|
|
||||||
# Rebuild with new SDK
|
# See how it's tested
|
||||||
weevil upgrade experimental-bot
|
cat src/test/java/robot/subsystems/WallApproachTest.java
|
||||||
cd experimental-bot
|
|
||||||
./build.sh
|
# Check the architecture
|
||||||
|
cat DESIGN_AND_TEST_PLAN.md
|
||||||
```
|
```
|
||||||
|
|
||||||
### Upgrading Projects
|
### 5. Modify for Your Robot
|
||||||
|
|
||||||
When Weevil releases new features:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
weevil upgrade my-robot
|
# The testing template gives you working patterns to modify
|
||||||
|
# Option 1: Modify existing subsystems
|
||||||
|
vim src/main/java/robot/subsystems/WallApproach.java
|
||||||
|
|
||||||
|
# Option 2: Copy and adapt
|
||||||
|
cp src/main/java/robot/subsystems/WallApproach.java \
|
||||||
|
src/main/java/robot/subsystems/MyApproach.java
|
||||||
|
|
||||||
|
# Run tests to verify
|
||||||
|
./gradlew test
|
||||||
```
|
```
|
||||||
|
|
||||||
This updates:
|
### 6. Deploy to Robot
|
||||||
- Build scripts
|
|
||||||
- Deployment scripts
|
|
||||||
- Gradle configuration
|
|
||||||
- Project templates
|
|
||||||
|
|
||||||
**Your code in `src/` is never touched.**
|
|
||||||
|
|
||||||
### Cross-Platform Development
|
|
||||||
|
|
||||||
All scripts work on Windows, Linux, and macOS:
|
|
||||||
|
|
||||||
**Linux/Mac:**
|
|
||||||
```bash
|
```bash
|
||||||
./build.sh
|
./build.sh
|
||||||
./deploy.sh --wifi
|
./deploy.sh --wifi
|
||||||
```
|
```
|
||||||
|
|
||||||
**Windows:**
|
---
|
||||||
```cmd
|
|
||||||
build.bat
|
## Template System
|
||||||
deploy.bat --wifi
|
|
||||||
|
### Listing Templates
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil new --list-templates
|
||||||
|
```
|
||||||
|
|
||||||
|
Output:
|
||||||
|
```
|
||||||
|
Available templates:
|
||||||
|
|
||||||
|
basic (default)
|
||||||
|
Minimal FTC project structure
|
||||||
|
Perfect for: Teams starting from scratch
|
||||||
|
Files: ~10 | Code: ~50 lines
|
||||||
|
|
||||||
|
testing
|
||||||
|
Professional testing showcase with examples
|
||||||
|
Perfect for: Learning best practices
|
||||||
|
Files: ~30 | Code: ~2,500 lines | Tests: 45
|
||||||
|
Includes:
|
||||||
|
• 3 complete subsystems (MotorCycler, WallApproach, TurnController)
|
||||||
|
• Hardware abstraction layer with mocks
|
||||||
|
• 45 passing tests (< 2 seconds)
|
||||||
|
• Comprehensive documentation
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
weevil new <project-name> # Uses basic template
|
||||||
|
weevil new <project-name> --template testing # Uses testing template
|
||||||
|
```
|
||||||
|
|
||||||
|
### Basic Template
|
||||||
|
|
||||||
|
**Use when:** Starting from scratch, want minimal boilerplate
|
||||||
|
|
||||||
|
**What you get:**
|
||||||
|
- Clean directory structure
|
||||||
|
- Placeholder OpMode
|
||||||
|
- Basic test file
|
||||||
|
- Build/deploy scripts
|
||||||
|
- Documentation
|
||||||
|
|
||||||
|
**Files:** ~10
|
||||||
|
**Code:** ~50 lines
|
||||||
|
**Tests:** 1
|
||||||
|
|
||||||
|
### Testing Template
|
||||||
|
|
||||||
|
**Use when:** Want to learn professional patterns, need working examples
|
||||||
|
|
||||||
|
**What you get:**
|
||||||
|
|
||||||
|
| Category | What's Included |
|
||||||
|
|----------|-----------------|
|
||||||
|
| **Subsystems** | 3 complete implementations demonstrating real patterns |
|
||||||
|
| **Hardware** | 6 interfaces + FTC wrappers + test mocks |
|
||||||
|
| **Tests** | 45 comprehensive tests (unit + integration) |
|
||||||
|
| **Docs** | 6 professional documentation files |
|
||||||
|
| **Patterns** | State machines, hardware abstraction, testing strategies |
|
||||||
|
|
||||||
|
**Files:** ~30
|
||||||
|
**Code:** ~2,500 lines
|
||||||
|
**Tests:** 45 (< 2 second runtime)
|
||||||
|
|
||||||
|
**Perfect for:**
|
||||||
|
- Learning how professional FTC code is structured
|
||||||
|
- Understanding test-driven development
|
||||||
|
- Seeing working examples before writing your own
|
||||||
|
- Teaching your team best practices
|
||||||
|
- Workshops and training sessions
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Android Studio Setup
|
||||||
|
|
||||||
|
### Opening a Weevil Project
|
||||||
|
|
||||||
|
1. Launch Android Studio
|
||||||
|
2. Choose **Open** (not "New Project")
|
||||||
|
3. Navigate to your project directory
|
||||||
|
4. Click OK
|
||||||
|
|
||||||
|
You'll see:
|
||||||
|
- Clean file tree (only your code visible)
|
||||||
|
- Run configurations in dropdown
|
||||||
|
- One-click deployment
|
||||||
|
|
||||||
|
### First-Time: Install Shell Script Plugin
|
||||||
|
|
||||||
|
1. **File → Settings** (Ctrl+Alt+S)
|
||||||
|
2. **Plugins → Marketplace**
|
||||||
|
3. Search **"Shell Script"**
|
||||||
|
4. Install plugin (by JetBrains)
|
||||||
|
5. Restart Android Studio
|
||||||
|
|
||||||
|
### Running from Android Studio
|
||||||
|
|
||||||
|
1. Select configuration (Test, Build, Deploy)
|
||||||
|
2. Click green play button (▶)
|
||||||
|
3. Watch output in Run panel
|
||||||
|
|
||||||
|
**That's it!** Deploy to robot without leaving IDE.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Advanced Usage
|
||||||
|
|
||||||
|
### Proxy Configuration
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Corporate proxy
|
||||||
|
weevil --proxy http://proxy.company.com:8080 setup
|
||||||
|
|
||||||
|
# Environment variable (auto-detected)
|
||||||
|
export HTTPS_PROXY=http://proxy:8080
|
||||||
|
weevil setup
|
||||||
|
|
||||||
|
# Bypass proxy
|
||||||
|
weevil --no-proxy setup
|
||||||
|
```
|
||||||
|
|
||||||
|
### Multiple SDK Versions
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create with specific SDK
|
||||||
|
weevil new experimental-bot --ftc-sdk /path/to/sdk-v11.0
|
||||||
|
|
||||||
|
# Switch SDKs later
|
||||||
|
weevil config experimental-bot --set-sdk /path/to/sdk-v11.1
|
||||||
|
```
|
||||||
|
|
||||||
|
### Upgrading Projects
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil upgrade my-robot
|
||||||
|
```
|
||||||
|
|
||||||
|
Updates build scripts, Gradle config, and IDE integration.
|
||||||
|
**Your code in `src/` is never touched.**
|
||||||
|
|
||||||
|
### System Maintenance
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil doctor # Check system health
|
||||||
|
weevil uninstall --dry-run # Preview uninstall
|
||||||
|
weevil uninstall --only 1 # Remove specific component
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Project Configuration
|
## Project Configuration
|
||||||
|
|
||||||
Each project has a `.weevil.toml` file:
|
`.weevil.toml`:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
|
[project]
|
||||||
project_name = "my-robot"
|
project_name = "my-robot"
|
||||||
weevil_version = "1.0.0"
|
created = "2026-02-02T10:30:00Z"
|
||||||
|
weevil_version = "1.1.0"
|
||||||
|
template = "testing"
|
||||||
ftc_sdk_path = "/home/user/.weevil/ftc-sdk"
|
ftc_sdk_path = "/home/user/.weevil/ftc-sdk"
|
||||||
ftc_sdk_version = "v10.1.1"
|
|
||||||
|
[ftc]
|
||||||
|
sdk_version = "v10.1.1"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
gradle_version = "8.5"
|
||||||
```
|
```
|
||||||
|
|
||||||
You can edit this manually or use:
|
Manage with:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
weevil config my-robot # View config
|
weevil config my-robot # View
|
||||||
weevil config my-robot --set-sdk /new/sdk # Change SDK
|
weevil config my-robot --set-sdk /new/sdk # Change SDK
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -250,88 +493,93 @@ weevil config my-robot --set-sdk /new/sdk # Change SDK
|
|||||||
### Recommended Git Workflow
|
### Recommended Git Workflow
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Create project
|
weevil new competition-bot --template testing
|
||||||
weevil new competition-bot
|
|
||||||
cd competition-bot
|
cd competition-bot
|
||||||
|
|
||||||
# Project is already a git repo!
|
# Already a git repo!
|
||||||
git remote add origin https://nxgit.dev/team/robot.git
|
git remote add origin https://nxgit.dev/team/robot.git
|
||||||
git push -u origin main
|
git push -u origin main
|
||||||
|
|
||||||
# Make changes
|
# Development cycle
|
||||||
# ... edit code ...
|
./gradlew test # Test locally
|
||||||
./gradlew test
|
git commit -am "Add feature"
|
||||||
git commit -am "Add autonomous mode"
|
|
||||||
git push
|
git push
|
||||||
|
./deploy.sh # Deploy to robot
|
||||||
# Deploy to robot
|
|
||||||
./deploy.sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Testing Strategy
|
### Learning from the Testing Template
|
||||||
|
|
||||||
1. **Unit Tests** - Test business logic on your PC
|
|
||||||
```bash
|
```bash
|
||||||
|
# Create learning project
|
||||||
|
weevil new learning --template testing
|
||||||
|
cd learning
|
||||||
|
|
||||||
|
# Study the architecture
|
||||||
|
cat DESIGN_AND_TEST_PLAN.md
|
||||||
|
|
||||||
|
# Run tests and see patterns
|
||||||
./gradlew test
|
./gradlew test
|
||||||
```
|
|
||||||
|
|
||||||
2. **Integration Tests** - Test on actual hardware
|
# Read a subsystem
|
||||||
```bash
|
cat src/main/java/robot/subsystems/MotorCycler.java
|
||||||
./build.sh
|
|
||||||
./deploy.sh --usb
|
|
||||||
# Run via Driver Station
|
|
||||||
```
|
|
||||||
|
|
||||||
### Team Collaboration
|
# Read its tests
|
||||||
|
cat src/test/java/robot/subsystems/MotorCyclerTest.java
|
||||||
|
|
||||||
**Project Structure is Portable:**
|
# Copy patterns for your robot
|
||||||
```bash
|
cp src/main/java/robot/subsystems/MotorCycler.java \
|
||||||
# Team member clones repo
|
src/main/java/robot/subsystems/MySystem.java
|
||||||
git clone https://nxgit.dev/team/robot.git
|
|
||||||
cd robot
|
|
||||||
|
|
||||||
# Check SDK location
|
|
||||||
weevil config .
|
|
||||||
|
|
||||||
# Set SDK to local path
|
|
||||||
weevil config . --set-sdk ~/ftc-sdk
|
|
||||||
|
|
||||||
# Build and deploy
|
|
||||||
./build.sh
|
|
||||||
./deploy.sh
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Command Reference
|
## Command Reference
|
||||||
|
|
||||||
|
### Environment Commands
|
||||||
|
|
||||||
|
| Command | Description |
|
||||||
|
|---------|-------------|
|
||||||
|
| `weevil doctor` | Check system health |
|
||||||
|
| `weevil setup` | Install FTC SDK, Android SDK |
|
||||||
|
| `weevil setup --ftc-sdk <path>` | Install to custom location |
|
||||||
|
| `weevil uninstall` | Remove all components |
|
||||||
|
| `weevil uninstall --dry-run` | Preview uninstall |
|
||||||
|
| `weevil uninstall --only <N>` | Remove specific component |
|
||||||
|
|
||||||
### Project Commands
|
### Project Commands
|
||||||
|
|
||||||
| Command | Description |
|
| Command | Description |
|
||||||
|---------|-------------|
|
|---------|-------------|
|
||||||
| `weevil new <name>` | Create new FTC project |
|
| `weevil new <name>` | Create project (basic template) |
|
||||||
|
| `weevil new <name> --template <t>` | Create with template |
|
||||||
|
| `weevil new --list-templates` | Show available templates |
|
||||||
| `weevil upgrade <path>` | Update project infrastructure |
|
| `weevil upgrade <path>` | Update project infrastructure |
|
||||||
| `weevil config <path>` | View project configuration |
|
| `weevil config <path>` | View configuration |
|
||||||
| `weevil config <path> --set-sdk <sdk>` | Change FTC SDK path |
|
| `weevil config <path> --set-sdk <sdk>` | Change FTC SDK |
|
||||||
|
|
||||||
### SDK Commands
|
### SDK Commands
|
||||||
|
|
||||||
| Command | Description |
|
| Command | Description |
|
||||||
|---------|-------------|
|
|---------|-------------|
|
||||||
| `weevil sdk status` | Show SDK locations and status |
|
| `weevil sdk status` | Show SDK status |
|
||||||
| `weevil sdk install` | Download and install SDKs |
|
| `weevil sdk install` | Download and install SDKs |
|
||||||
| `weevil sdk update` | Update SDKs to latest versions |
|
| `weevil sdk update` | Update to latest SDKs |
|
||||||
|
|
||||||
### Deployment Options
|
### Global Flags
|
||||||
|
|
||||||
**`deploy.sh` / `deploy.bat` flags:**
|
|
||||||
|
|
||||||
| Flag | Description |
|
| Flag | Description |
|
||||||
|------|-------------|
|
|------|-------------|
|
||||||
| `--usb` | Force USB deployment |
|
| `--proxy <url>` | Use HTTP proxy |
|
||||||
| `--wifi` | Force WiFi deployment |
|
| `--no-proxy` | Bypass proxy |
|
||||||
| `-i <ip>` | Custom Control Hub IP |
|
|
||||||
| `--timeout <sec>` | WiFi connection timeout |
|
### Deployment Options
|
||||||
|
|
||||||
|
| Flag | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `--usb` | Force USB |
|
||||||
|
| `--wifi` | Force WiFi |
|
||||||
|
| `-i <ip>` | Custom IP |
|
||||||
|
| `--timeout <sec>` | WiFi timeout |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -340,130 +588,91 @@ weevil config . --set-sdk ~/ftc-sdk
|
|||||||
### How It Works
|
### How It Works
|
||||||
|
|
||||||
1. **Project Generation**
|
1. **Project Generation**
|
||||||
- Creates standalone Java project structure
|
- Creates standalone Java project
|
||||||
- Generates Gradle build files that reference FTC SDK
|
- Optionally overlays template (basic/testing)
|
||||||
|
- Generates build files referencing FTC SDK
|
||||||
- Sets up deployment scripts
|
- Sets up deployment scripts
|
||||||
|
- Creates Android Studio integration
|
||||||
|
|
||||||
2. **Build Process**
|
2. **Build Process**
|
||||||
- Runs `deployToSDK` Gradle task
|
- Copies code to FTC SDK's TeamCode
|
||||||
- Copies your code to FTC SDK's `TeamCode` directory
|
- Builds APK using SDK
|
||||||
- Builds APK using SDK's Android configuration
|
- Leaves project directory clean
|
||||||
- Leaves your project directory clean
|
|
||||||
|
|
||||||
3. **Deployment**
|
3. **Deployment**
|
||||||
- Finds built APK in SDK
|
- Finds APK in SDK
|
||||||
- Connects to Control Hub (USB or WiFi)
|
- Connects to Control Hub (USB/WiFi)
|
||||||
- Installs APK using `adb`
|
- Installs using `adb`
|
||||||
|
|
||||||
### Why This Approach?
|
### Why This Approach?
|
||||||
|
|
||||||
**Separation of Concerns:**
|
**Separation of Concerns:**
|
||||||
- Your code: `my-robot/src/`
|
- Your code: `my-robot/src/`
|
||||||
- Build infrastructure: `my-robot/*.gradle.kts`
|
- Build infrastructure: `*.gradle.kts`
|
||||||
- FTC SDK: System-level installation
|
- FTC SDK: System installation
|
||||||
|
- Templates: Starting points
|
||||||
|
|
||||||
**Benefits:**
|
**Benefits:**
|
||||||
- Test code without SDK complications
|
- Test without SDK complications
|
||||||
- Multiple projects per SDK installation
|
- Multiple projects per SDK
|
||||||
- SDK updates don't break your projects
|
- SDK updates don't break projects
|
||||||
- Proper version control (no massive SDK in repo)
|
- Proper version control
|
||||||
- Industry-standard project structure
|
- Industry-standard structure
|
||||||
|
- Learn from professional examples
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
Weevil includes comprehensive tests:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Run all tests
|
cargo test # All tests
|
||||||
cargo test
|
cargo test --test integration # Integration tests
|
||||||
|
cargo test --test template_tests # Template tests
|
||||||
# Run specific test suites
|
|
||||||
cargo test --test integration
|
|
||||||
cargo test --test project_lifecycle
|
|
||||||
cargo test config_tests
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Test Coverage:**
|
**Coverage:**
|
||||||
- ✅ Project creation and structure
|
- ✅ Project creation
|
||||||
- ✅ Configuration persistence
|
- ✅ Template extraction
|
||||||
- ✅ SDK detection and validation
|
- ✅ Configuration
|
||||||
- ✅ Build script generation
|
- ✅ SDK detection
|
||||||
- ✅ Upgrade workflow
|
- ✅ Build scripts
|
||||||
- ✅ CLI commands
|
- ✅ Proxy support
|
||||||
|
- ✅ 62 tests passing
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
### "FTC SDK not found"
|
### "FTC SDK not found"
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Check SDK status
|
weevil doctor
|
||||||
weevil sdk status
|
weevil setup
|
||||||
|
|
||||||
# Install SDK
|
|
||||||
weevil sdk install
|
|
||||||
|
|
||||||
# Or specify custom location
|
|
||||||
weevil new my-robot --ftc-sdk /custom/path/to/sdk
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### "adb: command not found"
|
### "adb: command not found"
|
||||||
|
|
||||||
Install Android platform-tools:
|
|
||||||
|
|
||||||
**Linux:**
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt install android-tools-adb
|
weevil setup # Installs Android SDK with adb
|
||||||
```
|
```
|
||||||
|
|
||||||
**macOS:**
|
|
||||||
```bash
|
|
||||||
brew install android-platform-tools
|
|
||||||
```
|
|
||||||
|
|
||||||
**Windows:**
|
|
||||||
Download Android SDK Platform Tools from Google.
|
|
||||||
|
|
||||||
### "Build failed"
|
### "Build failed"
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Clean and rebuild
|
|
||||||
cd my-robot
|
|
||||||
./gradlew clean
|
./gradlew clean
|
||||||
./build.sh
|
./build.sh
|
||||||
|
weevil doctor
|
||||||
# Check SDK path
|
|
||||||
weevil config .
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### "Deploy failed - No devices"
|
### "Deploy failed - No devices"
|
||||||
|
**USB:** `./deploy.sh --usb`
|
||||||
|
**WiFi:** `./deploy.sh -i 192.168.43.1`
|
||||||
|
|
||||||
**USB:**
|
### "Unknown run configuration type ShellScript"
|
||||||
1. Connect robot via USB
|
Install Shell Script plugin in Android Studio (see [Android Studio Setup](#android-studio-setup))
|
||||||
2. Run `adb devices` to verify connection
|
|
||||||
3. Try `./deploy.sh --usb`
|
|
||||||
|
|
||||||
**WiFi:**
|
|
||||||
1. Connect to robot's WiFi network
|
|
||||||
2. Find Control Hub IP (usually 192.168.43.1 or 192.168.49.1)
|
|
||||||
3. Try `./deploy.sh -i <ip>`
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
Contributions welcome! Please:
|
Contributions welcome!
|
||||||
|
|
||||||
1. Fork the repository
|
|
||||||
2. Create a feature branch
|
|
||||||
3. Write tests for new features
|
|
||||||
4. Ensure `cargo test` passes with zero warnings
|
|
||||||
5. Submit a pull request
|
|
||||||
|
|
||||||
### Development Setup
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://www.nxgit.dev/nexus-workshops/weevil.git
|
git clone https://www.nxgit.dev/nexus-workshops/weevil.git
|
||||||
@@ -472,7 +681,7 @@ cargo build
|
|||||||
cargo test
|
cargo test
|
||||||
|
|
||||||
# Run locally
|
# Run locally
|
||||||
cargo run -- new test-project
|
cargo run -- new test-project --template testing
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -481,21 +690,23 @@ cargo run -- new test-project
|
|||||||
|
|
||||||
**Why "Weevil"?**
|
**Why "Weevil"?**
|
||||||
|
|
||||||
Like the boll weevil that bores through complex cotton bolls to reach the valuable fibers inside, this tool bores through the complexity of the FTC SDK structure to help students reach what matters: building robots and learning to code.
|
Like the boll weevil boring through cotton bolls to reach valuable fibers, this tool bores through SDK complexity to help students reach what matters: building robots and learning to code.
|
||||||
|
|
||||||
**Design Principles:**
|
**Design Principles:**
|
||||||
|
|
||||||
1. **Students first** - Minimize cognitive load for learners
|
1. **Students first** - Minimize cognitive load
|
||||||
2. **Industry practices** - Teach real software engineering
|
2. **Industry practices** - Teach real software engineering
|
||||||
3. **Testability** - Enable TDD and proper testing workflows
|
3. **Testability** - Enable TDD workflows
|
||||||
4. **Simplicity** - One command should do one obvious thing
|
4. **Simplicity** - One command, one purpose
|
||||||
5. **Transparency** - Students should understand what's happening
|
5. **Transparency** - Students understand what's happening
|
||||||
|
6. **Tool compatibility** - Work with familiar tools
|
||||||
|
7. **Learn from examples** - Provide professional code to study
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT License - See [LICENSE](LICENSE) file for details.
|
MIT License - See [LICENSE](LICENSE)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -503,7 +714,7 @@ MIT License - See [LICENSE](LICENSE) file for details.
|
|||||||
|
|
||||||
Created by Eric Ratliff for [Nexus Workshops LLC](https://nexusworkshops.com)
|
Created by Eric Ratliff for [Nexus Workshops LLC](https://nexusworkshops.com)
|
||||||
|
|
||||||
Built with frustration at unnecessarily complex robotics frameworks, and hope that students can focus on robotics instead of build systems.
|
Built with frustration at unnecessarily complex frameworks, and hope that students can focus on robotics instead of build systems.
|
||||||
|
|
||||||
**For FIRST Tech Challenge teams everywhere** - may your builds be fast and your deployments successful. 🤖
|
**For FIRST Tech Challenge teams everywhere** - may your builds be fast and your deployments successful. 🤖
|
||||||
|
|
||||||
@@ -511,22 +722,28 @@ Built with frustration at unnecessarily complex robotics frameworks, and hope th
|
|||||||
|
|
||||||
## Project Status
|
## Project Status
|
||||||
|
|
||||||
**Current Version:** 1.0.0
|
**Current Version:** 1.1.0
|
||||||
|
|
||||||
**What Works:**
|
**What Works:**
|
||||||
- ✅ Project generation
|
- ✅ Project generation with templates
|
||||||
|
- ✅ Professional testing showcase template
|
||||||
- ✅ Cross-platform build/deploy
|
- ✅ Cross-platform build/deploy
|
||||||
- ✅ SDK management
|
- ✅ SDK management and auto-install
|
||||||
- ✅ Configuration management
|
- ✅ Configuration management
|
||||||
- ✅ Project upgrades
|
- ✅ Project upgrades
|
||||||
- ✅ Local testing
|
- ✅ Local unit testing
|
||||||
|
- ✅ System diagnostics
|
||||||
|
- ✅ Selective uninstall
|
||||||
|
- ✅ Proxy support
|
||||||
|
- ✅ Android Studio integration
|
||||||
|
|
||||||
**Roadmap:**
|
**Roadmap:**
|
||||||
- 📋 Package management for FTC libraries
|
- 📋 `weevil add` - Package management system (v1.2.0)
|
||||||
- 📋 Template system for common robot configurations
|
- 📋 Community package repository
|
||||||
- 📋 IDE integration (VS Code, IntelliJ)
|
- 📋 Additional templates (mecanum, vision)
|
||||||
|
- 📋 VS Code integration
|
||||||
- 📋 Team collaboration features
|
- 📋 Team collaboration features
|
||||||
- 📋 Automated testing on robot hardware
|
- 📋 Multi-robot support
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
858
docs/ROADMAP.md
858
docs/ROADMAP.md
File diff suppressed because it is too large
Load Diff
727
docs/TEMPLATE-PACKAGE-SPEC.md
Normal file
727
docs/TEMPLATE-PACKAGE-SPEC.md
Normal file
@@ -0,0 +1,727 @@
|
|||||||
|
# Weevil Template & Package System - Specification
|
||||||
|
|
||||||
|
**Version:** 1.1
|
||||||
|
**Date:** February 2, 2026
|
||||||
|
**Status:** Template system ✅ COMPLETE | Package system 📋 Planned for v1.2.0
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
This document specifies two complementary features for Weevil:
|
||||||
|
|
||||||
|
1. **Template System (v1.1.0)** - ✅ **IMPLEMENTED** - Project scaffolding with professional code templates
|
||||||
|
2. **`weevil add` Package System (v1.2.0)** - 📋 **PLANNED** - Component package management
|
||||||
|
|
||||||
|
Together, these enable teams to start with professional code and extend projects with community-shared components.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 1: Template System ✅ IMPLEMENTED in v1.1.0
|
||||||
|
|
||||||
|
### Status: COMPLETE
|
||||||
|
|
||||||
|
The template system has been fully implemented and shipped in v1.1.0.
|
||||||
|
|
||||||
|
### Implementation Summary
|
||||||
|
|
||||||
|
**Command Syntax:**
|
||||||
|
```bash
|
||||||
|
weevil new <project-name> [--template <name>] [--list-templates]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Delivered Templates:**
|
||||||
|
|
||||||
|
1. **`basic`** (default) - Minimal FTC project
|
||||||
|
- 8 files, ~50 lines of code
|
||||||
|
- Clean starting point
|
||||||
|
- Example OpMode placeholder
|
||||||
|
|
||||||
|
2. **`testing`** - Professional showcase
|
||||||
|
- 28 files, ~2,500 lines of code
|
||||||
|
- 45 comprehensive tests (< 2 sec runtime)
|
||||||
|
- 3 complete subsystems
|
||||||
|
- Hardware abstraction layer
|
||||||
|
- Full documentation
|
||||||
|
|
||||||
|
**Key Features Delivered:**
|
||||||
|
- ✅ Template extraction and overlay system
|
||||||
|
- ✅ Variable substitution (`{{PROJECT_NAME}}`, etc.)
|
||||||
|
- ✅ Template validation with helpful errors
|
||||||
|
- ✅ `--list-templates` command
|
||||||
|
- ✅ Templates embedded in binary (no external files)
|
||||||
|
- ✅ Complete test coverage (62 tests passing)
|
||||||
|
|
||||||
|
### Template Variable Substitution
|
||||||
|
|
||||||
|
Implemented variables:
|
||||||
|
|
||||||
|
| Variable | Example Value |
|
||||||
|
|----------|---------------|
|
||||||
|
| `{{PROJECT_NAME}}` | `my-robot` |
|
||||||
|
| `{{PACKAGE_NAME}}` | `myrobot` |
|
||||||
|
| `{{CREATION_DATE}}` | `2026-02-02T10:30:00Z` |
|
||||||
|
| `{{WEEVIL_VERSION}}` | `1.1.0` |
|
||||||
|
| `{{TEMPLATE_NAME}}` | `testing` |
|
||||||
|
|
||||||
|
### Testing Template Contents
|
||||||
|
|
||||||
|
**Subsystems** (3):
|
||||||
|
- `MotorCycler.java` - State machine for motor cycling
|
||||||
|
- `WallApproach.java` - Sensor-based navigation
|
||||||
|
- `TurnController.java` - Gyro-based turning
|
||||||
|
|
||||||
|
**Hardware Layer** (12 files):
|
||||||
|
- 3 interfaces (MotorController, DistanceSensor, GyroSensor)
|
||||||
|
- 3 FTC implementations
|
||||||
|
- 3 mock implementations
|
||||||
|
- 3 additional interfaces
|
||||||
|
|
||||||
|
**Tests** (45 tests):
|
||||||
|
- Unit tests for each subsystem
|
||||||
|
- Integration tests
|
||||||
|
- All passing in < 2 seconds
|
||||||
|
|
||||||
|
**Documentation** (6 files):
|
||||||
|
- DESIGN_AND_TEST_PLAN.md (29 KB)
|
||||||
|
- TESTING_GUIDE.md (13 KB)
|
||||||
|
- TESTING_SHOWCASE.md (9 KB)
|
||||||
|
- ARCHITECTURE.md (6 KB)
|
||||||
|
- SOLUTION.md (3 KB)
|
||||||
|
- QUICKSTART.md (5 KB)
|
||||||
|
|
||||||
|
### Usage Examples
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create with default template
|
||||||
|
weevil new my-robot
|
||||||
|
|
||||||
|
# Create with testing template
|
||||||
|
weevil new my-robot --template testing
|
||||||
|
|
||||||
|
# List available templates
|
||||||
|
weevil new --list-templates
|
||||||
|
|
||||||
|
# Output from list:
|
||||||
|
# Available templates:
|
||||||
|
#
|
||||||
|
# basic (default)
|
||||||
|
# Minimal FTC project structure
|
||||||
|
# Perfect for: Teams starting from scratch
|
||||||
|
# Files: ~10 | Code: ~50 lines
|
||||||
|
#
|
||||||
|
# testing
|
||||||
|
# Professional testing showcase with examples
|
||||||
|
# Perfect for: Learning best practices
|
||||||
|
# Files: ~30 | Code: ~2,500 lines | Tests: 45
|
||||||
|
# Includes:
|
||||||
|
# • 3 complete subsystems
|
||||||
|
# • Hardware abstraction layer with mocks
|
||||||
|
# • 45 passing tests (< 2 seconds)
|
||||||
|
# • Comprehensive documentation
|
||||||
|
```
|
||||||
|
|
||||||
|
### Implementation Architecture
|
||||||
|
|
||||||
|
**Storage:** Templates embedded in binary using `include_dir!` macro
|
||||||
|
|
||||||
|
**Directory Structure:**
|
||||||
|
```
|
||||||
|
weevil/
|
||||||
|
├── templates/
|
||||||
|
│ ├── basic/
|
||||||
|
│ │ ├── .gitignore
|
||||||
|
│ │ ├── README.md.template
|
||||||
|
│ │ ├── settings.gradle
|
||||||
|
│ │ └── src/... (.gitkeep files)
|
||||||
|
│ └── testing/
|
||||||
|
│ ├── .gitignore
|
||||||
|
│ ├── README.md.template
|
||||||
|
│ ├── DESIGN_AND_TEST_PLAN.md
|
||||||
|
│ ├── ... (6 doc files)
|
||||||
|
│ └── src/
|
||||||
|
│ ├── main/java/robot/
|
||||||
|
│ │ ├── hardware/... (6 files)
|
||||||
|
│ │ ├── subsystems/... (3 files)
|
||||||
|
│ │ └── opmodes/...
|
||||||
|
│ └── test/java/robot/
|
||||||
|
│ ├── hardware/... (3 files)
|
||||||
|
│ └── subsystems/... (4 files)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Implementation Details:**
|
||||||
|
- Templates complement ProjectBuilder (don't replace it)
|
||||||
|
- ProjectBuilder creates infrastructure (.weevil.toml, build.gradle.kts, etc.)
|
||||||
|
- Templates overlay content (source code, docs)
|
||||||
|
- Files ending in `.template` get variable substitution
|
||||||
|
- Regular files copied as-is
|
||||||
|
|
||||||
|
### Success Metrics (Achieved)
|
||||||
|
|
||||||
|
- ✅ 62 tests passing (zero warnings)
|
||||||
|
- ✅ Testing template has 45 passing tests
|
||||||
|
- ✅ Clean separation: ProjectBuilder vs Templates
|
||||||
|
- ✅ Cross-platform compatibility (Windows, Linux, macOS)
|
||||||
|
- ✅ No template fragmentation (templates don't include build files)
|
||||||
|
- ✅ Professional code quality in testing template
|
||||||
|
- ✅ Comprehensive documentation
|
||||||
|
|
||||||
|
### Lessons Learned
|
||||||
|
|
||||||
|
1. **Don't fight ProjectBuilder** - Templates should complement, not replace infrastructure
|
||||||
|
2. **Embed in binary** - No external file dependencies
|
||||||
|
3. **Variable substitution** - Essential for project-specific values
|
||||||
|
4. **Test thoroughly** - Template extraction, variable substitution, file handling all need tests
|
||||||
|
5. **Documentation matters** - The testing template's value is in its docs as much as code
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Part 2: `weevil add` Command - Package Management System
|
||||||
|
|
||||||
|
### Status: PLANNED for v1.2.0
|
||||||
|
|
||||||
|
The package management system will allow teams to add pre-built components to existing projects.
|
||||||
|
|
||||||
|
### Overview
|
||||||
|
|
||||||
|
**Purpose:** Add components to existing Weevil projects
|
||||||
|
|
||||||
|
**Version:** v1.2.0
|
||||||
|
**Priority:** HIGH
|
||||||
|
**Estimated Effort:** 2-3 weeks
|
||||||
|
|
||||||
|
### Command Syntax
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil add <package> [OPTIONS]
|
||||||
|
|
||||||
|
OPTIONS:
|
||||||
|
--force Overwrite conflicting files
|
||||||
|
--merge Attempt to merge conflicts (experimental)
|
||||||
|
--interactive Prompt for each conflict
|
||||||
|
--dry-run Preview without adding
|
||||||
|
--no-deps Don't install dependencies
|
||||||
|
--dev Add as dev dependency
|
||||||
|
```
|
||||||
|
|
||||||
|
### Package Naming
|
||||||
|
|
||||||
|
Hierarchical structure: `scope/category/name/variant`
|
||||||
|
|
||||||
|
**Examples:**
|
||||||
|
```
|
||||||
|
nexus/hardware/dc-motor/core
|
||||||
|
nexus/hardware/dc-motor/mock
|
||||||
|
nexus/hardware/dc-motor/example
|
||||||
|
nexus/hardware/dc-motor/complete
|
||||||
|
|
||||||
|
nexus/subsystems/wall-approach/complete
|
||||||
|
nexus/examples/autonomous/simple-auto
|
||||||
|
|
||||||
|
team1234/sensors/custom-lidar/core
|
||||||
|
```
|
||||||
|
|
||||||
|
**Components:**
|
||||||
|
- **scope**: Publisher (nexus, team1234, etc.)
|
||||||
|
- **category**: Type (hardware, subsystems, examples, testing)
|
||||||
|
- **name**: Component name (dc-motor, wall-approach)
|
||||||
|
- **variant**: Implementation (core, mock, example, complete)
|
||||||
|
|
||||||
|
### Standard Variants
|
||||||
|
|
||||||
|
| Variant | Contents | Dependencies |
|
||||||
|
|---------|----------|--------------|
|
||||||
|
| `core` | Interface + FTC wrapper | None |
|
||||||
|
| `mock` | Test double | Requires core |
|
||||||
|
| `example` | Example OpMode | Requires core |
|
||||||
|
| `complete` | All of above | Includes all variants |
|
||||||
|
|
||||||
|
### Usage Examples
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Add complete package
|
||||||
|
weevil add nexus/hardware/dc-motor/complete
|
||||||
|
|
||||||
|
# Add specific variant
|
||||||
|
weevil add nexus/hardware/dc-motor/core
|
||||||
|
weevil add nexus/hardware/dc-motor/mock --dev
|
||||||
|
|
||||||
|
# Add subsystem (auto-installs dependencies)
|
||||||
|
weevil add nexus/subsystems/wall-approach/complete
|
||||||
|
|
||||||
|
# Preview
|
||||||
|
weevil add nexus/hardware/servo/core --dry-run
|
||||||
|
|
||||||
|
# Force overwrite
|
||||||
|
weevil add nexus/hardware/gyro/complete --force
|
||||||
|
|
||||||
|
# Interactive resolution
|
||||||
|
weevil add nexus/subsystems/turn-controller/core --interactive
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dependency Resolution
|
||||||
|
|
||||||
|
Packages declare dependencies in manifest:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[package]
|
||||||
|
name = "wall-approach"
|
||||||
|
scope = "nexus"
|
||||||
|
category = "subsystems"
|
||||||
|
version = "1.0.0"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
"nexus/hardware/distance/core" = "^2.0.0"
|
||||||
|
"nexus/hardware/dc-motor/core" = "^1.0.0"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
"nexus/testing/mock-base" = "^1.0.0"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Automatic Resolution:**
|
||||||
|
```bash
|
||||||
|
$ weevil add nexus/subsystems/wall-approach/complete
|
||||||
|
|
||||||
|
Resolving dependencies...
|
||||||
|
|
||||||
|
Installing:
|
||||||
|
1. nexus/hardware/distance/core (v2.1.0) - dependency
|
||||||
|
2. nexus/hardware/dc-motor/core (v1.2.0) - dependency
|
||||||
|
3. nexus/subsystems/wall-approach/complete (v1.0.0)
|
||||||
|
|
||||||
|
✓ Added 3 packages (15 files)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Conflict Handling
|
||||||
|
|
||||||
|
#### Default (Skip)
|
||||||
|
|
||||||
|
```
|
||||||
|
⚠ File conflicts detected:
|
||||||
|
src/main/java/robot/hardware/MotorController.java (exists)
|
||||||
|
|
||||||
|
Resolution: Skipping conflicting files
|
||||||
|
|
||||||
|
Added:
|
||||||
|
✓ src/main/java/robot/hardware/FtcMotorController.java
|
||||||
|
|
||||||
|
Skipped:
|
||||||
|
⊗ MotorController.java (already exists)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Force Mode
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ weevil add nexus/hardware/dc-motor/core --force
|
||||||
|
|
||||||
|
⚠ Warning: --force will overwrite 2 files
|
||||||
|
Continue? [y/N]: y
|
||||||
|
|
||||||
|
✓ Overwrote 2 files, added 3 files
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Interactive Mode
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ weevil add nexus/hardware/dc-motor/core --interactive
|
||||||
|
|
||||||
|
Conflict: MotorController.java
|
||||||
|
|
||||||
|
Options:
|
||||||
|
[s] Skip (keep your file)
|
||||||
|
[o] Overwrite (use package file)
|
||||||
|
[d] Show diff
|
||||||
|
[a] Abort
|
||||||
|
|
||||||
|
Choice [s]: d
|
||||||
|
|
||||||
|
Diff:
|
||||||
|
--- Existing
|
||||||
|
+++ Package
|
||||||
|
@@ -5,3 +5,5 @@
|
||||||
|
public interface MotorController {
|
||||||
|
void setPower(double power);
|
||||||
|
double getPower();
|
||||||
|
+ void setMode(RunMode mode);
|
||||||
|
+ RunMode getMode();
|
||||||
|
}
|
||||||
|
|
||||||
|
Choice [s]:
|
||||||
|
```
|
||||||
|
|
||||||
|
### Package Categories
|
||||||
|
|
||||||
|
#### `hardware/*`
|
||||||
|
Physical hardware abstractions
|
||||||
|
|
||||||
|
**Subcategories:**
|
||||||
|
- `hardware/motors/*` - Motor controllers
|
||||||
|
- `hardware/sensors/*` - Sensor interfaces
|
||||||
|
- `hardware/servos/*` - Servo controllers
|
||||||
|
- `hardware/vision/*` - Camera systems
|
||||||
|
- `hardware/imu/*` - Gyroscopes
|
||||||
|
|
||||||
|
**Standard Variants:** core, mock, example, complete
|
||||||
|
|
||||||
|
#### `subsystems/*`
|
||||||
|
Robot subsystems built on hardware
|
||||||
|
|
||||||
|
**Examples:**
|
||||||
|
- `subsystems/drivetrain/*`
|
||||||
|
- `subsystems/arm/*`
|
||||||
|
- `subsystems/intake/*`
|
||||||
|
|
||||||
|
**Standard Variants:** core, mock, example, complete
|
||||||
|
|
||||||
|
#### `examples/*`
|
||||||
|
Complete working examples
|
||||||
|
|
||||||
|
**Subcategories:**
|
||||||
|
- `examples/autonomous/*`
|
||||||
|
- `examples/teleop/*`
|
||||||
|
- `examples/vision/*`
|
||||||
|
|
||||||
|
**Variants:** Usually standalone (no variants)
|
||||||
|
|
||||||
|
#### `testing/*`
|
||||||
|
Testing utilities and patterns
|
||||||
|
|
||||||
|
**Examples:**
|
||||||
|
- `testing/mock-hardware` - Mock collection
|
||||||
|
- `testing/test-patterns` - Reusable patterns
|
||||||
|
- `testing/assertions` - Custom assertions
|
||||||
|
|
||||||
|
#### `utilities/*`
|
||||||
|
Helper utilities
|
||||||
|
|
||||||
|
**Examples:**
|
||||||
|
- `utilities/math/*`
|
||||||
|
- `utilities/telemetry/*`
|
||||||
|
- `utilities/logging/*`
|
||||||
|
|
||||||
|
### Package Manifest
|
||||||
|
|
||||||
|
**Example (`package.toml`):**
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[package]
|
||||||
|
name = "dc-motor"
|
||||||
|
scope = "nexus"
|
||||||
|
category = "hardware"
|
||||||
|
version = "1.2.0"
|
||||||
|
description = "DC motor controller interface and FTC implementation"
|
||||||
|
license = "MIT"
|
||||||
|
authors = ["Nexus Workshops <info@nxgit.dev>"]
|
||||||
|
|
||||||
|
[variants]
|
||||||
|
available = ["core", "mock", "example", "complete"]
|
||||||
|
default = "complete"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# Empty for base hardware
|
||||||
|
|
||||||
|
[files.core]
|
||||||
|
include = [
|
||||||
|
"src/main/java/robot/hardware/MotorController.java",
|
||||||
|
"src/main/java/robot/hardware/FtcMotorController.java"
|
||||||
|
]
|
||||||
|
|
||||||
|
[files.mock]
|
||||||
|
include = ["src/test/java/robot/hardware/MockMotorController.java"]
|
||||||
|
dependencies = ["core"]
|
||||||
|
|
||||||
|
[files.example]
|
||||||
|
include = ["src/main/java/robot/opmodes/examples/MotorExample.java"]
|
||||||
|
dependencies = ["core"]
|
||||||
|
|
||||||
|
[files.complete]
|
||||||
|
dependencies = ["core", "mock", "example"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Package Repository
|
||||||
|
|
||||||
|
**Location:** https://packages.nxgit.dev (to be implemented)
|
||||||
|
|
||||||
|
**Structure:**
|
||||||
|
```
|
||||||
|
packages.nxgit.dev/
|
||||||
|
├── index.json
|
||||||
|
├── nexus/
|
||||||
|
│ ├── hardware/
|
||||||
|
│ │ ├── dc-motor/
|
||||||
|
│ │ │ ├── package.toml
|
||||||
|
│ │ │ ├── core.tar.gz
|
||||||
|
│ │ │ ├── mock.tar.gz
|
||||||
|
│ │ │ └── complete.tar.gz
|
||||||
|
│ │ └── distance/...
|
||||||
|
│ └── subsystems/...
|
||||||
|
└── team1234/...
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Supporting Commands (v1.2.0)
|
||||||
|
|
||||||
|
### `weevil remove`
|
||||||
|
|
||||||
|
Remove installed package
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil remove <package> [--prune] [--force]
|
||||||
|
```
|
||||||
|
|
||||||
|
### `weevil search`
|
||||||
|
|
||||||
|
Search package registry
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil search <query>
|
||||||
|
|
||||||
|
Output:
|
||||||
|
nexus/hardware/mecanum-drive/complete
|
||||||
|
Mecanum drive system with holonomic control
|
||||||
|
★★★★★ (342 downloads)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `weevil list`
|
||||||
|
|
||||||
|
List packages
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil list --installed # Show installed
|
||||||
|
weevil list --available # Show all available
|
||||||
|
```
|
||||||
|
|
||||||
|
### `weevil info`
|
||||||
|
|
||||||
|
Show package details
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil info nexus/hardware/dc-motor/complete
|
||||||
|
|
||||||
|
Package: nexus/hardware/dc-motor/complete
|
||||||
|
Version: 1.2.0
|
||||||
|
Downloads: 1,523
|
||||||
|
License: MIT
|
||||||
|
|
||||||
|
Description:
|
||||||
|
DC motor controller with interface, FTC implementation,
|
||||||
|
test mocks, and examples.
|
||||||
|
```
|
||||||
|
|
||||||
|
### `weevil update`
|
||||||
|
|
||||||
|
Update packages to latest versions
|
||||||
|
|
||||||
|
```bash
|
||||||
|
weevil update # Update all
|
||||||
|
weevil update <package> # Update specific
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implementation Roadmap
|
||||||
|
|
||||||
|
### Phase 1: v1.1.0 ✅ COMPLETE
|
||||||
|
|
||||||
|
**Template System:**
|
||||||
|
- [x] Template storage system (embedded in binary)
|
||||||
|
- [x] Variable substitution engine
|
||||||
|
- [x] Basic template (minimal project)
|
||||||
|
- [x] Testing template (professional showcase)
|
||||||
|
- [x] `--list-templates` command
|
||||||
|
- [x] Template validation
|
||||||
|
- [x] Success/error messages
|
||||||
|
- [x] Documentation (README, DESIGN_AND_TEST_PLAN, etc.)
|
||||||
|
- [x] Comprehensive tests (62 tests passing)
|
||||||
|
- [x] Cross-platform support
|
||||||
|
|
||||||
|
**Delivered:**
|
||||||
|
- Template system fully functional
|
||||||
|
- Two high-quality templates
|
||||||
|
- Professional documentation
|
||||||
|
- 100% test coverage
|
||||||
|
- Zero warnings in `cargo test`
|
||||||
|
|
||||||
|
### Phase 2: v1.2.0 📋 PLANNED (2-3 weeks)
|
||||||
|
|
||||||
|
**`weevil add` Package System:**
|
||||||
|
- [ ] Package registry infrastructure
|
||||||
|
- [ ] Package manifest format (`package.toml`)
|
||||||
|
- [ ] Dependency resolver (semver)
|
||||||
|
- [ ] Conflict detection and resolution
|
||||||
|
- [ ] File installation system
|
||||||
|
- [ ] `weevil remove` command
|
||||||
|
- [ ] `weevil search` command
|
||||||
|
- [ ] `weevil list` command
|
||||||
|
- [ ] `weevil info` command
|
||||||
|
- [ ] `weevil update` command
|
||||||
|
- [ ] 10+ launch packages
|
||||||
|
- [ ] Documentation
|
||||||
|
- [ ] Comprehensive tests
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Initial Package Set (v1.2.0 Launch)
|
||||||
|
|
||||||
|
**Must Have (10 packages):**
|
||||||
|
|
||||||
|
1. nexus/hardware/dc-motor/complete
|
||||||
|
2. nexus/hardware/servo/complete
|
||||||
|
3. nexus/hardware/distance/complete
|
||||||
|
4. nexus/hardware/imu/complete
|
||||||
|
5. nexus/hardware/color-sensor/complete
|
||||||
|
6. nexus/subsystems/wall-approach/complete
|
||||||
|
7. nexus/subsystems/turn-controller/complete
|
||||||
|
8. nexus/testing/mock-hardware
|
||||||
|
9. nexus/examples/autonomous/simple-auto
|
||||||
|
10. nexus/examples/teleop/basic-drive
|
||||||
|
|
||||||
|
**Nice to Have (+5):**
|
||||||
|
|
||||||
|
11. nexus/hardware/mecanum-drive/complete
|
||||||
|
12. nexus/subsystems/april-tag/complete
|
||||||
|
13. nexus/examples/autonomous/complex-auto
|
||||||
|
14. nexus/utilities/telemetry/dashboard
|
||||||
|
15. nexus/testing/test-patterns
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Strategic Benefits
|
||||||
|
|
||||||
|
### For Teams
|
||||||
|
- **Faster start** - Working code from day one (via templates)
|
||||||
|
- **Code reuse** - Don't reinvent wheels (via packages)
|
||||||
|
- **Best practices** - Learn from examples
|
||||||
|
- **Community** - Share solutions
|
||||||
|
|
||||||
|
### For Nexus Workshops
|
||||||
|
- **Authority** - Set FTC code standards
|
||||||
|
- **Network effects** - More packages = more value
|
||||||
|
- **Revenue** - Workshops teach patterns
|
||||||
|
- **Differentiation** - Unique offering
|
||||||
|
|
||||||
|
### For FTC Community
|
||||||
|
- **Quality** - Raised bar across teams
|
||||||
|
- **Collaboration** - Build on each other
|
||||||
|
- **Education** - Professional patterns
|
||||||
|
- **Innovation** - Focus on unique solutions
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Success Metrics
|
||||||
|
|
||||||
|
### v1.1.0 (Templates) ✅ ACHIEVED
|
||||||
|
- [x] Template system implemented
|
||||||
|
- [x] Testing template includes 45 passing tests
|
||||||
|
- [x] Professional documentation delivered
|
||||||
|
- [x] 62 tests passing, zero warnings
|
||||||
|
- [x] Cross-platform support
|
||||||
|
- [ ] 50+ teams use testing template (tracking in progress)
|
||||||
|
- [ ] Used in Nexus Workshops curriculum (planned)
|
||||||
|
|
||||||
|
### v1.2.0 (Packages) 📋 PLANNED
|
||||||
|
- [ ] 20+ quality packages at launch
|
||||||
|
- [ ] 100+ downloads first month
|
||||||
|
- [ ] 5+ community packages
|
||||||
|
- [ ] Active ecosystem
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Package Quality Standards (v1.2.0)
|
||||||
|
|
||||||
|
**Required (All Packages):**
|
||||||
|
- ✅ Valid package.toml
|
||||||
|
- ✅ License specified
|
||||||
|
- ✅ README included
|
||||||
|
- ✅ Compiles without errors
|
||||||
|
|
||||||
|
**Recommended (Verified Badge):**
|
||||||
|
- ✅ Tests included
|
||||||
|
- ✅ Comprehensive docs
|
||||||
|
- ✅ Interface-based design
|
||||||
|
- ✅ No hardcoded values
|
||||||
|
- ✅ Follows naming conventions
|
||||||
|
|
||||||
|
**Nexus Verified:**
|
||||||
|
- All required + recommended
|
||||||
|
- Professional code quality
|
||||||
|
- Full test coverage
|
||||||
|
- Maintained and supported
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Open Questions (v1.2.0)
|
||||||
|
|
||||||
|
1. **Versioning:** How handle breaking changes? (Semver with pre-release tags)
|
||||||
|
2. **Testing:** Require tests in packages? (Recommended, not required)
|
||||||
|
3. **Licensing:** Enforce compliance? (Check but don't block)
|
||||||
|
4. **Moderation:** Who approves packages? (Automated checks + manual review for Nexus Verified)
|
||||||
|
5. **Private packages:** Support team-private? (v1.3.0 feature)
|
||||||
|
6. **Namespaces:** Use team numbers? (Optional, teams can use team1234 as scope)
|
||||||
|
7. **Binary support:** Allow compiled code? (No, source only)
|
||||||
|
8. **Update notifications:** Alert on updates? (Yes, via `weevil list --upgradable`)
|
||||||
|
9. **Code signing:** Security/trust model? (GPG signatures for Nexus Verified, optional for community)
|
||||||
|
10. **Monorepo:** Where store packages? (Separate repo: weevil-packages)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Future Enhancements
|
||||||
|
|
||||||
|
### v1.3.0+
|
||||||
|
- Package signing (GPG)
|
||||||
|
- Private registries
|
||||||
|
- `weevil publish` command
|
||||||
|
- Package mirrors
|
||||||
|
- Offline mode
|
||||||
|
- Additional templates (mecanum, vision, etc.)
|
||||||
|
|
||||||
|
### v2.0.0+
|
||||||
|
- Binary packages
|
||||||
|
- Pre-built libraries
|
||||||
|
- Cloud builds
|
||||||
|
- Team collaboration features
|
||||||
|
- VS Code integration
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- **npm** - Node package manager (scopes, registry)
|
||||||
|
- **Cargo** - Rust package manager (semver, crates.io)
|
||||||
|
- **FreeBSD Ports** - Package system inspiration
|
||||||
|
- **Maven Central** - Java repository patterns
|
||||||
|
- **Homebrew** - macOS package management
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Appendix: Comparison Matrix
|
||||||
|
|
||||||
|
| Feature | Templates (v1.1.0) | Packages (v1.2.0) |
|
||||||
|
|---------|-------------------|-------------------|
|
||||||
|
| **Purpose** | Start projects | Extend projects |
|
||||||
|
| **When** | Project creation | After creation |
|
||||||
|
| **Size** | Large (complete projects) | Small (components) |
|
||||||
|
| **Conflicts** | None (new project) | Possible (merging) |
|
||||||
|
| **Dependencies** | None | Yes (dependency tree) |
|
||||||
|
| **Variants** | 2 templates | Many per package |
|
||||||
|
| **Customization** | Fork template | Use as-is or modify |
|
||||||
|
| **Updates** | Manual (copy pattern) | `weevil update` |
|
||||||
|
| **Status** | ✅ Shipped | 📋 Planned |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*End of Specification*
|
||||||
|
|
||||||
|
**Status:**
|
||||||
|
- ✅ Part 1 (Templates): COMPLETE in v1.1.0
|
||||||
|
- 📋 Part 2 (Packages): PLANNED for v1.2.0
|
||||||
|
|
||||||
|
**Next Steps:**
|
||||||
|
1. ✅ Ship v1.1.0 with template system
|
||||||
|
2. Gather feedback on testing template
|
||||||
|
3. Begin v1.2.0 package system development
|
||||||
|
4. Create initial package set
|
||||||
|
|
||||||
|
**Contact:** eric@intrepidfusion.com
|
||||||
|
**Organization:** Nexus Workshops LLC
|
||||||
@@ -1,26 +1,74 @@
|
|||||||
use anyhow::{Result, bail};
|
use anyhow::{Result, bail};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use colored::*;
|
use colored::*;
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
use crate::sdk::SdkConfig;
|
use crate::sdk::SdkConfig;
|
||||||
use crate::sdk::proxy::ProxyConfig;
|
use crate::sdk::proxy::ProxyConfig;
|
||||||
use crate::project::ProjectBuilder;
|
use crate::project::ProjectBuilder;
|
||||||
|
use crate::templates::{TemplateManager, TemplateContext};
|
||||||
|
|
||||||
|
// Use Cargo's version macro
|
||||||
|
const WEEVIL_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
|
|
||||||
|
pub fn list_templates() -> Result<()> {
|
||||||
|
println!("{}", "Available templates:".bright_cyan().bold());
|
||||||
|
println!();
|
||||||
|
|
||||||
|
println!("{}", " basic (default)".bright_white().bold());
|
||||||
|
println!(" Minimal FTC project structure");
|
||||||
|
println!(" Perfect for: Teams starting from scratch");
|
||||||
|
println!(" Files: ~10 | Code: ~50 lines");
|
||||||
|
println!();
|
||||||
|
|
||||||
|
println!("{}", " testing".bright_white().bold());
|
||||||
|
println!(" Professional testing showcase with examples");
|
||||||
|
println!(" Perfect for: Learning best practices");
|
||||||
|
println!(" Files: ~30 | Code: ~2,500 lines | Tests: 45");
|
||||||
|
println!(" Includes:");
|
||||||
|
println!(" • 3 complete subsystems (MotorCycler, WallApproach, TurnController)");
|
||||||
|
println!(" • Hardware abstraction layer with mocks");
|
||||||
|
println!(" • 45 passing tests (< 2 seconds)");
|
||||||
|
println!(" • Comprehensive documentation");
|
||||||
|
println!();
|
||||||
|
|
||||||
|
println!("{}", "Usage:".bright_yellow().bold());
|
||||||
|
println!(" weevil new <project-name> # Uses basic template");
|
||||||
|
println!(" weevil new <project-name> --template testing # Uses testing template");
|
||||||
|
println!();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn create_project(
|
pub fn create_project(
|
||||||
name: &str,
|
name: &str,
|
||||||
ftc_sdk: Option<&str>,
|
ftc_sdk: Option<&str>,
|
||||||
android_sdk: Option<&str>,
|
android_sdk: Option<&str>,
|
||||||
|
template: Option<&str>,
|
||||||
_proxy: &ProxyConfig,
|
_proxy: &ProxyConfig,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
// _proxy is threaded through here so future flows (e.g. auto-install on
|
// _proxy is threaded through here so future flows (e.g. auto-install on
|
||||||
// missing SDK) can use it without changing the call site in main.
|
// missing SDK) can use it without changing the call site in main.
|
||||||
|
|
||||||
// Validate project name
|
// Validate project name
|
||||||
if name.is_empty() {
|
if name.is_empty() {
|
||||||
bail!("Project name cannot be empty");
|
bail!("Project name cannot be empty");
|
||||||
}
|
}
|
||||||
|
|
||||||
if !name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
|
if name.len() > 50 {
|
||||||
bail!("Project name must contain only alphanumeric characters, hyphens, and underscores");
|
bail!("Project name must be 50 characters or less");
|
||||||
|
}
|
||||||
|
|
||||||
|
let valid = name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_');
|
||||||
|
if !valid {
|
||||||
|
bail!(
|
||||||
|
"Invalid project name '{}'\nProject names must:\n - Contain only letters, numbers, hyphens, underscores\n - Start with a letter\n - Be 1-50 characters long\n\nValid examples:\n my-robot\n team1234_robot\n competitionBot2024",
|
||||||
|
name
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !name.chars().next().unwrap().is_alphabetic() {
|
||||||
|
bail!("Project name must start with a letter");
|
||||||
}
|
}
|
||||||
|
|
||||||
let project_path = PathBuf::from(name);
|
let project_path = PathBuf::from(name);
|
||||||
@@ -35,7 +83,26 @@ pub fn create_project(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let template_name = template.unwrap_or("basic");
|
||||||
|
|
||||||
|
// Verify template exists BEFORE starting project creation
|
||||||
|
let template_mgr = TemplateManager::new()?;
|
||||||
|
if !template_mgr.template_exists(template_name) {
|
||||||
|
println!("{}", format!("✗ Template '{}' not found", template_name).red().bold());
|
||||||
|
println!();
|
||||||
|
println!("{}", "Available templates:".bright_yellow());
|
||||||
|
for tmpl in template_mgr.list_templates() {
|
||||||
|
println!("{}", tmpl);
|
||||||
|
}
|
||||||
|
println!();
|
||||||
|
println!("{}", "To see details:".bright_yellow());
|
||||||
|
println!(" weevil new --list-templates");
|
||||||
|
println!();
|
||||||
|
bail!("Invalid template");
|
||||||
|
}
|
||||||
|
|
||||||
println!("{}", format!("Creating FTC project: {}", name).bright_green().bold());
|
println!("{}", format!("Creating FTC project: {}", name).bright_green().bold());
|
||||||
|
println!("{}", format!("Template: {}", template_name).bright_cyan());
|
||||||
println!();
|
println!();
|
||||||
|
|
||||||
// Check system health FIRST
|
// Check system health FIRST
|
||||||
@@ -81,10 +148,33 @@ pub fn create_project(
|
|||||||
|
|
||||||
println!("{}", "Creating project structure...".bright_yellow());
|
println!("{}", "Creating project structure...".bright_yellow());
|
||||||
|
|
||||||
// Build the project
|
// Build the project using existing ProjectBuilder
|
||||||
let builder = ProjectBuilder::new(name, &sdk_config)?;
|
let builder = ProjectBuilder::new(name, &sdk_config)?;
|
||||||
builder.create(&project_path, &sdk_config)?;
|
builder.create(&project_path, &sdk_config)?;
|
||||||
|
|
||||||
|
// Apply template overlay
|
||||||
|
println!("{}", format!("Applying '{}' template...", template_name).bright_yellow());
|
||||||
|
|
||||||
|
let context = TemplateContext {
|
||||||
|
project_name: name.to_string(),
|
||||||
|
package_name: name.to_lowercase().replace("-", "").replace("_", ""),
|
||||||
|
creation_date: Utc::now().to_rfc3339(),
|
||||||
|
weevil_version: WEEVIL_VERSION.to_string(),
|
||||||
|
template_name: template_name.to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let files_added = template_mgr.extract_template(template_name, &project_path, &context)?;
|
||||||
|
|
||||||
|
if files_added > 0 {
|
||||||
|
println!("{} Added {} template files", "✓".green(), files_added);
|
||||||
|
} else {
|
||||||
|
println!("{}", "⚠ Warning: No template files were added".yellow());
|
||||||
|
println!(" Check that templates/{} directory exists and contains files", template_name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize git repository
|
||||||
|
init_git_repository(&project_path, template_name)?;
|
||||||
|
|
||||||
println!();
|
println!();
|
||||||
println!("{}", "═══════════════════════════════════════════════════════════".bright_green());
|
println!("{}", "═══════════════════════════════════════════════════════════".bright_green());
|
||||||
println!("{}", format!(" ✓ Project Created: {}", name).bright_green().bold());
|
println!("{}", format!(" ✓ Project Created: {}", name).bright_green().bold());
|
||||||
@@ -92,14 +182,82 @@ pub fn create_project(
|
|||||||
println!();
|
println!();
|
||||||
println!("FTC SDK: {}", sdk_config.ftc_sdk_path.display());
|
println!("FTC SDK: {}", sdk_config.ftc_sdk_path.display());
|
||||||
println!("Version: {}", crate::sdk::ftc::get_version(&sdk_config.ftc_sdk_path).unwrap_or_else(|_| "unknown".to_string()));
|
println!("Version: {}", crate::sdk::ftc::get_version(&sdk_config.ftc_sdk_path).unwrap_or_else(|_| "unknown".to_string()));
|
||||||
|
println!("Template: {}", template_name);
|
||||||
|
if files_added > 0 {
|
||||||
|
println!("Files added from template: {}", files_added);
|
||||||
|
}
|
||||||
println!();
|
println!();
|
||||||
println!("{}", "Next steps:".bright_yellow().bold());
|
|
||||||
println!(" 1. {}", format!("cd {}", name).bright_cyan());
|
print_next_steps(name, template_name);
|
||||||
println!(" 2. Review README.md for project structure");
|
|
||||||
println!(" 3. Start coding in src/main/java/robot/");
|
|
||||||
println!(" 4. Run tests: {}", "./gradlew test".bright_cyan());
|
|
||||||
println!(" 5. Deploy to robot: {}", format!("weevil deploy {}", name).bright_cyan());
|
|
||||||
println!();
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn init_git_repository(project_dir: &std::path::Path, template_name: &str) -> Result<()> {
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
// Check if git is available
|
||||||
|
let git_check = Command::new("git")
|
||||||
|
.arg("--version")
|
||||||
|
.output();
|
||||||
|
|
||||||
|
if git_check.is_err() {
|
||||||
|
println!("{}", "⚠ Git not found, skipping repository initialization".yellow());
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize repository
|
||||||
|
let status = Command::new("git")
|
||||||
|
.arg("init")
|
||||||
|
.current_dir(project_dir)
|
||||||
|
.output()?;
|
||||||
|
|
||||||
|
if !status.status.success() {
|
||||||
|
println!("{}", "⚠ Failed to initialize git repository".yellow());
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create initial commit
|
||||||
|
Command::new("git")
|
||||||
|
.args(&["add", "."])
|
||||||
|
.current_dir(project_dir)
|
||||||
|
.output()
|
||||||
|
.ok();
|
||||||
|
|
||||||
|
let commit_message = format!("Initial commit from weevil new --template {}", template_name);
|
||||||
|
Command::new("git")
|
||||||
|
.args(&["commit", "-m", &commit_message])
|
||||||
|
.current_dir(project_dir)
|
||||||
|
.output()
|
||||||
|
.ok();
|
||||||
|
|
||||||
|
println!("{} Initialized Git repository", "✓".green());
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_next_steps(project_name: &str, template_name: &str) {
|
||||||
|
println!("{}", "Next steps:".bright_yellow().bold());
|
||||||
|
println!(" 1. {}", format!("cd {}", project_name).bright_cyan());
|
||||||
|
|
||||||
|
match template_name {
|
||||||
|
"testing" => {
|
||||||
|
println!(" 2. Run tests: {}", "./gradlew test".bright_cyan());
|
||||||
|
println!(" {} 45 tests will pass in < 2 seconds", "✓".green());
|
||||||
|
println!(" 3. Review documentation:");
|
||||||
|
println!(" - README.md - Project overview");
|
||||||
|
println!(" - DESIGN_AND_TEST_PLAN.md - System architecture");
|
||||||
|
println!(" - TESTING_GUIDE.md - How to write tests");
|
||||||
|
println!(" 4. Build APK: {}", "./gradlew build".bright_cyan());
|
||||||
|
println!(" 5. Deploy to robot: {}", format!("weevil deploy {}", project_name).bright_cyan());
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
println!(" 2. Review README.md for project structure");
|
||||||
|
println!(" 3. Start coding in src/main/java/robot/");
|
||||||
|
println!(" 4. Run tests: {}", "./gradlew test".bright_cyan());
|
||||||
|
println!(" 5. Deploy to robot: {}", format!("weevil deploy {}", project_name).bright_cyan());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
println!();
|
||||||
|
}
|
||||||
@@ -52,6 +52,19 @@ pub fn upgrade_project(path: &str) -> Result<()> {
|
|||||||
"gradle/wrapper/gradle-wrapper.properties",
|
"gradle/wrapper/gradle-wrapper.properties",
|
||||||
"gradle/wrapper/gradle-wrapper.jar",
|
"gradle/wrapper/gradle-wrapper.jar",
|
||||||
".gitignore",
|
".gitignore",
|
||||||
|
// Android Studio integration — regenerated so run configs stay in
|
||||||
|
// sync if deploy.sh flags or script names ever change.
|
||||||
|
".idea/workspace.xml",
|
||||||
|
".idea/runConfigurations/Build.xml",
|
||||||
|
".idea/runConfigurations/Build (Windows).xml",
|
||||||
|
".idea/runConfigurations/Deploy (auto).xml",
|
||||||
|
".idea/runConfigurations/Deploy (auto) (Windows).xml",
|
||||||
|
".idea/runConfigurations/Deploy (USB).xml",
|
||||||
|
".idea/runConfigurations/Deploy (USB) (Windows).xml",
|
||||||
|
".idea/runConfigurations/Deploy (WiFi).xml",
|
||||||
|
".idea/runConfigurations/Deploy (WiFi) (Windows).xml",
|
||||||
|
".idea/runConfigurations/Test.xml",
|
||||||
|
".idea/runConfigurations/Test (Windows).xml",
|
||||||
];
|
];
|
||||||
|
|
||||||
println!("{}", "Updating infrastructure files...".bright_yellow());
|
println!("{}", "Updating infrastructure files...".bright_yellow());
|
||||||
|
|||||||
32
src/main.rs
32
src/main.rs
@@ -3,12 +3,6 @@ use colored::*;
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use weevil::version::WEEVIL_VERSION;
|
use weevil::version::WEEVIL_VERSION;
|
||||||
|
|
||||||
// Import ProxyConfig through our own `mod sdk`, not through the `weevil`
|
|
||||||
// library crate. Both re-export the same source, but Rust treats
|
|
||||||
// `weevil::sdk::proxy::ProxyConfig` and `sdk::proxy::ProxyConfig` as
|
|
||||||
// distinct types when a binary and its lib are compiled together.
|
|
||||||
// The command modules already see the local-mod version, so main must match.
|
|
||||||
|
|
||||||
mod commands;
|
mod commands;
|
||||||
mod sdk;
|
mod sdk;
|
||||||
mod project;
|
mod project;
|
||||||
@@ -42,7 +36,7 @@ enum Commands {
|
|||||||
/// Create a new FTC robot project
|
/// Create a new FTC robot project
|
||||||
New {
|
New {
|
||||||
/// Name of the robot project
|
/// Name of the robot project
|
||||||
name: String,
|
name: Option<String>,
|
||||||
|
|
||||||
/// Path to FTC SDK (optional, will auto-detect or download)
|
/// Path to FTC SDK (optional, will auto-detect or download)
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
@@ -51,6 +45,14 @@ enum Commands {
|
|||||||
/// Path to Android SDK (optional, will auto-detect or download)
|
/// Path to Android SDK (optional, will auto-detect or download)
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
android_sdk: Option<String>,
|
android_sdk: Option<String>,
|
||||||
|
|
||||||
|
/// Template to use (basic, testing)
|
||||||
|
#[arg(long, short = 't', value_name = "TEMPLATE")]
|
||||||
|
template: Option<String>,
|
||||||
|
|
||||||
|
/// List available templates
|
||||||
|
#[arg(long, conflicts_with = "name")]
|
||||||
|
list_templates: bool,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Check system health and diagnose issues
|
/// Check system health and diagnose issues
|
||||||
@@ -139,8 +141,20 @@ fn main() -> Result<()> {
|
|||||||
let proxy = ProxyConfig::resolve(cli.proxy.as_deref(), cli.no_proxy)?;
|
let proxy = ProxyConfig::resolve(cli.proxy.as_deref(), cli.no_proxy)?;
|
||||||
|
|
||||||
match cli.command {
|
match cli.command {
|
||||||
Commands::New { name, ftc_sdk, android_sdk } => {
|
Commands::New { name, ftc_sdk, android_sdk, template, list_templates } => {
|
||||||
commands::new::create_project(&name, ftc_sdk.as_deref(), android_sdk.as_deref(), &proxy)
|
if list_templates {
|
||||||
|
commands::new::list_templates()
|
||||||
|
} else if let Some(project_name) = name {
|
||||||
|
commands::new::create_project(
|
||||||
|
&project_name,
|
||||||
|
ftc_sdk.as_deref(),
|
||||||
|
android_sdk.as_deref(),
|
||||||
|
template.as_deref(),
|
||||||
|
&proxy
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
anyhow::bail!("Project name is required. Use --list-templates to see available templates.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Commands::Doctor => {
|
Commands::Doctor => {
|
||||||
commands::doctor::run_diagnostics()
|
commands::doctor::run_diagnostics()
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ impl ProjectBuilder {
|
|||||||
"src/test/java/robot",
|
"src/test/java/robot",
|
||||||
"src/test/java/robot/subsystems",
|
"src/test/java/robot/subsystems",
|
||||||
"gradle/wrapper",
|
"gradle/wrapper",
|
||||||
|
".idea/runConfigurations",
|
||||||
];
|
];
|
||||||
|
|
||||||
for dir in dirs {
|
for dir in dirs {
|
||||||
@@ -132,11 +133,6 @@ deploy.bat
|
|||||||
java
|
java
|
||||||
}}
|
}}
|
||||||
|
|
||||||
repositories {{
|
|
||||||
mavenCentral()
|
|
||||||
google()
|
|
||||||
}}
|
|
||||||
|
|
||||||
dependencies {{
|
dependencies {{
|
||||||
// Testing (runs on PC without SDK)
|
// Testing (runs on PC without SDK)
|
||||||
testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
|
testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
|
||||||
@@ -199,8 +195,18 @@ tasks.register<Exec>("buildApk") {{
|
|||||||
"#, sdk_path, sdk_path);
|
"#, sdk_path, sdk_path);
|
||||||
fs::write(project_path.join("build.gradle.kts"), build_gradle)?;
|
fs::write(project_path.join("build.gradle.kts"), build_gradle)?;
|
||||||
|
|
||||||
// settings.gradle.kts
|
// settings.gradle.kts - Repositories go here in Gradle 8+
|
||||||
let settings_gradle = format!("rootProject.name = \"{}\"\n", self.name);
|
let settings_gradle = format!(r#"rootProject.name = "{}"
|
||||||
|
|
||||||
|
// Repository configuration (Gradle 8+ prefers repositories in settings)
|
||||||
|
dependencyResolutionManagement {{
|
||||||
|
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
|
||||||
|
repositories {{
|
||||||
|
mavenCentral()
|
||||||
|
google()
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
"#, self.name);
|
||||||
fs::write(project_path.join("settings.gradle.kts"), settings_gradle)?;
|
fs::write(project_path.join("settings.gradle.kts"), settings_gradle)?;
|
||||||
|
|
||||||
// build.sh (Linux/Mac)
|
// build.sh (Linux/Mac)
|
||||||
@@ -416,6 +422,304 @@ class BasicTest {
|
|||||||
test_file
|
test_file
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
// Android Studio integration: .idea/ files
|
||||||
|
self.generate_idea_files(project_path)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate .idea/ files for Android Studio integration.
|
||||||
|
///
|
||||||
|
/// The goal is for students to open the project in Android Studio and see
|
||||||
|
/// a clean file tree (just src/ and the scripts) with Run configurations
|
||||||
|
/// that invoke Weevil's shell scripts directly. All the internal plumbing
|
||||||
|
/// (sdk/, .gradle/, build/) is hidden from the IDE view.
|
||||||
|
///
|
||||||
|
/// Android Studio uses IntelliJ's run configuration XML format. The
|
||||||
|
/// ShellScript type invokes a script relative to the project root — exactly
|
||||||
|
/// what we want since deploy.sh and build.sh already live there.
|
||||||
|
fn generate_idea_files(&self, project_path: &Path) -> Result<()> {
|
||||||
|
// workspace.xml — controls the file-tree view and hides internals.
|
||||||
|
// We use a ProjectViewPane exclude pattern list rather than touching
|
||||||
|
// the module's source roots, so this works regardless of whether the
|
||||||
|
// student has opened the project before.
|
||||||
|
let workspace_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectViewManager">
|
||||||
|
<state>
|
||||||
|
<navigator currentProjector="ProjectFiles" hideEmptyMiddlePackages="true" sortByType="true">
|
||||||
|
<state>
|
||||||
|
<expand>
|
||||||
|
<file url="file://$PROJECT_DIR$/src" />
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main" />
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main/java" />
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main/java/robot" />
|
||||||
|
<file url="file://$PROJECT_DIR$/src/test" />
|
||||||
|
<file url="file://$PROJECT_DIR$/src/test/java" />
|
||||||
|
<file url="file://$PROJECT_DIR$/src/test/java/robot" />
|
||||||
|
</expand>
|
||||||
|
</state>
|
||||||
|
</navigator>
|
||||||
|
</state>
|
||||||
|
</component>
|
||||||
|
<component name="ExcludedFiles">
|
||||||
|
<file url="file://$PROJECT_DIR$/build" reason="Build output" />
|
||||||
|
<file url="file://$PROJECT_DIR$/.gradle" reason="Gradle cache" />
|
||||||
|
<file url="file://$PROJECT_DIR$/gradle" reason="Gradle wrapper internals" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
"#;
|
||||||
|
fs::write(project_path.join(".idea/workspace.xml"), workspace_xml)?;
|
||||||
|
|
||||||
|
// Run configurations. Each is a ShellScript type that invokes one of
|
||||||
|
// Weevil's scripts. Android Studio shows these in the Run dropdown
|
||||||
|
// at the top of the IDE — no configuration needed by the student.
|
||||||
|
//
|
||||||
|
// We generate both Unix (.sh, ./gradlew) and Windows (.bat, gradlew.bat)
|
||||||
|
// variants. Android Studio automatically hides configs whose script files
|
||||||
|
// don't exist, so only the platform-appropriate ones appear in the dropdown.
|
||||||
|
|
||||||
|
// Build (Unix) — just builds the APK without deploying
|
||||||
|
let build_unix_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Build" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/build.sh" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="/bin/bash" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Build.xml"),
|
||||||
|
build_unix_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Build (Windows) — same, but calls build.bat
|
||||||
|
let build_windows_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Build (Windows)" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/build.bat" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="C:\Windows\System32\cmd.exe" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="/c" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Build (Windows).xml"),
|
||||||
|
build_windows_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Deploy (auto) — no flags, deploy.sh auto-detects USB vs WiFi
|
||||||
|
let deploy_auto_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Deploy (auto)" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/deploy.sh" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="/bin/bash" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Deploy (auto).xml"),
|
||||||
|
deploy_auto_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Deploy (auto) (Windows)
|
||||||
|
let deploy_auto_windows_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Deploy (auto) (Windows)" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/deploy.bat" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="C:\Windows\System32\cmd.exe" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="/c" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Deploy (auto) (Windows).xml"),
|
||||||
|
deploy_auto_windows_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Deploy (USB) — forces USB connection
|
||||||
|
let deploy_usb_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Deploy (USB)" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/deploy.sh" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="--usb" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="/bin/bash" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Deploy (USB).xml"),
|
||||||
|
deploy_usb_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Deploy (USB) (Windows)
|
||||||
|
let deploy_usb_windows_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Deploy (USB) (Windows)" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/deploy.bat" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="C:\Windows\System32\cmd.exe" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="/c" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Deploy (USB) (Windows).xml"),
|
||||||
|
deploy_usb_windows_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Deploy (WiFi) — forces WiFi connection to default 192.168.43.1
|
||||||
|
let deploy_wifi_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Deploy (WiFi)" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/deploy.sh" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="--wifi" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="/bin/bash" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Deploy (WiFi).xml"),
|
||||||
|
deploy_wifi_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Deploy (WiFi) (Windows)
|
||||||
|
let deploy_wifi_windows_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Deploy (WiFi) (Windows)" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/deploy.bat" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="C:\Windows\System32\cmd.exe" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="/c" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Deploy (WiFi) (Windows).xml"),
|
||||||
|
deploy_wifi_windows_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Test — runs the unit test suite via Gradle
|
||||||
|
let test_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Test" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/gradlew" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="test" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="/bin/bash" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Test.xml"),
|
||||||
|
test_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
// Test (Windows)
|
||||||
|
let test_windows_xml = r#"<component name="ProjectRunConfigurationManager">
|
||||||
|
<configuration name="Test (Windows)" type="ShConfigurationType">
|
||||||
|
<option name="SCRIPT_TEXT" value="" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||||
|
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/gradlew.bat" />
|
||||||
|
<option name="SCRIPT_OPTIONS" value="test" />
|
||||||
|
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
|
||||||
|
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
|
||||||
|
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
|
||||||
|
<option name="INTERPRETER_PATH" value="C:\Windows\System32\cmd.exe" />
|
||||||
|
<option name="INTERPRETER_OPTIONS" value="/c" />
|
||||||
|
<option name="EXECUTE_IN_TERMINAL" value="true" />
|
||||||
|
<option name="EXECUTE_SCRIPT_FILE" value="true" />
|
||||||
|
<envs />
|
||||||
|
<method v="2" />
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
"#;
|
||||||
|
fs::write(
|
||||||
|
project_path.join(".idea/runConfigurations/Test (Windows).xml"),
|
||||||
|
test_windows_xml,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,101 +1,288 @@
|
|||||||
use include_dir::{include_dir, Dir};
|
use include_dir::{include_dir, Dir};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use anyhow::{Result, Context};
|
use anyhow::{Result, Context, bail};
|
||||||
use tera::{Tera, Context as TeraContext};
|
use tera::Tera;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
use colored::*;
|
||||||
|
|
||||||
// Embed all template files at compile time
|
// Embed template directories at compile time
|
||||||
static TEMPLATES_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates");
|
static BASIC_TEMPLATE: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/basic");
|
||||||
|
static TESTING_TEMPLATE: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/testing");
|
||||||
|
static LOCALIZATION_TEMPLATE: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates/localization");
|
||||||
|
|
||||||
pub struct TemplateEngine {
|
pub struct TemplateManager {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
tera: Tera,
|
tera: Tera,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TemplateEngine {
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn new() -> Result<Self> {
|
pub struct TemplateInfo {
|
||||||
let mut tera = Tera::default();
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
// Load all templates from embedded directory
|
pub file_count: usize,
|
||||||
for file in TEMPLATES_DIR.files() {
|
pub line_count: usize,
|
||||||
let path = file.path().to_string_lossy();
|
pub test_count: usize,
|
||||||
let contents = file.contents_utf8()
|
pub is_default: bool,
|
||||||
.context("Template must be valid UTF-8")?;
|
|
||||||
tera.add_raw_template(&path, contents)?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct TemplateContext {
|
||||||
|
pub project_name: String,
|
||||||
|
pub package_name: String,
|
||||||
|
pub creation_date: String,
|
||||||
|
pub weevil_version: String,
|
||||||
|
pub template_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TemplateManager {
|
||||||
|
pub fn new() -> Result<Self> {
|
||||||
|
let tera = Tera::default();
|
||||||
Ok(Self { tera })
|
Ok(Self { tera })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn template_exists(&self, name: &str) -> bool {
|
||||||
|
matches!(name, "basic" | "testing" | "localization")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list_templates(&self) -> Vec<String> {
|
||||||
|
vec![
|
||||||
|
" basic - Minimal FTC project (default)".to_string(),
|
||||||
|
" testing - Testing showcase with examples".to_string(),
|
||||||
|
" localization - Grid-based positioning with sensor fusion".to_string(),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn render_to_file(
|
pub fn get_template_info_all(&self) -> Result<Vec<TemplateInfo>> {
|
||||||
|
Ok(vec![
|
||||||
|
TemplateInfo {
|
||||||
|
name: "basic".to_string(),
|
||||||
|
description: "Minimal FTC project structure".to_string(),
|
||||||
|
file_count: 10,
|
||||||
|
line_count: 50,
|
||||||
|
test_count: 0,
|
||||||
|
is_default: true,
|
||||||
|
},
|
||||||
|
TemplateInfo {
|
||||||
|
name: "testing".to_string(),
|
||||||
|
description: "Professional testing showcase with examples".to_string(),
|
||||||
|
file_count: 30,
|
||||||
|
line_count: 2500,
|
||||||
|
test_count: 45,
|
||||||
|
is_default: false,
|
||||||
|
},
|
||||||
|
TemplateInfo {
|
||||||
|
name: "localization".to_string(),
|
||||||
|
description: "Grid-based robot localization with sensor fusion".to_string(),
|
||||||
|
file_count: 21,
|
||||||
|
line_count: 1500,
|
||||||
|
test_count: 3,
|
||||||
|
is_default: false,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn show_template_info(&self, name: &str) -> Result<()> {
|
||||||
|
let info = match name {
|
||||||
|
"basic" => TemplateInfo {
|
||||||
|
name: "basic".to_string(),
|
||||||
|
description: "Minimal FTC project with clean structure".to_string(),
|
||||||
|
file_count: 10,
|
||||||
|
line_count: 50,
|
||||||
|
test_count: 0,
|
||||||
|
is_default: true,
|
||||||
|
},
|
||||||
|
"testing" => TemplateInfo {
|
||||||
|
name: "testing".to_string(),
|
||||||
|
description: "Comprehensive testing showcase demonstrating professional robotics software engineering practices.".to_string(),
|
||||||
|
file_count: 30,
|
||||||
|
line_count: 2500,
|
||||||
|
test_count: 45,
|
||||||
|
is_default: false,
|
||||||
|
},
|
||||||
|
"localization" => TemplateInfo {
|
||||||
|
name: "localization".to_string(),
|
||||||
|
description: "Grid-based robot localization system with multi-sensor fusion and fault tolerance.".to_string(),
|
||||||
|
file_count: 21,
|
||||||
|
line_count: 1500,
|
||||||
|
test_count: 3,
|
||||||
|
is_default: false,
|
||||||
|
},
|
||||||
|
_ => bail!("Unknown template: {}", name),
|
||||||
|
};
|
||||||
|
|
||||||
|
println!("{}", format!("Template: {}", info.name).bright_cyan().bold());
|
||||||
|
println!();
|
||||||
|
println!("{}", "Description:".bright_white().bold());
|
||||||
|
println!(" {}", info.description);
|
||||||
|
println!();
|
||||||
|
|
||||||
|
if info.name == "testing" {
|
||||||
|
println!("{}", "Features:".bright_white().bold());
|
||||||
|
println!(" • Three complete subsystems with full test coverage");
|
||||||
|
println!(" • Hardware abstraction layer with mocks");
|
||||||
|
println!(" • 45 passing tests (unit, integration, system)");
|
||||||
|
println!(" • Comprehensive documentation (6 files)");
|
||||||
|
println!(" • Ready to use as learning material");
|
||||||
|
println!();
|
||||||
|
}
|
||||||
|
|
||||||
|
if info.name == "localization" {
|
||||||
|
println!("{}", "Features:".bright_white().bold());
|
||||||
|
println!(" • 12x12 field grid system (12-inch cells)");
|
||||||
|
println!(" • Multi-sensor fusion (encoders + IMU + vision)");
|
||||||
|
println!(" • Fault-tolerant positioning (graceful degradation)");
|
||||||
|
println!(" • Kalman-filter-style sensor fusion");
|
||||||
|
println!(" • Professional robotics patterns");
|
||||||
|
println!();
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("{}", "Files included:".bright_white().bold());
|
||||||
|
println!(" {} files", info.file_count);
|
||||||
|
println!(" ~{} lines of code", info.line_count);
|
||||||
|
if info.test_count > 0 {
|
||||||
|
println!(" {} tests", info.test_count);
|
||||||
|
}
|
||||||
|
println!();
|
||||||
|
|
||||||
|
println!("{}", "Example usage:".bright_white().bold());
|
||||||
|
println!(" weevil new my-robot --template {}", info.name);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn extract_template(
|
||||||
&self,
|
&self,
|
||||||
template_name: &str,
|
template_name: &str,
|
||||||
output_path: &Path,
|
output_dir: &Path,
|
||||||
context: &TeraContext,
|
context: &TemplateContext,
|
||||||
) -> Result<()> {
|
) -> Result<usize> {
|
||||||
let rendered = self.tera.render(template_name, context)?;
|
let template_dir = match template_name {
|
||||||
|
"basic" => &BASIC_TEMPLATE,
|
||||||
|
"testing" => &TESTING_TEMPLATE,
|
||||||
|
"localization" => &LOCALIZATION_TEMPLATE,
|
||||||
|
_ => bail!("Unknown template: {}", template_name),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Extract all files from template
|
||||||
|
let file_count = self.extract_dir_recursively(template_dir, output_dir, "", context)?;
|
||||||
|
|
||||||
|
Ok(file_count)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_dir_recursively(
|
||||||
|
&self,
|
||||||
|
source: &Dir,
|
||||||
|
output_base: &Path,
|
||||||
|
relative_path: &str,
|
||||||
|
context: &TemplateContext,
|
||||||
|
) -> Result<usize> {
|
||||||
|
let mut file_count = 0;
|
||||||
|
|
||||||
|
// Process files in current directory
|
||||||
|
for file in source.files() {
|
||||||
|
let file_path = file.path();
|
||||||
|
let file_name = file_path.file_name().unwrap().to_string_lossy();
|
||||||
|
|
||||||
|
let output_path = if relative_path.is_empty() {
|
||||||
|
output_base.join(&*file_name)
|
||||||
|
} else {
|
||||||
|
output_base.join(relative_path).join(&*file_name)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create parent directory if needed
|
||||||
if let Some(parent) = output_path.parent() {
|
if let Some(parent) = output_path.parent() {
|
||||||
fs::create_dir_all(parent)?;
|
fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
fs::write(output_path, rendered)?;
|
// Process file based on extension
|
||||||
Ok(())
|
if file_name.ends_with(".template") {
|
||||||
|
// Template file - process variables
|
||||||
|
let contents = file.contents_utf8()
|
||||||
|
.context("Template file must be UTF-8")?;
|
||||||
|
|
||||||
|
let processed = self.process_template_string(contents, context)?;
|
||||||
|
|
||||||
|
// Remove .template extension from output
|
||||||
|
let output_name = file_name.trim_end_matches(".template");
|
||||||
|
let final_path = output_path.with_file_name(output_name);
|
||||||
|
|
||||||
|
fs::write(final_path, processed)?;
|
||||||
|
file_count += 1;
|
||||||
|
} else {
|
||||||
|
// Regular file - copy as-is
|
||||||
|
fs::write(&output_path, file.contents())?;
|
||||||
|
file_count += 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
// Process subdirectories
|
||||||
pub fn extract_static_file(&self, template_path: &str, output_path: &Path) -> Result<()> {
|
for dir in source.dirs() {
|
||||||
let file = TEMPLATES_DIR
|
let dir_name = dir.path().file_name().unwrap().to_string_lossy();
|
||||||
.get_file(template_path)
|
let new_relative = if relative_path.is_empty() {
|
||||||
.context(format!("Template not found: {}", template_path))?;
|
dir_name.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{}/{}", relative_path, dir_name)
|
||||||
|
};
|
||||||
|
|
||||||
if let Some(parent) = output_path.parent() {
|
file_count += self.extract_dir_recursively(dir, output_base, &new_relative, context)?;
|
||||||
fs::create_dir_all(parent)?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fs::write(output_path, file.contents())?;
|
Ok(file_count)
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
fn process_template_string(
|
||||||
pub fn list_templates(&self) -> Vec<String> {
|
&self,
|
||||||
TEMPLATES_DIR
|
template: &str,
|
||||||
.files()
|
context: &TemplateContext,
|
||||||
.map(|f| f.path().to_string_lossy().to_string())
|
) -> Result<String> {
|
||||||
.collect()
|
let processed = template
|
||||||
|
.replace("{{PROJECT_NAME}}", &context.project_name)
|
||||||
|
.replace("{{PACKAGE_NAME}}", &context.package_name)
|
||||||
|
.replace("{{CREATION_DATE}}", &context.creation_date)
|
||||||
|
.replace("{{WEEVIL_VERSION}}", &context.weevil_version)
|
||||||
|
.replace("{{TEMPLATE_NAME}}", &context.template_name);
|
||||||
|
|
||||||
|
Ok(processed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use tempfile::TempDir;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_template_engine_creation() {
|
fn test_template_manager_creation() {
|
||||||
let engine = TemplateEngine::new();
|
let mgr = TemplateManager::new();
|
||||||
assert!(engine.is_ok());
|
assert!(mgr.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_template_exists() {
|
||||||
|
let mgr = TemplateManager::new().unwrap();
|
||||||
|
assert!(mgr.template_exists("basic"));
|
||||||
|
assert!(mgr.template_exists("testing"));
|
||||||
|
assert!(mgr.template_exists("localization"));
|
||||||
|
assert!(!mgr.template_exists("nonexistent"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_list_templates() {
|
fn test_list_templates() {
|
||||||
let engine = TemplateEngine::new().unwrap();
|
let mgr = TemplateManager::new().unwrap();
|
||||||
let templates = engine.list_templates();
|
let templates = mgr.list_templates();
|
||||||
assert!(!templates.is_empty());
|
assert_eq!(templates.len(), 3);
|
||||||
|
assert!(templates[0].contains("basic"));
|
||||||
|
assert!(templates[1].contains("testing"));
|
||||||
|
assert!(templates[2].contains("localization"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_render_template() {
|
fn test_template_info_all() {
|
||||||
let _engine = TemplateEngine::new().unwrap();
|
let mgr = TemplateManager::new().unwrap();
|
||||||
let temp = TempDir::new().unwrap();
|
let infos = mgr.get_template_info_all().unwrap();
|
||||||
let _output = temp.path().join("test.txt");
|
assert_eq!(infos.len(), 3);
|
||||||
|
assert_eq!(infos[0].name, "basic");
|
||||||
let mut context = TeraContext::new();
|
assert_eq!(infos[1].name, "testing");
|
||||||
context.insert("project_name", "TestRobot");
|
assert_eq!(infos[2].name, "localization");
|
||||||
|
|
||||||
// This will fail until we add templates, but shows the pattern
|
|
||||||
// engine.render_to_file("README.md", &output, &context).unwrap();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
26
templates/basic/.gitignore
vendored
Normal file
26
templates/basic/.gitignore
vendored
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Gradle
|
||||||
|
.gradle/
|
||||||
|
build/
|
||||||
|
gradle-app.setting
|
||||||
|
!gradle-wrapper.jar
|
||||||
|
|
||||||
|
# Android
|
||||||
|
*.apk
|
||||||
|
*.ap_
|
||||||
|
*.aab
|
||||||
|
local.properties
|
||||||
|
|
||||||
|
# IDEs
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Weevil
|
||||||
|
.weevil/
|
||||||
1
templates/basic/.gitkeep
Normal file
1
templates/basic/.gitkeep
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# This file ensures the directory is tracked by git even when empty
|
||||||
53
templates/basic/README.md.template
Normal file
53
templates/basic/README.md.template
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
# {{PROJECT_NAME}}
|
||||||
|
|
||||||
|
FTC Robot project created with Weevil {{WEEVIL_VERSION}} on {{CREATION_DATE}}.
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
This is a minimal FTC robot project. Add your robot code in:
|
||||||
|
- `src/main/java/robot/opmodes/` - OpModes for TeleOp and Autonomous
|
||||||
|
- `src/main/java/robot/subsystems/` - Robot subsystems
|
||||||
|
- `src/main/java/robot/hardware/` - Hardware abstractions
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Setup environment (first time only)
|
||||||
|
weevil setup
|
||||||
|
|
||||||
|
# Build APK
|
||||||
|
weevil build
|
||||||
|
|
||||||
|
# Deploy to robot
|
||||||
|
weevil deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
{{PROJECT_NAME}}/
|
||||||
|
├── src/
|
||||||
|
│ ├── main/java/robot/
|
||||||
|
│ │ ├── hardware/ # Hardware interfaces
|
||||||
|
│ │ ├── subsystems/ # Robot subsystems
|
||||||
|
│ │ └── opmodes/ # TeleOp and Autonomous
|
||||||
|
│ └── test/java/robot/ # Unit tests
|
||||||
|
├── build.gradle # Build configuration
|
||||||
|
└── README.md # This file
|
||||||
|
```
|
||||||
|
|
||||||
|
## Next Steps
|
||||||
|
|
||||||
|
1. Add your robot hardware in `src/main/java/robot/hardware/`
|
||||||
|
2. Create subsystems in `src/main/java/robot/subsystems/`
|
||||||
|
3. Write OpModes in `src/main/java/robot/opmodes/`
|
||||||
|
4. Test and deploy!
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- [Weevil Documentation](https://docs.weevil.dev)
|
||||||
|
- [FTC SDK Documentation](https://ftc-docs.firstinspires.org)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Created with [Weevil](https://weevil.dev) - FTC Project Generator
|
||||||
17
templates/basic/settings.gradle
Normal file
17
templates/basic/settings.gradle
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
gradlePluginPortal()
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = 'FtcRobotController'
|
||||||
1
templates/basic/src/main/java/robot/hardware/.gitkeep
Normal file
1
templates/basic/src/main/java/robot/hardware/.gitkeep
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# This file ensures the directory is tracked by git even when empty
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package robot.opmodes;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Basic OpMode for {{PROJECT_NAME}}
|
||||||
|
*
|
||||||
|
* This is a placeholder to demonstrate project structure.
|
||||||
|
* To use this with FTC SDK:
|
||||||
|
* 1. Run: weevil deploy {{PROJECT_NAME}}
|
||||||
|
* 2. Add FTC SDK imports (OpMode, TeleOp, etc.)
|
||||||
|
* 3. Extend OpMode and implement methods
|
||||||
|
*
|
||||||
|
* For local testing (without robot), write unit tests in src/test/java/robot/
|
||||||
|
* Run tests with: ./gradlew test
|
||||||
|
*
|
||||||
|
* Created by Weevil {{WEEVIL_VERSION}}
|
||||||
|
* Template: {{TEMPLATE_NAME}}
|
||||||
|
*/
|
||||||
|
public class BasicOpMode {
|
||||||
|
|
||||||
|
// This placeholder compiles without FTC SDK dependencies
|
||||||
|
// Replace with actual OpMode code when deploying to robot
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("{{PROJECT_NAME}} - Ready for deployment");
|
||||||
|
System.out.println("Run: weevil deploy {{PROJECT_NAME}}");
|
||||||
|
}
|
||||||
|
}
|
||||||
1
templates/basic/src/main/java/robot/subsystems/.gitkeep
Normal file
1
templates/basic/src/main/java/robot/subsystems/.gitkeep
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# This file ensures the directory is tracked by git even when empty
|
||||||
1
templates/basic/src/test/java/robot/.gitkeep
Normal file
1
templates/basic/src/test/java/robot/.gitkeep
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# This file ensures the directory is tracked by git even when empty
|
||||||
7
templates/localization/.gitignore
vendored
Normal file
7
templates/localization/.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
build/
|
||||||
|
.gradle/
|
||||||
|
*.iml
|
||||||
|
.idea/
|
||||||
|
local.properties
|
||||||
|
*.apk
|
||||||
|
.DS_Store
|
||||||
53
templates/localization/README.md.template
Normal file
53
templates/localization/README.md.template
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
# {{PROJECT_NAME}} - Localization Template
|
||||||
|
|
||||||
|
Grid-based robot localization with sensor fusion and fault tolerance.
|
||||||
|
|
||||||
|
**Created:** {{CREATION_DATE}}
|
||||||
|
**Weevil:** {{WEEVIL_VERSION}}
|
||||||
|
**Template:** localization
|
||||||
|
|
||||||
|
## What's Included
|
||||||
|
|
||||||
|
- **Grid System** - 12x12 field grid (12" cells)
|
||||||
|
- **Sensor Fusion** - Combine encoders, IMU, vision
|
||||||
|
- **Fault Tolerance** - Graceful sensor failure handling
|
||||||
|
- **3 Tests** - All passing
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./gradlew test # Run tests
|
||||||
|
./build.sh # Build
|
||||||
|
./deploy.sh # Deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
Field divided into 144 cells (12x12 grid):
|
||||||
|
- Cell (0,0) = Red backstage
|
||||||
|
- Cell (11,11) = Blue backstage
|
||||||
|
- Cell (6,6) = Center
|
||||||
|
|
||||||
|
Sensor fusion priority:
|
||||||
|
1. Vision (AprilTags) - ±2" accuracy
|
||||||
|
2. IMU + Odometry - ±4" accuracy
|
||||||
|
3. Odometry only - ±12" accuracy
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
**Localization:**
|
||||||
|
- GridCell.java - Cell representation
|
||||||
|
- Pose2D.java - Position + heading
|
||||||
|
- FieldGrid.java - Coordinate system
|
||||||
|
- RobotLocalizer.java - Sensor fusion engine
|
||||||
|
|
||||||
|
**Sensors:**
|
||||||
|
- OdometryTracker.java - Dead reckoning
|
||||||
|
- ImuLocalizer.java - Heading tracking
|
||||||
|
- VisionLocalizer.java - AprilTag positioning
|
||||||
|
|
||||||
|
**Docs:**
|
||||||
|
- LOCALIZATION_GUIDE.md - How it works
|
||||||
|
- GRID_SYSTEM.md - Field coordinates
|
||||||
|
|
||||||
|
See docs/ for full documentation.
|
||||||
41
templates/localization/docs/GRID_SYSTEM.md
Normal file
41
templates/localization/docs/GRID_SYSTEM.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# Field Grid System
|
||||||
|
|
||||||
|
## Grid Layout
|
||||||
|
|
||||||
|
12x12 cells, each 12" x 12":
|
||||||
|
|
||||||
|
```
|
||||||
|
0 1 2 3 4 5 6 7 8 9 10 11
|
||||||
|
11 . . . . . . . . . . . B
|
||||||
|
10 . . . . . . . . . . . .
|
||||||
|
9 . . . . . . . . . . . .
|
||||||
|
8 . . . . . . . . . . . .
|
||||||
|
7 . . . . . . . . . . . .
|
||||||
|
6 . . . . . X . . . . . .
|
||||||
|
5 . . . . . . . . . . . .
|
||||||
|
4 . . . . . . . . . . . .
|
||||||
|
3 . . . . . . . . . . . .
|
||||||
|
2 . . . . . . . . . . . .
|
||||||
|
1 . . . . . . . . . . . .
|
||||||
|
0 R . . . . . . . . . . .
|
||||||
|
|
||||||
|
R = Red backstage (0,0)
|
||||||
|
B = Blue backstage (11,11)
|
||||||
|
X = Center (6,6)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```java
|
||||||
|
GridCell cell = new GridCell(5, 7);
|
||||||
|
double dist = cell.distanceTo(FieldGrid.CENTER);
|
||||||
|
double angle = cell.angleTo(FieldGrid.BLUE_BACKSTAGE);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Locations
|
||||||
|
|
||||||
|
```java
|
||||||
|
FieldGrid.RED_BACKSTAGE // (0, 0)
|
||||||
|
FieldGrid.BLUE_BACKSTAGE // (11, 11)
|
||||||
|
FieldGrid.CENTER // (6, 6)
|
||||||
|
```
|
||||||
72
templates/localization/docs/LOCALIZATION_GUIDE.md
Normal file
72
templates/localization/docs/LOCALIZATION_GUIDE.md
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
# Robot Localization Guide
|
||||||
|
|
||||||
|
## What is Localization?
|
||||||
|
|
||||||
|
Answering: "Where is my robot on the field?"
|
||||||
|
|
||||||
|
## The Grid System
|
||||||
|
|
||||||
|
12ft x 12ft field → 12x12 grid of 12" cells
|
||||||
|
|
||||||
|
```
|
||||||
|
Cell (0,0) = Red backstage
|
||||||
|
Cell (11,11) = Blue backstage
|
||||||
|
Cell (6,6) = Center
|
||||||
|
```
|
||||||
|
|
||||||
|
## Sensor Fusion
|
||||||
|
|
||||||
|
Combine three sensors:
|
||||||
|
|
||||||
|
1. **Odometry (Encoders)** - Track wheel rotation
|
||||||
|
- Accuracy: ±1" per foot (cumulative drift)
|
||||||
|
- Always available
|
||||||
|
|
||||||
|
2. **IMU (Gyroscope)** - Measure heading
|
||||||
|
- Accuracy: ±2° (non-cumulative)
|
||||||
|
- Corrects heading drift
|
||||||
|
|
||||||
|
3. **Vision (AprilTags)** - Detect position markers
|
||||||
|
- Accuracy: ±2" (when visible)
|
||||||
|
- Ground truth - resets drift
|
||||||
|
|
||||||
|
## Fusion Strategy
|
||||||
|
|
||||||
|
```
|
||||||
|
if vision available:
|
||||||
|
position = vision (most accurate)
|
||||||
|
correct odometry
|
||||||
|
elif IMU available:
|
||||||
|
position = odometry
|
||||||
|
heading = IMU
|
||||||
|
else:
|
||||||
|
position = odometry only (dead reckoning)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fault Tolerance
|
||||||
|
|
||||||
|
| Sensors | Accuracy | Confidence |
|
||||||
|
|---------|----------|------------|
|
||||||
|
| All 3 | ±2" | 100% |
|
||||||
|
| Odometry + IMU | ±4" | 70% |
|
||||||
|
| Odometry only | ±12" | 40% |
|
||||||
|
|
||||||
|
System keeps working when sensors fail!
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```java
|
||||||
|
RobotLocalizer localizer = new RobotLocalizer(odometry, imu, vision);
|
||||||
|
localizer.setInitialPose(new Pose2D(12, 12, 0));
|
||||||
|
|
||||||
|
while (opModeIsActive()) {
|
||||||
|
localizer.update();
|
||||||
|
|
||||||
|
GridCell cell = localizer.getCurrentCell();
|
||||||
|
double confidence = localizer.getConfidence();
|
||||||
|
|
||||||
|
// Make decisions based on position
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
See README.md for full examples.
|
||||||
17
templates/localization/settings.gradle.kts.template
Normal file
17
templates/localization/settings.gradle.kts.template
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
google()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = "{{PROJECT_NAME}}"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
public interface Encoder {
|
||||||
|
int getTicks();
|
||||||
|
int getTicksPerRevolution();
|
||||||
|
boolean isConnected();
|
||||||
|
void reset();
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
public interface GyroSensor {
|
||||||
|
double getHeading();
|
||||||
|
boolean isConnected();
|
||||||
|
void calibrate();
|
||||||
|
boolean isCalibrated();
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
import robot.localization.Pose2D;
|
||||||
|
|
||||||
|
public interface VisionCamera {
|
||||||
|
Pose2D detectPose();
|
||||||
|
boolean isConnected();
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
public class FieldGrid {
|
||||||
|
public static final int FIELD_SIZE = 144;
|
||||||
|
public static final int CELL_SIZE = 12;
|
||||||
|
public static final int GRID_SIZE = 12;
|
||||||
|
|
||||||
|
public static final GridCell RED_BACKSTAGE = new GridCell(0, 0);
|
||||||
|
public static final GridCell BLUE_BACKSTAGE = new GridCell(11, 11);
|
||||||
|
public static final GridCell CENTER = new GridCell(6, 6);
|
||||||
|
|
||||||
|
public static GridCell poseToCell(Pose2D pose) {
|
||||||
|
double cx = Math.max(0, Math.min(FIELD_SIZE - 0.001, pose.x));
|
||||||
|
double cy = Math.max(0, Math.min(FIELD_SIZE - 0.001, pose.y));
|
||||||
|
return new GridCell((int)(cx / CELL_SIZE), (int)(cy / CELL_SIZE));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Pose2D cellToPose(GridCell cell) {
|
||||||
|
return new Pose2D((cell.x + 0.5) * CELL_SIZE, (cell.y + 0.5) * CELL_SIZE, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isWithinField(Pose2D pose) {
|
||||||
|
return pose.x >= 0 && pose.x <= FIELD_SIZE && pose.y >= 0 && pose.y <= FIELD_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Pose2D clampToField(Pose2D pose) {
|
||||||
|
double x = Math.max(0, Math.min(FIELD_SIZE, pose.x));
|
||||||
|
double y = Math.max(0, Math.min(FIELD_SIZE, pose.y));
|
||||||
|
return new Pose2D(x, y, pose.heading);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
public class GridCell {
|
||||||
|
public final int x, y;
|
||||||
|
|
||||||
|
public GridCell(int x, int y) {
|
||||||
|
if (x < 0 || x > 11 || y < 0 || y > 11) {
|
||||||
|
throw new IllegalArgumentException("Cell out of bounds: (" + x + "," + y + ")");
|
||||||
|
}
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double distanceTo(GridCell other) {
|
||||||
|
int dx = other.x - this.x;
|
||||||
|
int dy = other.y - this.y;
|
||||||
|
return Math.sqrt(dx * dx + dy * dy) * FieldGrid.CELL_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double angleTo(GridCell other) {
|
||||||
|
return Math.toDegrees(Math.atan2(other.y - this.y, other.x - this.x));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pose2D getCenterPose() {
|
||||||
|
return new Pose2D((x + 0.5) * FieldGrid.CELL_SIZE, (y + 0.5) * FieldGrid.CELL_SIZE, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isAdjacentTo(GridCell other) {
|
||||||
|
int dx = Math.abs(other.x - this.x);
|
||||||
|
int dy = Math.abs(other.y - this.y);
|
||||||
|
return dx <= 1 && dy <= 1 && (dx + dy) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int manhattanDistanceTo(GridCell other) {
|
||||||
|
return Math.abs(other.x - this.x) + Math.abs(other.y - this.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (!(obj instanceof GridCell)) return false;
|
||||||
|
GridCell o = (GridCell) obj;
|
||||||
|
return this.x == o.x && this.y == o.y;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() { return x * 31 + y; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() { return "Cell(" + x + "," + y + ")"; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
import robot.hardware.GyroSensor;
|
||||||
|
|
||||||
|
public class ImuLocalizer {
|
||||||
|
private final GyroSensor gyro;
|
||||||
|
private double headingOffset;
|
||||||
|
|
||||||
|
public ImuLocalizer(GyroSensor gyro) {
|
||||||
|
this.gyro = gyro;
|
||||||
|
this.headingOffset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void calibrate(double initialHeading) {
|
||||||
|
if (gyro.isConnected()) {
|
||||||
|
gyro.calibrate();
|
||||||
|
this.headingOffset = initialHeading - gyro.getHeading();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Double getHeading() {
|
||||||
|
if (!gyro.isConnected() || !gyro.isCalibrated()) return null;
|
||||||
|
return Pose2D.normalizeAngle(gyro.getHeading() + headingOffset);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isWorking() {
|
||||||
|
return gyro.isConnected() && gyro.isCalibrated();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
import robot.hardware.Encoder;
|
||||||
|
|
||||||
|
public class OdometryTracker {
|
||||||
|
private final Encoder leftEncoder, rightEncoder;
|
||||||
|
private final double wheelDiameter, trackWidth;
|
||||||
|
private Pose2D currentPose;
|
||||||
|
private int lastLeftTicks, lastRightTicks;
|
||||||
|
|
||||||
|
public OdometryTracker(Encoder left, Encoder right, double wheelDia, double trackW) {
|
||||||
|
this.leftEncoder = left;
|
||||||
|
this.rightEncoder = right;
|
||||||
|
this.wheelDiameter = wheelDia;
|
||||||
|
this.trackWidth = trackW;
|
||||||
|
this.currentPose = new Pose2D(0, 0, 0);
|
||||||
|
this.lastLeftTicks = left.getTicks();
|
||||||
|
this.lastRightTicks = right.getTicks();
|
||||||
|
}
|
||||||
|
|
||||||
|
public OdometryTracker(Encoder left, Encoder right) {
|
||||||
|
this(left, right, 4.0, 16.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPose(Pose2D pose) {
|
||||||
|
this.currentPose = pose;
|
||||||
|
this.lastLeftTicks = leftEncoder.getTicks();
|
||||||
|
this.lastRightTicks = rightEncoder.getTicks();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pose2D getPose() {
|
||||||
|
int leftTicks = leftEncoder.getTicks();
|
||||||
|
int rightTicks = rightEncoder.getTicks();
|
||||||
|
int deltaLeft = leftTicks - lastLeftTicks;
|
||||||
|
int deltaRight = rightTicks - lastRightTicks;
|
||||||
|
|
||||||
|
double ticksPerInch = leftEncoder.getTicksPerRevolution() / (Math.PI * wheelDiameter);
|
||||||
|
double leftDist = deltaLeft / ticksPerInch;
|
||||||
|
double rightDist = deltaRight / ticksPerInch;
|
||||||
|
|
||||||
|
lastLeftTicks = leftTicks;
|
||||||
|
lastRightTicks = rightTicks;
|
||||||
|
|
||||||
|
double distanceMoved = (leftDist + rightDist) / 2.0;
|
||||||
|
double angleChanged = (rightDist - leftDist) / trackWidth;
|
||||||
|
double midHeading = currentPose.heading + Math.toDegrees(angleChanged / 2);
|
||||||
|
|
||||||
|
double deltaX = distanceMoved * Math.cos(Math.toRadians(midHeading));
|
||||||
|
double deltaY = distanceMoved * Math.sin(Math.toRadians(midHeading));
|
||||||
|
|
||||||
|
currentPose = new Pose2D(
|
||||||
|
currentPose.x + deltaX,
|
||||||
|
currentPose.y + deltaY,
|
||||||
|
currentPose.heading + Math.toDegrees(angleChanged)
|
||||||
|
);
|
||||||
|
|
||||||
|
return currentPose;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void correctPose(Pose2D pose) { this.currentPose = pose; }
|
||||||
|
public void correctHeading(double heading) {
|
||||||
|
this.currentPose = new Pose2D(currentPose.x, currentPose.y, heading);
|
||||||
|
}
|
||||||
|
public boolean isWorking() {
|
||||||
|
return leftEncoder.isConnected() && rightEncoder.isConnected();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
public class Pose2D {
|
||||||
|
public final double x, y, heading;
|
||||||
|
|
||||||
|
public Pose2D(double x, double y, double heading) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
this.heading = normalizeAngle(heading);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static double normalizeAngle(double degrees) {
|
||||||
|
double angle = degrees % 360;
|
||||||
|
if (angle > 180) angle -= 360;
|
||||||
|
else if (angle < -180) angle += 360;
|
||||||
|
return angle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double distanceTo(Pose2D other) {
|
||||||
|
double dx = other.x - this.x;
|
||||||
|
double dy = other.y - this.y;
|
||||||
|
return Math.sqrt(dx * dx + dy * dy);
|
||||||
|
}
|
||||||
|
|
||||||
|
public double angleTo(Pose2D other) {
|
||||||
|
return Math.toDegrees(Math.atan2(other.y - this.y, other.x - this.x));
|
||||||
|
}
|
||||||
|
|
||||||
|
public double headingDifferenceTo(Pose2D other) {
|
||||||
|
return normalizeAngle(angleTo(other) - this.heading);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pose2D translate(double dx, double dy) {
|
||||||
|
return new Pose2D(this.x + dx, this.y + dy, this.heading);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pose2D rotate(double degrees) {
|
||||||
|
return new Pose2D(this.x, this.y, this.heading + degrees);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isWithinField() {
|
||||||
|
return x >= 0 && x <= FieldGrid.FIELD_SIZE && y >= 0 && y <= FieldGrid.FIELD_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GridCell toGridCell() {
|
||||||
|
return FieldGrid.poseToCell(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return String.format("Pose(%.1f\", %.1f\", %.1f°)", x, y, heading);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
public class RobotLocalizer {
|
||||||
|
|
||||||
|
private final OdometryTracker odometry;
|
||||||
|
private final ImuLocalizer imuLocalizer;
|
||||||
|
private final VisionLocalizer visionLocalizer;
|
||||||
|
private Pose2D currentPose;
|
||||||
|
private long lastUpdateTime;
|
||||||
|
|
||||||
|
public RobotLocalizer(OdometryTracker odometry, ImuLocalizer imu, VisionLocalizer vision) {
|
||||||
|
this.odometry = odometry;
|
||||||
|
this.imuLocalizer = imu;
|
||||||
|
this.visionLocalizer = vision;
|
||||||
|
this.currentPose = new Pose2D(0, 0, 0);
|
||||||
|
this.lastUpdateTime = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInitialPose(Pose2D pose) {
|
||||||
|
this.currentPose = pose;
|
||||||
|
this.odometry.setPose(pose);
|
||||||
|
this.lastUpdateTime = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update() {
|
||||||
|
Pose2D odometryPose = odometry.getPose();
|
||||||
|
Double imuHeading = imuLocalizer.getHeading();
|
||||||
|
Pose2D visionPose = visionLocalizer.getPose();
|
||||||
|
|
||||||
|
if (visionPose != null) {
|
||||||
|
currentPose = visionPose;
|
||||||
|
odometry.correctPose(visionPose);
|
||||||
|
} else if (imuHeading != null) {
|
||||||
|
currentPose = new Pose2D(odometryPose.x, odometryPose.y, imuHeading);
|
||||||
|
odometry.correctHeading(imuHeading);
|
||||||
|
} else {
|
||||||
|
currentPose = odometryPose;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentPose = FieldGrid.clampToField(currentPose);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pose2D getCurrentPose() { return currentPose; }
|
||||||
|
public GridCell getCurrentCell() { return FieldGrid.poseToCell(currentPose); }
|
||||||
|
|
||||||
|
public SensorHealth getSensorHealth() {
|
||||||
|
return new SensorHealth(
|
||||||
|
odometry.isWorking(),
|
||||||
|
imuLocalizer.isWorking(),
|
||||||
|
visionLocalizer.isWorking()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getConfidence() {
|
||||||
|
SensorHealth h = getSensorHealth();
|
||||||
|
if (h.visionWorking) return 1.0;
|
||||||
|
if (h.imuWorking) return 0.7;
|
||||||
|
if (h.odometryWorking) return 0.4;
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class SensorHealth {
|
||||||
|
public final boolean odometryWorking, imuWorking, visionWorking;
|
||||||
|
public SensorHealth(boolean o, boolean i, boolean v) {
|
||||||
|
odometryWorking = o; imuWorking = i; visionWorking = v;
|
||||||
|
}
|
||||||
|
public int getSensorCount() {
|
||||||
|
return (odometryWorking ? 1 : 0) + (imuWorking ? 1 : 0) + (visionWorking ? 1 : 0);
|
||||||
|
}
|
||||||
|
public String getStatus() {
|
||||||
|
int c = getSensorCount();
|
||||||
|
if (c == 3) return "Excellent";
|
||||||
|
if (c == 2) return "Good";
|
||||||
|
if (c == 1) return "Degraded";
|
||||||
|
return "Critical";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
import robot.hardware.VisionCamera;
|
||||||
|
|
||||||
|
public class VisionLocalizer {
|
||||||
|
private final VisionCamera camera;
|
||||||
|
private Pose2D lastVisionPose;
|
||||||
|
private long lastUpdateTime;
|
||||||
|
|
||||||
|
public VisionLocalizer(VisionCamera camera) {
|
||||||
|
this.camera = camera;
|
||||||
|
this.lastVisionPose = null;
|
||||||
|
this.lastUpdateTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pose2D getPose() {
|
||||||
|
if (!camera.isConnected()) return null;
|
||||||
|
|
||||||
|
Pose2D detected = camera.detectPose();
|
||||||
|
if (detected != null) {
|
||||||
|
lastVisionPose = detected;
|
||||||
|
lastUpdateTime = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
return lastVisionPose;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTimeSinceLastUpdate() {
|
||||||
|
if (lastUpdateTime == 0) return Long.MAX_VALUE;
|
||||||
|
return System.currentTimeMillis() - lastUpdateTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isWorking() {
|
||||||
|
return camera.isConnected() && getTimeSinceLastUpdate() < 10000;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
public class MockEncoder implements Encoder {
|
||||||
|
private int ticks = 0;
|
||||||
|
private boolean connected = true;
|
||||||
|
|
||||||
|
public int getTicks() { return ticks; }
|
||||||
|
public int getTicksPerRevolution() { return 1000; }
|
||||||
|
public boolean isConnected() { return connected; }
|
||||||
|
public void reset() { ticks = 0; }
|
||||||
|
|
||||||
|
public void setTicks(int t) { ticks = t; }
|
||||||
|
public void addTicks(int delta) { ticks += delta; }
|
||||||
|
public void setConnected(boolean c) { connected = c; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
public class MockGyroSensor implements GyroSensor {
|
||||||
|
private double heading = 0;
|
||||||
|
private boolean connected = true;
|
||||||
|
private boolean calibrated = true;
|
||||||
|
|
||||||
|
public double getHeading() { return heading; }
|
||||||
|
public boolean isConnected() { return connected; }
|
||||||
|
public void calibrate() { calibrated = true; }
|
||||||
|
public boolean isCalibrated() { return calibrated; }
|
||||||
|
|
||||||
|
public void setHeading(double h) { heading = h; }
|
||||||
|
public void setConnected(boolean c) { connected = c; }
|
||||||
|
public void setCalibrated(boolean c) { calibrated = c; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
import robot.localization.Pose2D;
|
||||||
|
|
||||||
|
public class MockVisionCamera implements VisionCamera {
|
||||||
|
private Pose2D pose = null;
|
||||||
|
private boolean connected = true;
|
||||||
|
|
||||||
|
public Pose2D detectPose() { return pose; }
|
||||||
|
public boolean isConnected() { return connected; }
|
||||||
|
|
||||||
|
public void setPose(Pose2D p) { pose = p; }
|
||||||
|
public void setConnected(boolean c) { connected = c; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class GridCellTest {
|
||||||
|
@Test
|
||||||
|
void testCellCreation() {
|
||||||
|
GridCell cell = new GridCell(5, 7);
|
||||||
|
assertEquals(5, cell.x);
|
||||||
|
assertEquals(7, cell.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testInvalidCell() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new GridCell(-1, 5));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new GridCell(5, 12));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDistance() {
|
||||||
|
GridCell a = new GridCell(0, 0);
|
||||||
|
GridCell b = new GridCell(3, 4);
|
||||||
|
assertEquals(60.0, a.distanceTo(b), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAngle() {
|
||||||
|
GridCell origin = new GridCell(0, 0);
|
||||||
|
GridCell right = new GridCell(1, 0);
|
||||||
|
GridCell up = new GridCell(0, 1);
|
||||||
|
assertEquals(0.0, origin.angleTo(right), 0.001);
|
||||||
|
assertEquals(90.0, origin.angleTo(up), 0.001);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class Pose2DTest {
|
||||||
|
@Test
|
||||||
|
void testCreation() {
|
||||||
|
Pose2D pose = new Pose2D(24.0, 36.0, 45.0);
|
||||||
|
assertEquals(24.0, pose.x, 0.001);
|
||||||
|
assertEquals(36.0, pose.y, 0.001);
|
||||||
|
assertEquals(45.0, pose.heading, 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testNormalization() {
|
||||||
|
Pose2D p1 = new Pose2D(0, 0, 370);
|
||||||
|
assertEquals(10.0, p1.heading, 0.001);
|
||||||
|
|
||||||
|
Pose2D p2 = new Pose2D(0, 0, -190);
|
||||||
|
assertEquals(170.0, p2.heading, 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDistance() {
|
||||||
|
Pose2D a = new Pose2D(0, 0, 0);
|
||||||
|
Pose2D b = new Pose2D(3, 4, 0);
|
||||||
|
assertEquals(5.0, a.distanceTo(b), 0.001);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package robot.localization;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import robot.hardware.*;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class SensorFusionTest {
|
||||||
|
@Test
|
||||||
|
void testVisionCorrection() {
|
||||||
|
MockEncoder left = new MockEncoder();
|
||||||
|
MockEncoder right = new MockEncoder();
|
||||||
|
MockGyroSensor gyro = new MockGyroSensor();
|
||||||
|
MockVisionCamera camera = new MockVisionCamera();
|
||||||
|
|
||||||
|
OdometryTracker odometry = new OdometryTracker(left, right);
|
||||||
|
ImuLocalizer imu = new ImuLocalizer(gyro);
|
||||||
|
VisionLocalizer vision = new VisionLocalizer(camera);
|
||||||
|
|
||||||
|
RobotLocalizer localizer = new RobotLocalizer(odometry, imu, vision);
|
||||||
|
localizer.setInitialPose(new Pose2D(0, 0, 0));
|
||||||
|
|
||||||
|
camera.setPose(new Pose2D(12, 12, 0));
|
||||||
|
localizer.update();
|
||||||
|
|
||||||
|
Pose2D pose = localizer.getCurrentPose();
|
||||||
|
assertEquals(12.0, pose.x, 0.1);
|
||||||
|
assertEquals(12.0, pose.y, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGracefulDegradation() {
|
||||||
|
MockEncoder left = new MockEncoder();
|
||||||
|
MockEncoder right = new MockEncoder();
|
||||||
|
MockGyroSensor gyro = new MockGyroSensor();
|
||||||
|
MockVisionCamera camera = new MockVisionCamera();
|
||||||
|
|
||||||
|
// Set a pose so vision is actually "working" (not just connected)
|
||||||
|
camera.setPose(new Pose2D(12, 12, 0));
|
||||||
|
|
||||||
|
OdometryTracker odometry = new OdometryTracker(left, right);
|
||||||
|
ImuLocalizer imu = new ImuLocalizer(gyro);
|
||||||
|
VisionLocalizer vision = new VisionLocalizer(camera);
|
||||||
|
|
||||||
|
RobotLocalizer localizer = new RobotLocalizer(odometry, imu, vision);
|
||||||
|
localizer.update(); // Need to update to actually use vision
|
||||||
|
|
||||||
|
assertEquals(1.0, localizer.getConfidence(), 0.01);
|
||||||
|
|
||||||
|
camera.setConnected(false);
|
||||||
|
localizer.update();
|
||||||
|
assertEquals(0.7, localizer.getConfidence(), 0.01);
|
||||||
|
|
||||||
|
gyro.setConnected(false);
|
||||||
|
localizer.update();
|
||||||
|
assertEquals(0.4, localizer.getConfidence(), 0.01);
|
||||||
|
}
|
||||||
|
}
|
||||||
199
templates/testing/ARCHITECTURE.md
Normal file
199
templates/testing/ARCHITECTURE.md
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
# Weevil Motor Cycle Demo - Architecture Overview
|
||||||
|
|
||||||
|
## What This Example Demonstrates
|
||||||
|
|
||||||
|
This is a minimal but complete FTC robot project showing how Weevil enables:
|
||||||
|
1. Clean separation of business logic from hardware
|
||||||
|
2. Unit testing on Windows JRE without FTC SDK
|
||||||
|
3. Professional software architecture for robotics
|
||||||
|
|
||||||
|
## The Problem Weevil Solves
|
||||||
|
|
||||||
|
Traditional FTC projects:
|
||||||
|
- Force you to edit SDK files directly (TeamCode folder)
|
||||||
|
- Mix hardware dependencies with business logic
|
||||||
|
- Make testing nearly impossible without a physical robot
|
||||||
|
- Create monolithic OpMode classes that are hard to maintain
|
||||||
|
|
||||||
|
## Weevil's Solution
|
||||||
|
|
||||||
|
### Three-Layer Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────┐
|
||||||
|
│ OpMode (Integration Layer) │ ← Only runs on robot
|
||||||
|
│ - Wires everything together │
|
||||||
|
└─────────────────────────────────┘
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────┐
|
||||||
|
│ Business Logic Layer │ ← Runs everywhere!
|
||||||
|
│ - MotorCycler │ Tests on Windows JRE
|
||||||
|
│ - Pure Java, no FTC deps │
|
||||||
|
└─────────────────────────────────┘
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────┐
|
||||||
|
│ Hardware Abstraction Layer │ ← Interface + implementations
|
||||||
|
│ - MotorController (interface) │
|
||||||
|
│ - FtcMotorController (robot) │
|
||||||
|
│ - MockMotorController (tests) │
|
||||||
|
└─────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## File Breakdown
|
||||||
|
|
||||||
|
### Hardware Abstraction (`src/main/java/robot/hardware/`)
|
||||||
|
|
||||||
|
**MotorController.java** (17 lines)
|
||||||
|
- Interface defining motor operations
|
||||||
|
- No FTC SDK dependencies
|
||||||
|
- Default methods for convenience
|
||||||
|
|
||||||
|
**FtcMotorController.java** (19 lines)
|
||||||
|
- Wraps FTC SDK's DcMotor
|
||||||
|
- Only compiled when building for robot
|
||||||
|
- Implements MotorController interface
|
||||||
|
|
||||||
|
**MockMotorController.java** (27 lines - in test/)
|
||||||
|
- Test implementation
|
||||||
|
- Tracks state for assertions
|
||||||
|
- No hardware required
|
||||||
|
|
||||||
|
### Business Logic (`src/main/java/robot/subsystems/`)
|
||||||
|
|
||||||
|
**MotorCycler.java** (95 lines)
|
||||||
|
- Pure Java state machine
|
||||||
|
- Time-based motor cycling
|
||||||
|
- Zero FTC SDK dependencies
|
||||||
|
- Fully testable in isolation
|
||||||
|
|
||||||
|
Core design:
|
||||||
|
```java
|
||||||
|
public void update(long currentTimeMs) {
|
||||||
|
long elapsed = currentTimeMs - stateStartTime;
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
case OFF:
|
||||||
|
if (elapsed >= offDurationMs) {
|
||||||
|
motor.setPower(motorPower);
|
||||||
|
state = ON;
|
||||||
|
stateStartTime = currentTimeMs;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case ON:
|
||||||
|
if (elapsed >= onDurationMs) {
|
||||||
|
motor.setPower(0.0);
|
||||||
|
state = OFF;
|
||||||
|
stateStartTime = currentTimeMs;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Integration (`src/main/java/robot/opmodes/`)
|
||||||
|
|
||||||
|
**MotorCycleOpMode.java** (44 lines)
|
||||||
|
- FTC OpMode
|
||||||
|
- Connects hardware to logic
|
||||||
|
- Minimal glue code
|
||||||
|
|
||||||
|
### Tests (`src/test/java/`)
|
||||||
|
|
||||||
|
**MotorCyclerTest.java** (136 lines)
|
||||||
|
- 9 comprehensive unit tests
|
||||||
|
- Tests timing, state transitions, edge cases
|
||||||
|
- Runs in milliseconds on PC
|
||||||
|
- No robot or FTC SDK required
|
||||||
|
|
||||||
|
Test coverage:
|
||||||
|
- Initialization
|
||||||
|
- State transitions (OFF→ON, ON→OFF)
|
||||||
|
- Full cycle sequences
|
||||||
|
- Time tracking
|
||||||
|
- Stop functionality
|
||||||
|
- Edge cases (default power, tiny power values)
|
||||||
|
|
||||||
|
## Development Workflow
|
||||||
|
|
||||||
|
### 1. Write Code Locally
|
||||||
|
Edit files in `src/main/java/robot/` - your IDE works perfectly
|
||||||
|
|
||||||
|
### 2. Test Immediately
|
||||||
|
```bash
|
||||||
|
gradlew test
|
||||||
|
```
|
||||||
|
- Runs in seconds on Windows
|
||||||
|
- No robot connection needed
|
||||||
|
- Full JUnit reports
|
||||||
|
|
||||||
|
### 3. Deploy to Robot
|
||||||
|
```bash
|
||||||
|
build.bat # Compiles everything, builds APK
|
||||||
|
deploy.bat # Copies APK to robot
|
||||||
|
```
|
||||||
|
|
||||||
|
## Why This Architecture Matters
|
||||||
|
|
||||||
|
### For Students
|
||||||
|
- Learn professional software engineering
|
||||||
|
- Write testable code
|
||||||
|
- Build confidence through tests
|
||||||
|
- Debug logic without hardware
|
||||||
|
|
||||||
|
### For Teams
|
||||||
|
- Multiple programmers can work simultaneously
|
||||||
|
- Test changes before robot practice
|
||||||
|
- Catch bugs early (compile-time, not drive-time)
|
||||||
|
- Build more complex robots with confidence
|
||||||
|
|
||||||
|
### For Competitions
|
||||||
|
- More reliable code
|
||||||
|
- Faster iteration cycles
|
||||||
|
- Better debugging capabilities
|
||||||
|
- Professional development practices
|
||||||
|
|
||||||
|
## Technical Benefits
|
||||||
|
|
||||||
|
1. **Dependency Injection**: MotorCycler receives MotorController through constructor
|
||||||
|
2. **Interface Segregation**: Clean interface with single responsibility
|
||||||
|
3. **Testability**: Mock implementations enable isolated testing
|
||||||
|
4. **Separation of Concerns**: Hardware, logic, and integration are distinct
|
||||||
|
5. **Open/Closed Principle**: Easy to extend without modifying core logic
|
||||||
|
|
||||||
|
## Comparison to Traditional FTC
|
||||||
|
|
||||||
|
| Traditional FTC | Weevil Architecture |
|
||||||
|
|----------------|---------------------|
|
||||||
|
| Edit SDK files directly | Your code stays separate |
|
||||||
|
| Mix hardware and logic | Clean separation |
|
||||||
|
| No unit tests | Comprehensive tests |
|
||||||
|
| Debug on robot only | Debug on PC first |
|
||||||
|
| Monolithic OpModes | Modular subsystems |
|
||||||
|
| Hard to maintain | Easy to understand |
|
||||||
|
|
||||||
|
## Extending This Example
|
||||||
|
|
||||||
|
Want to add more features? Keep the pattern:
|
||||||
|
|
||||||
|
1. **Add Interface** in `hardware/` (e.g., `ServoController`)
|
||||||
|
2. **Implement Logic** in `subsystems/` (e.g., `ArmController`)
|
||||||
|
3. **Create Mock** in `test/hardware/`
|
||||||
|
4. **Write Tests** in `test/subsystems/`
|
||||||
|
5. **Wire in OpMode** - just a few lines of glue code
|
||||||
|
|
||||||
|
The architecture scales from simple examples like this to complex multi-subsystem robots.
|
||||||
|
|
||||||
|
## Real-World Application
|
||||||
|
|
||||||
|
This demo shows the fundamentals. Real robots would have:
|
||||||
|
- Multiple subsystems (drivetrain, arm, intake, etc.)
|
||||||
|
- Command pattern for complex sequences
|
||||||
|
- State machines for autonomous
|
||||||
|
- Sensor integration (same abstraction pattern)
|
||||||
|
- Configuration management
|
||||||
|
|
||||||
|
All testable. All maintainable. All professional.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**This is what Weevil enables: writing robot code like professional software.**
|
||||||
975
templates/testing/DESIGN_AND_TEST_PLAN.md
Normal file
975
templates/testing/DESIGN_AND_TEST_PLAN.md
Normal file
@@ -0,0 +1,975 @@
|
|||||||
|
# FTC Robot System Design & Test Plan
|
||||||
|
|
||||||
|
## Document Overview
|
||||||
|
|
||||||
|
This document defines the system architecture, component responsibilities, and comprehensive test strategy for the FTC robot project. It serves as the authoritative reference for understanding how the system is structured and how tests validate each component.
|
||||||
|
|
||||||
|
**Version:** 1.0
|
||||||
|
**Last Updated:** February 2026
|
||||||
|
**Status:** Implementation Complete, All Tests Passing
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [System Architecture](#system-architecture)
|
||||||
|
2. [Component Specifications](#component-specifications)
|
||||||
|
3. [Interface Contracts](#interface-contracts)
|
||||||
|
4. [Test Strategy](#test-strategy)
|
||||||
|
5. [Test Coverage Matrix](#test-coverage-matrix)
|
||||||
|
6. [Test Cases by Component](#test-cases-by-component)
|
||||||
|
7. [Integration Test Scenarios](#integration-test-scenarios)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## System Architecture
|
||||||
|
|
||||||
|
### High-Level System Diagram
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────────┐
|
||||||
|
│ FTC ROBOT SYSTEM │
|
||||||
|
└─────────────────────────────────────────────────────────────────┘
|
||||||
|
|
||||||
|
┌──────────────────────┐
|
||||||
|
│ OpMode Layer │ ← FTC Integration
|
||||||
|
│ (Robot Only) │
|
||||||
|
└──────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────┴─────────────────────┐
|
||||||
|
│ │
|
||||||
|
┌───────▼───────┐ ┌──────────▼─────────┐ ┌───────▼────────┐
|
||||||
|
│ MotorCycler │ │ WallApproach │ │ TurnController │
|
||||||
|
│ Subsystem │ │ Subsystem │ │ Subsystem │
|
||||||
|
└───────┬───────┘ └────────┬───────────┘ └────────┬───────┘
|
||||||
|
│ │ │
|
||||||
|
│ ┌───────┴────────┐ │
|
||||||
|
│ │ │ │
|
||||||
|
▼ ▼ ▼ ▼
|
||||||
|
┌──────────────────────────────────────────────────────────┐
|
||||||
|
│ Hardware Abstraction Layer │
|
||||||
|
│ (Interfaces - No FTC Dependencies) │
|
||||||
|
│ │
|
||||||
|
│ • MotorController • DistanceSensor • GyroSensor │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
│ │ │
|
||||||
|
└───────────────────┴────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────────────────┐
|
||||||
|
│ │
|
||||||
|
TEST MODE ROBOT MODE
|
||||||
|
│ │
|
||||||
|
┌───────▼───────┐ ┌─────────▼─────────┐
|
||||||
|
│ Test Mocks │ │ FTC Wrappers │
|
||||||
|
│ │ │ │
|
||||||
|
│ • MockMotor │ │ • FtcMotor │
|
||||||
|
│ • MockDist │ │ • FtcDistance │
|
||||||
|
│ • MockGyro │ │ • FtcGyro │
|
||||||
|
│ │ │ │
|
||||||
|
│ (Variables) │ │ (Real Hardware) │
|
||||||
|
└───────────────┘ └───────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Layer Responsibilities
|
||||||
|
|
||||||
|
| Layer | Purpose | Dependencies | Testability |
|
||||||
|
|-------|---------|--------------|-------------|
|
||||||
|
| **OpMode** | FTC SDK integration, hardware initialization | FTC SDK | Not tested (trivial glue code) |
|
||||||
|
| **Subsystems** | Robot behavior logic, state machines, control | Interfaces only | ✅ 100% tested |
|
||||||
|
| **Interfaces** | Hardware abstraction contracts | None (pure interfaces) | ✅ Contracts verified |
|
||||||
|
| **FTC Wrappers** | Thin hardware adapters | FTC SDK | Not tested (3-5 line wrappers) |
|
||||||
|
| **Test Mocks** | Test doubles for hardware | Interfaces only | ✅ Used in all tests |
|
||||||
|
|
||||||
|
### Data Flow: Test Mode vs Robot Mode
|
||||||
|
|
||||||
|
```
|
||||||
|
TEST MODE: ROBOT MODE:
|
||||||
|
═══════════ ════════════
|
||||||
|
|
||||||
|
Test Case OpMode.loop()
|
||||||
|
↓ ↓
|
||||||
|
Set Mock State Read Hardware Map
|
||||||
|
↓ ↓
|
||||||
|
Call Subsystem FTC Wrapper
|
||||||
|
↓ ↓
|
||||||
|
Subsystem Logic ←──────── SAME CODE ──────────→ Subsystem Logic
|
||||||
|
↓ ↓
|
||||||
|
Call Interface Method Call Interface Method
|
||||||
|
↓ ↓
|
||||||
|
Mock Returns Value FTC Wrapper Reads I2C/PWM
|
||||||
|
↓ ↓
|
||||||
|
Subsystem Continues Subsystem Continues
|
||||||
|
↓ ↓
|
||||||
|
Assert Result Robot Moves
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Component Specifications
|
||||||
|
|
||||||
|
### 1. MotorCycler Subsystem
|
||||||
|
|
||||||
|
**Purpose:** Demonstrate time-based control and state machines
|
||||||
|
|
||||||
|
**Responsibilities:**
|
||||||
|
- Cycle motor ON/OFF at configurable intervals
|
||||||
|
- Track elapsed time in current state
|
||||||
|
- Provide state information for telemetry
|
||||||
|
- Support start/stop control
|
||||||
|
|
||||||
|
**States:**
|
||||||
|
```
|
||||||
|
┌──────┐
|
||||||
|
│ OFF │ ←──┐
|
||||||
|
└───┬──┘ │
|
||||||
|
│ │
|
||||||
|
[offDurationMs elapsed]
|
||||||
|
│ │
|
||||||
|
▼ │
|
||||||
|
┌──────┐ │
|
||||||
|
│ ON │ ──┘
|
||||||
|
└──────┘
|
||||||
|
[onDurationMs elapsed]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configuration:**
|
||||||
|
- `onDurationMs`: Time to stay ON (default: 2000ms)
|
||||||
|
- `offDurationMs`: Time to stay OFF (default: 1000ms)
|
||||||
|
- `motorPower`: Power level when ON (default: 0.5)
|
||||||
|
|
||||||
|
**Dependencies:**
|
||||||
|
- `MotorController` (interface)
|
||||||
|
|
||||||
|
**Key Methods:**
|
||||||
|
- `init()`: Initialize to OFF state
|
||||||
|
- `update(long currentTimeMs)`: Update state based on elapsed time
|
||||||
|
- `stop()`: Force stop and reset to OFF
|
||||||
|
- `getState()`: Current state (ON/OFF)
|
||||||
|
- `getTimeInState(long currentTime)`: Time spent in current state
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. WallApproach Subsystem
|
||||||
|
|
||||||
|
**Purpose:** Safely approach obstacles using distance feedback with speed ramping
|
||||||
|
|
||||||
|
**Responsibilities:**
|
||||||
|
- Drive toward wall at safe speed
|
||||||
|
- Slow down as approaching target distance
|
||||||
|
- Emergency stop if too close
|
||||||
|
- Handle sensor failures gracefully
|
||||||
|
- Coordinate left/right motor speeds
|
||||||
|
|
||||||
|
**States:**
|
||||||
|
```
|
||||||
|
┌──────┐
|
||||||
|
│ INIT │
|
||||||
|
└───┬──┘
|
||||||
|
│ start()
|
||||||
|
▼
|
||||||
|
┌────────────┐
|
||||||
|
│ APPROACHING│ ←────────┐
|
||||||
|
└─────┬──────┘ │
|
||||||
|
│ │
|
||||||
|
[distance < 30cm] [distance > 30cm]
|
||||||
|
│ │
|
||||||
|
▼ │
|
||||||
|
┌────────┐ │
|
||||||
|
│ SLOWING│ ─────────────┘
|
||||||
|
└────┬───┘
|
||||||
|
│
|
||||||
|
[distance < 10cm]
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────┐
|
||||||
|
│ STOPPED │
|
||||||
|
└─────────┘
|
||||||
|
|
||||||
|
[sensor invalid]
|
||||||
|
↓
|
||||||
|
┌────────┐
|
||||||
|
│ ERROR │
|
||||||
|
└────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configuration:**
|
||||||
|
- `STOP_DISTANCE_CM`: Target stop distance (10cm)
|
||||||
|
- `SLOW_DISTANCE_CM`: Begin slowing threshold (30cm)
|
||||||
|
- `FAST_SPEED`: Full speed power (0.6)
|
||||||
|
- `SLOW_SPEED`: Reduced speed power (0.2)
|
||||||
|
|
||||||
|
**Dependencies:**
|
||||||
|
- `DistanceSensor` (interface)
|
||||||
|
- `MotorController` x2 (left/right)
|
||||||
|
|
||||||
|
**Key Methods:**
|
||||||
|
- `start()`: Begin approach sequence
|
||||||
|
- `update()`: State machine update
|
||||||
|
- `stop()`: Emergency stop
|
||||||
|
- `getState()`: Current state
|
||||||
|
- `getCurrentDistance()`: Current sensor reading
|
||||||
|
- `hasSensorError()`: Error flag status
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. TurnController Subsystem
|
||||||
|
|
||||||
|
**Purpose:** Rotate robot to target heading using gyro feedback with proportional control
|
||||||
|
|
||||||
|
**Responsibilities:**
|
||||||
|
- Turn to specified heading (0-359°)
|
||||||
|
- Choose shortest rotation path
|
||||||
|
- Apply proportional control (faster when far from target)
|
||||||
|
- Handle 360° wraparound math
|
||||||
|
- Detect completion within tolerance
|
||||||
|
|
||||||
|
**States:**
|
||||||
|
```
|
||||||
|
┌──────┐
|
||||||
|
│ IDLE │
|
||||||
|
└───┬──┘
|
||||||
|
│ turnTo(heading)
|
||||||
|
▼
|
||||||
|
┌─────────┐
|
||||||
|
│ TURNING │
|
||||||
|
└────┬────┘
|
||||||
|
│
|
||||||
|
[error < tolerance]
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────┐
|
||||||
|
│ COMPLETE │
|
||||||
|
└──────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Control Algorithm:**
|
||||||
|
```
|
||||||
|
error = shortestAngle(current, target)
|
||||||
|
power = error × KP
|
||||||
|
power = clamp(power, MIN_TURN_POWER, MAX_TURN_POWER)
|
||||||
|
leftMotor = power
|
||||||
|
rightMotor = -power
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configuration:**
|
||||||
|
- `HEADING_TOLERANCE`: Success threshold (2.0°)
|
||||||
|
- `MIN_TURN_POWER`: Minimum power (0.15)
|
||||||
|
- `MAX_TURN_POWER`: Maximum power (0.5)
|
||||||
|
- `KP`: Proportional gain (0.02)
|
||||||
|
|
||||||
|
**Dependencies:**
|
||||||
|
- `GyroSensor` (interface)
|
||||||
|
- `MotorController` x2 (left/right)
|
||||||
|
|
||||||
|
**Key Methods:**
|
||||||
|
- `turnTo(double targetDegrees)`: Start turn
|
||||||
|
- `update()`: Control loop update
|
||||||
|
- `stop()`: Halt turning
|
||||||
|
- `getState()`: Current state
|
||||||
|
- `getHeadingError()`: Degrees from target
|
||||||
|
- `getCurrentHeading()`: Current gyro reading
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Interface Contracts
|
||||||
|
|
||||||
|
### MotorController Interface
|
||||||
|
|
||||||
|
**Contract:** Abstract motor control with power setting and reading
|
||||||
|
|
||||||
|
```java
|
||||||
|
public interface MotorController {
|
||||||
|
/**
|
||||||
|
* Set motor power.
|
||||||
|
* @param power Range: -1.0 (full reverse) to +1.0 (full forward)
|
||||||
|
*/
|
||||||
|
void setPower(double power);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current motor power setting.
|
||||||
|
* @return Current power (-1.0 to +1.0)
|
||||||
|
*/
|
||||||
|
double getPower();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Implementations:**
|
||||||
|
- `FtcMotorController`: Wraps `DcMotor` from FTC SDK
|
||||||
|
- `MockMotorController`: Test double, stores power in variable
|
||||||
|
|
||||||
|
**Invariants:**
|
||||||
|
- Power values should be clamped to [-1.0, 1.0]
|
||||||
|
- `getPower()` should return last value set by `setPower()`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### DistanceSensor Interface
|
||||||
|
|
||||||
|
**Contract:** Abstract distance measurement
|
||||||
|
|
||||||
|
```java
|
||||||
|
public interface DistanceSensor {
|
||||||
|
/**
|
||||||
|
* Get distance reading in centimeters.
|
||||||
|
* @return Distance in cm, or -1 if error
|
||||||
|
*/
|
||||||
|
double getDistanceCm();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if sensor has valid data.
|
||||||
|
* @return true if working properly
|
||||||
|
*/
|
||||||
|
boolean isValid();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Implementations:**
|
||||||
|
- `FtcDistanceSensor`: Wraps REV 2m Distance Sensor
|
||||||
|
- `MockDistanceSensor`: Test double, configurable distance/noise/failure
|
||||||
|
|
||||||
|
**Invariants:**
|
||||||
|
- Valid readings should be in range [0, 8190] cm
|
||||||
|
- `isValid()` returns false when `getDistanceCm()` returns -1
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### GyroSensor Interface
|
||||||
|
|
||||||
|
**Contract:** Abstract heading measurement
|
||||||
|
|
||||||
|
```java
|
||||||
|
public interface GyroSensor {
|
||||||
|
/**
|
||||||
|
* Get current heading.
|
||||||
|
* @return Heading in degrees (0-359)
|
||||||
|
*/
|
||||||
|
double getHeading();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset heading to zero.
|
||||||
|
*/
|
||||||
|
void reset();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check calibration status.
|
||||||
|
* @return true if calibrated and ready
|
||||||
|
*/
|
||||||
|
boolean isCalibrated();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Implementations:**
|
||||||
|
- `FtcGyroSensor`: Wraps REV Hub IMU
|
||||||
|
- `MockGyroSensor`: Test double, configurable heading/drift
|
||||||
|
|
||||||
|
**Invariants:**
|
||||||
|
- Heading should be normalized to [0, 360) range
|
||||||
|
- `isCalibrated()` must be true before readings are reliable
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test Strategy
|
||||||
|
|
||||||
|
### Testing Pyramid
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────┐
|
||||||
|
│ E2E │ (5 tests)
|
||||||
|
│ System │ - Complete missions
|
||||||
|
└──────────┘ - Multi-subsystem
|
||||||
|
╱ ╲
|
||||||
|
╱ ╲
|
||||||
|
╱ Integration ╲ (3 tests)
|
||||||
|
╱ (Component) ╲ - Realistic scenarios
|
||||||
|
╱ ╲- Noise, variance
|
||||||
|
└──────────────────────┘
|
||||||
|
╱ ╲
|
||||||
|
╱ ╲
|
||||||
|
╱ Unit Tests ╲ (37 tests)
|
||||||
|
╱ (Isolated Behaviors) ╲ - State transitions
|
||||||
|
╱ ╲- Calculations
|
||||||
|
└──────────────────────────────────┘- Edge cases
|
||||||
|
```
|
||||||
|
|
||||||
|
### Test Levels
|
||||||
|
|
||||||
|
| Level | Count | Purpose | Execution Time |
|
||||||
|
|-------|-------|---------|----------------|
|
||||||
|
| **Unit** | 37 | Test individual component behaviors in isolation | < 1 second |
|
||||||
|
| **Integration** | 3 | Test realistic scenarios with noise/variance | < 0.5 seconds |
|
||||||
|
| **System** | 5 | Test complete missions with multiple subsystems | < 1 second |
|
||||||
|
| **Total** | 45 | Complete validation suite | < 2 seconds |
|
||||||
|
|
||||||
|
### Test Categories
|
||||||
|
|
||||||
|
**Functional Tests:**
|
||||||
|
- State machine transitions
|
||||||
|
- Control algorithms
|
||||||
|
- Calculations and logic
|
||||||
|
- API contracts
|
||||||
|
|
||||||
|
**Non-Functional Tests:**
|
||||||
|
- Edge cases (boundaries, wraparound)
|
||||||
|
- Error handling (sensor failures)
|
||||||
|
- Robustness (noise, drift)
|
||||||
|
- Performance (loop timing)
|
||||||
|
|
||||||
|
**System Tests:**
|
||||||
|
- Complete autonomous sequences
|
||||||
|
- Multi-subsystem coordination
|
||||||
|
- Mission scenarios
|
||||||
|
- Failure recovery
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test Coverage Matrix
|
||||||
|
|
||||||
|
### Coverage by Component
|
||||||
|
|
||||||
|
| Component | Unit Tests | Integration Tests | System Tests | Total | LOC | Coverage |
|
||||||
|
|-----------|------------|-------------------|--------------|-------|-----|----------|
|
||||||
|
| MotorCycler | 8 | 0 | 0 | 8 | 106 | 100% |
|
||||||
|
| WallApproach | 13 | 1 | 0 | 14 | 130 | 100% |
|
||||||
|
| TurnController | 15 | 0 | 0 | 15 | 140 | 100% |
|
||||||
|
| System Integration | 0 | 0 | 5 | 5 | N/A | N/A |
|
||||||
|
| Mock Hardware | 0 | 2 | 3 | 5 | 85 | 100% |
|
||||||
|
| **Totals** | **36** | **3** | **5** | **45** | **461** | **100%** |
|
||||||
|
|
||||||
|
### Coverage by Feature
|
||||||
|
|
||||||
|
| Feature | Test Cases | Status |
|
||||||
|
|---------|------------|--------|
|
||||||
|
| Motor timing control | 8 | ✅ All pass |
|
||||||
|
| Distance-based speed control | 7 | ✅ All pass |
|
||||||
|
| Sensor failure handling | 3 | ✅ All pass |
|
||||||
|
| Turn angle calculations | 6 | ✅ All pass |
|
||||||
|
| Proportional control | 3 | ✅ All pass |
|
||||||
|
| State machine transitions | 12 | ✅ All pass |
|
||||||
|
| Wraparound math (0°↔359°) | 4 | ✅ All pass |
|
||||||
|
| Emergency stops | 3 | ✅ All pass |
|
||||||
|
| Complete missions | 5 | ✅ All pass |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test Cases by Component
|
||||||
|
|
||||||
|
### MotorCycler Tests (8 tests)
|
||||||
|
|
||||||
|
#### Unit Tests
|
||||||
|
|
||||||
|
**MC-01: Initial State Verification**
|
||||||
|
- **Purpose:** Verify subsystem initializes to correct state
|
||||||
|
- **Setup:** Create MotorCycler with 100ms ON, 50ms OFF
|
||||||
|
- **Action:** Call `init()`
|
||||||
|
- **Assert:** State = OFF, motor power = 0.0
|
||||||
|
- **Rationale:** Ensures safe startup (motor off)
|
||||||
|
|
||||||
|
**MC-02: OFF→ON Transition**
|
||||||
|
- **Purpose:** Verify state transition after OFF period
|
||||||
|
- **Setup:** Initialize, advance time 50ms (past OFF duration)
|
||||||
|
- **Action:** Call `update()`
|
||||||
|
- **Assert:** State = ON, motor power = 0.75
|
||||||
|
- **Rationale:** Tests timing logic and state machine
|
||||||
|
|
||||||
|
**MC-03: ON→OFF Transition**
|
||||||
|
- **Purpose:** Verify state transition after ON period
|
||||||
|
- **Setup:** Initialize, advance to ON state, advance 100ms
|
||||||
|
- **Action:** Call `update()`
|
||||||
|
- **Assert:** State = OFF, motor power = 0.0
|
||||||
|
- **Rationale:** Completes cycle verification
|
||||||
|
|
||||||
|
**MC-04: Complete Cycle Sequence**
|
||||||
|
- **Purpose:** Verify multiple state transitions
|
||||||
|
- **Setup:** Initialize, advance through OFF→ON→OFF→ON
|
||||||
|
- **Action:** Multiple `update()` calls with time advancement
|
||||||
|
- **Assert:** Correct states and powers at each step
|
||||||
|
- **Rationale:** Tests sustained operation
|
||||||
|
|
||||||
|
**MC-05: Time-in-State Tracking**
|
||||||
|
- **Purpose:** Verify elapsed time calculation
|
||||||
|
- **Setup:** Initialize, advance 25ms
|
||||||
|
- **Action:** Call `getTimeInState()`
|
||||||
|
- **Assert:** Returns 25ms
|
||||||
|
- **Rationale:** Tests telemetry support
|
||||||
|
|
||||||
|
**MC-06: Emergency Stop**
|
||||||
|
- **Purpose:** Verify manual stop functionality
|
||||||
|
- **Setup:** Initialize, reach ON state
|
||||||
|
- **Action:** Call `stop()`
|
||||||
|
- **Assert:** State = OFF, motor power = 0.0
|
||||||
|
- **Rationale:** Tests safety override
|
||||||
|
|
||||||
|
**MC-07: Default Power Configuration**
|
||||||
|
- **Purpose:** Verify default power value (0.5)
|
||||||
|
- **Setup:** Create with 2-arg constructor
|
||||||
|
- **Action:** Advance to ON state
|
||||||
|
- **Assert:** Motor power = 0.5
|
||||||
|
- **Rationale:** Tests configuration defaults
|
||||||
|
|
||||||
|
**MC-08: Custom Power Configuration**
|
||||||
|
- **Purpose:** Verify custom power setting
|
||||||
|
- **Setup:** Create with power = 0.01
|
||||||
|
- **Action:** Advance to ON state
|
||||||
|
- **Assert:** Motor power = 0.01
|
||||||
|
- **Rationale:** Tests configuration flexibility
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### WallApproach Tests (14 tests)
|
||||||
|
|
||||||
|
#### Unit Tests
|
||||||
|
|
||||||
|
**WA-01: Initial State**
|
||||||
|
- **Purpose:** Verify initialization
|
||||||
|
- **Assert:** State = INIT
|
||||||
|
- **Rationale:** Safe starting condition
|
||||||
|
|
||||||
|
**WA-02: Start Transition**
|
||||||
|
- **Purpose:** Verify start command
|
||||||
|
- **Action:** Call `start()`
|
||||||
|
- **Assert:** State = APPROACHING
|
||||||
|
- **Rationale:** Proper state machine entry
|
||||||
|
|
||||||
|
**WA-03: Full Speed When Far**
|
||||||
|
- **Purpose:** Test speed selection at distance
|
||||||
|
- **Setup:** Distance = 100cm
|
||||||
|
- **Assert:** Motor power = 0.6, State = APPROACHING
|
||||||
|
- **Rationale:** Optimal speed for long distances
|
||||||
|
|
||||||
|
**WA-04: Slow Speed When Near**
|
||||||
|
- **Purpose:** Test speed reduction near target
|
||||||
|
- **Setup:** Distance = 25cm (< 30cm threshold)
|
||||||
|
- **Assert:** Motor power = 0.2, State = SLOWING
|
||||||
|
- **Rationale:** Safety deceleration
|
||||||
|
|
||||||
|
**WA-05: Stop at Target**
|
||||||
|
- **Purpose:** Test final stop condition
|
||||||
|
- **Setup:** Distance = 10cm (at target)
|
||||||
|
- **Assert:** Motor power = 0.0, State = STOPPED
|
||||||
|
- **Rationale:** Precise positioning
|
||||||
|
|
||||||
|
**WA-06: Emergency Stop If Too Close**
|
||||||
|
- **Purpose:** Test immediate stop when starting too close
|
||||||
|
- **Setup:** Distance = 5cm (< stop threshold)
|
||||||
|
- **Action:** Call `start()`, `update()`
|
||||||
|
- **Assert:** State = STOPPED immediately
|
||||||
|
- **Rationale:** Safety override
|
||||||
|
|
||||||
|
**WA-07: Sensor Failure Handling**
|
||||||
|
- **Purpose:** Test error detection
|
||||||
|
- **Setup:** Running approach, sensor fails
|
||||||
|
- **Action:** Call `simulateFailure()`, `update()`
|
||||||
|
- **Assert:** State = ERROR, motors = 0.0
|
||||||
|
- **Rationale:** Graceful degradation
|
||||||
|
|
||||||
|
**WA-08: Recovery from Pushback**
|
||||||
|
- **Purpose:** Test state reversal if pushed backward
|
||||||
|
- **Setup:** In SLOWING state (25cm), pushed to 35cm
|
||||||
|
- **Action:** Call `update()`
|
||||||
|
- **Assert:** State = APPROACHING, speed = 0.6
|
||||||
|
- **Rationale:** Adaptive behavior
|
||||||
|
|
||||||
|
**WA-09: Stays Stopped**
|
||||||
|
- **Purpose:** Test final state persistence
|
||||||
|
- **Setup:** Reach STOPPED state
|
||||||
|
- **Action:** Multiple `update()` calls
|
||||||
|
- **Assert:** Remains STOPPED
|
||||||
|
- **Rationale:** Stable final state
|
||||||
|
|
||||||
|
**WA-10: Manual Stop Override**
|
||||||
|
- **Purpose:** Test emergency stop command
|
||||||
|
- **Setup:** Running at any state
|
||||||
|
- **Action:** Call `stop()`
|
||||||
|
- **Assert:** Motors = 0.0
|
||||||
|
- **Rationale:** Safety control
|
||||||
|
|
||||||
|
**WA-11: Threshold Boundaries**
|
||||||
|
- **Purpose:** Test exact boundary values
|
||||||
|
- **Setup:** Test at 30.1cm, 29.9cm, 10.1cm, 9.9cm
|
||||||
|
- **Assert:** Correct state transitions at boundaries
|
||||||
|
- **Rationale:** Precision verification
|
||||||
|
|
||||||
|
#### System Test
|
||||||
|
|
||||||
|
**WA-12: Complete Approach Sequence**
|
||||||
|
- **Purpose:** Test full approach from far to stopped
|
||||||
|
- **Setup:** Start at 100cm
|
||||||
|
- **Action:** Simulate approach with speed ramping
|
||||||
|
- **Assert:** Transitions through all states, stops at target
|
||||||
|
- **Rationale:** End-to-end validation
|
||||||
|
|
||||||
|
**WA-13: Sensor Noise Handling**
|
||||||
|
- **Purpose:** Test robustness to noisy readings
|
||||||
|
- **Setup:** Distance = 50cm, noise = ±2cm
|
||||||
|
- **Action:** 20 updates with random noise
|
||||||
|
- **Assert:** No erratic behavior, smooth operation
|
||||||
|
- **Rationale:** Real-world reliability
|
||||||
|
|
||||||
|
#### Integration Test
|
||||||
|
|
||||||
|
**WA-14: Realistic Approach with Variance**
|
||||||
|
- **Purpose:** Test complete approach with realistic conditions
|
||||||
|
- **Setup:** Start 80cm away, ±1.5cm noise, variable speeds
|
||||||
|
- **Action:** Simulate until stopped
|
||||||
|
- **Assert:** Successfully stops near target, no crashes
|
||||||
|
- **Rationale:** Real-world scenario validation
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### TurnController Tests (15 tests)
|
||||||
|
|
||||||
|
#### Unit Tests
|
||||||
|
|
||||||
|
**TC-01: Initial State**
|
||||||
|
- **Assert:** State = IDLE
|
||||||
|
- **Rationale:** Proper initialization
|
||||||
|
|
||||||
|
**TC-02: TurnTo Activation**
|
||||||
|
- **Action:** Call `turnTo(90)`
|
||||||
|
- **Assert:** State = TURNING, target = 90°
|
||||||
|
- **Rationale:** Command handling
|
||||||
|
|
||||||
|
**TC-03: Completion Detection**
|
||||||
|
- **Setup:** Heading = 88.5°, target = 90°
|
||||||
|
- **Assert:** State = COMPLETE (within 2° tolerance)
|
||||||
|
- **Rationale:** Tolerance-based success
|
||||||
|
|
||||||
|
#### Path Selection Tests
|
||||||
|
|
||||||
|
**TC-04: Simple Clockwise (0°→90°)**
|
||||||
|
- **Setup:** Current = 0°, target = 90°
|
||||||
|
- **Assert:** Left motor positive, right motor negative
|
||||||
|
- **Rationale:** Correct rotation direction
|
||||||
|
|
||||||
|
**TC-05: Simple Counter-Clockwise (90°→0°)**
|
||||||
|
- **Setup:** Current = 90°, target = 0°
|
||||||
|
- **Assert:** Left motor negative, right motor positive
|
||||||
|
- **Rationale:** Correct rotation direction
|
||||||
|
|
||||||
|
**TC-06: Wraparound Clockwise (350°→10°)**
|
||||||
|
- **Setup:** Current = 350°, target = 10°
|
||||||
|
- **Assert:** Error = +20° (clockwise is shorter)
|
||||||
|
- **Rationale:** Optimal path through 0°
|
||||||
|
|
||||||
|
**TC-07: Wraparound Counter-Clockwise (10°→350°)**
|
||||||
|
- **Setup:** Current = 10°, target = 350°
|
||||||
|
- **Assert:** Error = -20° (CCW is shorter)
|
||||||
|
- **Rationale:** Optimal path through 0°
|
||||||
|
|
||||||
|
**TC-08: Opposite Heading (180° Ambiguous)**
|
||||||
|
- **Setup:** Current = 0°, target = 180°
|
||||||
|
- **Assert:** Error magnitude = 180°
|
||||||
|
- **Rationale:** Either direction valid
|
||||||
|
|
||||||
|
#### Control Algorithm Tests
|
||||||
|
|
||||||
|
**TC-09: Proportional Power**
|
||||||
|
- **Purpose:** Test power scales with error
|
||||||
|
- **Setup:** Test large error (90°) vs small error (5°)
|
||||||
|
- **Assert:** Large error → large power, small error → small power
|
||||||
|
- **Rationale:** P-controller verification
|
||||||
|
|
||||||
|
**TC-10: Minimum Power Enforcement**
|
||||||
|
- **Setup:** Very small error (just above tolerance)
|
||||||
|
- **Assert:** Power ≥ 0.15 (minimum)
|
||||||
|
- **Rationale:** Overcome friction
|
||||||
|
|
||||||
|
**TC-11: Maximum Power Cap**
|
||||||
|
- **Setup:** Very large error (179°)
|
||||||
|
- **Assert:** Power ≤ 0.5 (maximum)
|
||||||
|
- **Rationale:** Safety limit
|
||||||
|
|
||||||
|
#### System Tests
|
||||||
|
|
||||||
|
**TC-12: Complete 90° Turn**
|
||||||
|
- **Purpose:** Full turn execution
|
||||||
|
- **Action:** Simulate turn with gyro feedback
|
||||||
|
- **Assert:** Reaches target within tolerance
|
||||||
|
- **Rationale:** Closed-loop validation
|
||||||
|
|
||||||
|
**TC-13: Complete Wraparound Turn**
|
||||||
|
- **Purpose:** Test wraparound path
|
||||||
|
- **Setup:** 350° → 10°
|
||||||
|
- **Action:** Simulate turn
|
||||||
|
- **Assert:** Completes via shortest path
|
||||||
|
- **Rationale:** Math correctness
|
||||||
|
|
||||||
|
#### Edge Cases
|
||||||
|
|
||||||
|
**TC-14: Uncalibrated Gyro**
|
||||||
|
- **Setup:** Set gyro uncalibrated
|
||||||
|
- **Action:** Attempt turn
|
||||||
|
- **Assert:** Returns to IDLE, motors stopped
|
||||||
|
- **Rationale:** Safety check
|
||||||
|
|
||||||
|
**TC-15: Gyro Drift During Turn**
|
||||||
|
- **Setup:** Drift = 0.5°/sec
|
||||||
|
- **Action:** Simulate turn with drift
|
||||||
|
- **Assert:** Compensates and completes
|
||||||
|
- **Rationale:** Real-world robustness
|
||||||
|
|
||||||
|
**TC-16: Sequential Turns**
|
||||||
|
- **Purpose:** Multiple turns without reset
|
||||||
|
- **Action:** Turn 0→90→180→0
|
||||||
|
- **Assert:** All complete successfully
|
||||||
|
- **Rationale:** Continuous operation
|
||||||
|
|
||||||
|
**TC-17: Manual Stop**
|
||||||
|
- **Setup:** Mid-turn
|
||||||
|
- **Action:** Call `stop()`
|
||||||
|
- **Assert:** Motors = 0.0
|
||||||
|
- **Rationale:** Safety override
|
||||||
|
|
||||||
|
**TC-18: No-Op Turn (Already at Target)**
|
||||||
|
- **Setup:** Current = target = 45°
|
||||||
|
- **Action:** Call `turnTo(45)`
|
||||||
|
- **Assert:** Immediately COMPLETE
|
||||||
|
- **Rationale:** Efficiency
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Integration Test Scenarios
|
||||||
|
|
||||||
|
### INT-01: Complete Autonomous Mission
|
||||||
|
|
||||||
|
**Objective:** Validate full autonomous sequence with multiple subsystems
|
||||||
|
|
||||||
|
**Scenario:**
|
||||||
|
```
|
||||||
|
1. Start 100cm from wall, heading 0°
|
||||||
|
2. Drive forward (WallApproach)
|
||||||
|
3. Stop at 10cm from wall
|
||||||
|
4. Turn 90° right (TurnController)
|
||||||
|
5. Drive forward 80cm (WallApproach)
|
||||||
|
6. Stop at wall
|
||||||
|
7. Turn back to 0° (TurnController)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Subsystems Involved:** WallApproach, TurnController
|
||||||
|
|
||||||
|
**Duration:** ~100ms simulated time
|
||||||
|
|
||||||
|
**Assertions:**
|
||||||
|
- All phase transitions occur
|
||||||
|
- Final heading within 2° of 0°
|
||||||
|
- All stops occur at correct distances
|
||||||
|
- No subsystem errors
|
||||||
|
|
||||||
|
**Result:** ✅ PASS
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### INT-02: Sensor Failure Recovery
|
||||||
|
|
||||||
|
**Objective:** Validate graceful handling of sensor failures
|
||||||
|
|
||||||
|
**Scenario:**
|
||||||
|
```
|
||||||
|
1. Begin wall approach
|
||||||
|
2. Midway, distance sensor fails
|
||||||
|
3. System detects failure
|
||||||
|
4. Emergency stops
|
||||||
|
5. Reports error status
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fault Injection:** `sensor.simulateFailure()`
|
||||||
|
|
||||||
|
**Assertions:**
|
||||||
|
- Enters ERROR state
|
||||||
|
- Motors stop immediately
|
||||||
|
- Error flag set
|
||||||
|
- No crashes or exceptions
|
||||||
|
|
||||||
|
**Result:** ✅ PASS
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### INT-03: Unexpected Obstacle
|
||||||
|
|
||||||
|
**Objective:** Test emergency stop on sudden obstacle
|
||||||
|
|
||||||
|
**Scenario:**
|
||||||
|
```
|
||||||
|
1. Approaching wall at 50cm
|
||||||
|
2. Sudden obstacle appears at 8cm
|
||||||
|
3. Emergency stop triggered
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fault Injection:** Sudden distance change
|
||||||
|
|
||||||
|
**Assertions:**
|
||||||
|
- Immediate transition to STOPPED
|
||||||
|
- No collision (motors stop)
|
||||||
|
- System remains stable
|
||||||
|
|
||||||
|
**Result:** ✅ PASS
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### INT-04: Multi-Waypoint Navigation (Square Pattern)
|
||||||
|
|
||||||
|
**Objective:** Validate repeated subsystem usage
|
||||||
|
|
||||||
|
**Scenario:**
|
||||||
|
```
|
||||||
|
For each side of square (4 times):
|
||||||
|
1. Drive forward 50cm
|
||||||
|
2. Turn 90° right
|
||||||
|
Result: Complete square, return to start
|
||||||
|
```
|
||||||
|
|
||||||
|
**Subsystems Involved:** WallApproach, TurnController (8 activations each)
|
||||||
|
|
||||||
|
**Assertions:**
|
||||||
|
- All 4 sides complete
|
||||||
|
- Final heading = 0° (back to start)
|
||||||
|
- No accumulated errors
|
||||||
|
- Consistent behavior each iteration
|
||||||
|
|
||||||
|
**Result:** ✅ PASS
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### INT-05: Concurrent Sensor Updates
|
||||||
|
|
||||||
|
**Objective:** Test system with asynchronous sensor data
|
||||||
|
|
||||||
|
**Scenario:**
|
||||||
|
```
|
||||||
|
Distance sensor: Updates every cycle
|
||||||
|
Gyro sensor: Updates every 3 cycles
|
||||||
|
100 update cycles
|
||||||
|
```
|
||||||
|
|
||||||
|
**Stress Test:** Varying sensor update rates
|
||||||
|
|
||||||
|
**Assertions:**
|
||||||
|
- No crashes or errors
|
||||||
|
- System remains stable
|
||||||
|
- Graceful handling of stale data
|
||||||
|
|
||||||
|
**Result:** ✅ PASS
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test Execution
|
||||||
|
|
||||||
|
### Running Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run all tests
|
||||||
|
gradlew test
|
||||||
|
|
||||||
|
# Run specific test class
|
||||||
|
gradlew test --tests MotorCyclerTest
|
||||||
|
|
||||||
|
# Run specific test method
|
||||||
|
gradlew test --tests WallApproachTest.testSensorFailureHandling
|
||||||
|
|
||||||
|
# Run with verbose output
|
||||||
|
gradlew test --info
|
||||||
|
```
|
||||||
|
|
||||||
|
### Expected Results
|
||||||
|
|
||||||
|
```
|
||||||
|
Total Tests: 45
|
||||||
|
Passed: 45
|
||||||
|
Failed: 0
|
||||||
|
Skipped: 0
|
||||||
|
Duration: < 2 seconds
|
||||||
|
|
||||||
|
Coverage:
|
||||||
|
- MotorCycler: 100%
|
||||||
|
- WallApproach: 100%
|
||||||
|
- TurnController: 100%
|
||||||
|
```
|
||||||
|
|
||||||
|
### Test Reports
|
||||||
|
|
||||||
|
After running tests, view detailed HTML reports at:
|
||||||
|
```
|
||||||
|
build/reports/tests/test/index.html
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Design Rationale
|
||||||
|
|
||||||
|
### Why This Architecture?
|
||||||
|
|
||||||
|
**Separation of Concerns:**
|
||||||
|
- Robot logic is independent of hardware
|
||||||
|
- FTC SDK isolated to thin wrappers
|
||||||
|
- Each subsystem has single responsibility
|
||||||
|
|
||||||
|
**Testability:**
|
||||||
|
- All logic testable without hardware
|
||||||
|
- Tests run in seconds on Windows
|
||||||
|
- 100% code coverage achievable
|
||||||
|
|
||||||
|
**Maintainability:**
|
||||||
|
- Clear component boundaries
|
||||||
|
- Easy to add new sensors/actuators
|
||||||
|
- Students understand each layer
|
||||||
|
|
||||||
|
**Professional Practice:**
|
||||||
|
- Industry-standard patterns
|
||||||
|
- Dependency injection
|
||||||
|
- Interface-based design
|
||||||
|
- Test-driven development
|
||||||
|
|
||||||
|
### What Makes This Different from Traditional FTC?
|
||||||
|
|
||||||
|
| Traditional FTC | This Architecture |
|
||||||
|
|----------------|-------------------|
|
||||||
|
| Logic in OpMode | Logic in subsystems |
|
||||||
|
| Direct hardware calls | Hardware abstractions |
|
||||||
|
| No testing without robot | 100% testable |
|
||||||
|
| Monolithic structure | Layered architecture |
|
||||||
|
| Hard to maintain | Clear separation |
|
||||||
|
| Students write spaghetti | Students learn design |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Appendix: Test Data
|
||||||
|
|
||||||
|
### Mock Sensor Capabilities
|
||||||
|
|
||||||
|
**MockDistanceSensor:**
|
||||||
|
- Set exact distance values
|
||||||
|
- Add Gaussian noise (±N cm)
|
||||||
|
- Simulate failures
|
||||||
|
- Simulate gradual approach
|
||||||
|
- Reproducible (seeded random)
|
||||||
|
|
||||||
|
**MockGyroSensor:**
|
||||||
|
- Set exact heading
|
||||||
|
- Simulate rotation
|
||||||
|
- Add drift (°/sec)
|
||||||
|
- Simulate calibration states
|
||||||
|
- Wraparound handling
|
||||||
|
|
||||||
|
**MockMotorController:**
|
||||||
|
- Store power settings
|
||||||
|
- Track power history
|
||||||
|
- No actual hardware needed
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Document Control
|
||||||
|
|
||||||
|
**Approvals:**
|
||||||
|
- Design: ✅ Complete
|
||||||
|
- Implementation: ✅ Complete
|
||||||
|
- Testing: ✅ All tests passing
|
||||||
|
- Documentation: ✅ This document
|
||||||
|
|
||||||
|
**Change History:**
|
||||||
|
- 2026-02-02: Initial version, all tests passing
|
||||||
|
|
||||||
|
**Related Documents:**
|
||||||
|
- `README.md` - Project overview
|
||||||
|
- `TESTING_SHOWCASE.md` - Testing philosophy
|
||||||
|
- `SOLUTION.md` - Technical implementation
|
||||||
|
- `ARCHITECTURE.md` - Detailed design patterns
|
||||||
173
templates/testing/QUICKSTART.md
Normal file
173
templates/testing/QUICKSTART.md
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
# Quick Reference Guide
|
||||||
|
|
||||||
|
## Project Commands
|
||||||
|
|
||||||
|
### Testing (Windows JRE - No Robot Needed)
|
||||||
|
```bash
|
||||||
|
gradlew test # Run all tests
|
||||||
|
gradlew test --tests MotorCyclerTest # Run specific test
|
||||||
|
```
|
||||||
|
|
||||||
|
### Building for Robot
|
||||||
|
```bash
|
||||||
|
build.bat # Build APK (Windows)
|
||||||
|
./build.sh # Build APK (Linux/Mac)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deployment
|
||||||
|
```bash
|
||||||
|
deploy.bat # Deploy to robot (Windows)
|
||||||
|
./deploy.sh # Deploy to robot (Linux/Mac)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Project Structure Quick View
|
||||||
|
|
||||||
|
```
|
||||||
|
my-robot/
|
||||||
|
│
|
||||||
|
├── src/main/java/robot/
|
||||||
|
│ ├── hardware/ # Hardware abstractions
|
||||||
|
│ │ ├── MotorController.java [Interface - No FTC deps]
|
||||||
|
│ │ └── FtcMotorController.java [FTC SDK wrapper]
|
||||||
|
│ │
|
||||||
|
│ ├── subsystems/ # Business logic
|
||||||
|
│ │ └── MotorCycler.java [Pure Java - Testable!]
|
||||||
|
│ │
|
||||||
|
│ └── opmodes/ # FTC integration
|
||||||
|
│ └── MotorCycleOpMode.java [Glue code]
|
||||||
|
│
|
||||||
|
├── src/test/java/robot/
|
||||||
|
│ ├── hardware/
|
||||||
|
│ │ └── MockMotorController.java [Test mock]
|
||||||
|
│ └── subsystems/
|
||||||
|
│ └── MotorCyclerTest.java [Unit tests]
|
||||||
|
│
|
||||||
|
├── build.gradle.kts # Build configuration
|
||||||
|
├── build.bat / build.sh # Build scripts
|
||||||
|
└── deploy.bat / deploy.sh # Deploy scripts
|
||||||
|
```
|
||||||
|
|
||||||
|
## Code Flow
|
||||||
|
|
||||||
|
1. **OpMode starts** → Creates FtcMotorController from hardware map
|
||||||
|
2. **OpMode.init()** → Creates MotorCycler, passes controller
|
||||||
|
3. **OpMode.loop()** → Calls motorCycler.update(currentTime)
|
||||||
|
4. **MotorCycler** → Updates state, controls motor via interface
|
||||||
|
5. **MotorController** → Abstraction hides whether it's real or mock
|
||||||
|
|
||||||
|
## Testing Flow
|
||||||
|
|
||||||
|
1. **Test creates** → MockMotorController
|
||||||
|
2. **Test creates** → MotorCycler with mock
|
||||||
|
3. **Test calls** → motorCycler.init()
|
||||||
|
4. **Test calls** → motorCycler.update() with simulated time
|
||||||
|
5. **Test verifies** → Mock motor received correct commands
|
||||||
|
|
||||||
|
## Key Design Patterns
|
||||||
|
|
||||||
|
### Dependency Injection
|
||||||
|
```java
|
||||||
|
// Good: Pass dependencies in constructor
|
||||||
|
MotorCycler cycler = new MotorCycler(motorController, 2000, 1000);
|
||||||
|
|
||||||
|
// Bad: Create dependencies internally
|
||||||
|
// class MotorCycler {
|
||||||
|
// DcMotor motor = hardwareMap.get(...); // Hard to test!
|
||||||
|
// }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Interface Abstraction
|
||||||
|
```java
|
||||||
|
// Good: Program to interface
|
||||||
|
MotorController motor = new FtcMotorController(dcMotor);
|
||||||
|
|
||||||
|
// Bad: Program to implementation
|
||||||
|
// FtcMotorController motor = new FtcMotorController(dcMotor);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Time-Based State Machine
|
||||||
|
```java
|
||||||
|
// Good: Pass time as parameter (testable)
|
||||||
|
void update(long currentTimeMs) { ... }
|
||||||
|
|
||||||
|
// Bad: Read time internally (hard to test)
|
||||||
|
// void update() {
|
||||||
|
// long time = System.currentTimeMillis();
|
||||||
|
// }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Tasks
|
||||||
|
|
||||||
|
### Add a New Subsystem
|
||||||
|
1. Create interface in `hardware/` (e.g., `ServoController.java`)
|
||||||
|
2. Create FTC implementation (e.g., `FtcServoController.java`)
|
||||||
|
3. Create business logic in `subsystems/` (e.g., `ClawController.java`)
|
||||||
|
4. Create mock in `test/hardware/` (e.g., `MockServoController.java`)
|
||||||
|
5. Create tests in `test/subsystems/` (e.g., `ClawControllerTest.java`)
|
||||||
|
6. Wire into OpMode
|
||||||
|
|
||||||
|
### Run a Specific Test
|
||||||
|
```bash
|
||||||
|
gradlew test --tests "MotorCyclerTest.testFullCycle"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Debug Test Failure
|
||||||
|
1. Look at test output (shows which assertion failed)
|
||||||
|
2. Check expected vs actual values
|
||||||
|
3. Add println() to MotorCycler if needed
|
||||||
|
4. Re-run test instantly (no robot deploy needed!)
|
||||||
|
|
||||||
|
### Modify Timing
|
||||||
|
Edit MotorCycleOpMode.java line 20:
|
||||||
|
```java
|
||||||
|
// Change from 2000, 1000 to whatever you want
|
||||||
|
motorCycler = new MotorCycler(motorController, 2000, 1000, 0.5);
|
||||||
|
// ^^^^ ^^^^ ^^^
|
||||||
|
// on-ms off-ms power
|
||||||
|
```
|
||||||
|
|
||||||
|
## Hardware Configuration
|
||||||
|
|
||||||
|
Your FTC Robot Configuration needs:
|
||||||
|
- **One DC Motor** named `"motor"` (exact spelling matters!)
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### "Could not find motor"
|
||||||
|
→ Check hardware configuration has motor named "motor"
|
||||||
|
|
||||||
|
### "Tests won't run"
|
||||||
|
→ Make sure you're using `gradlew test` not `gradlew build`
|
||||||
|
→ Tests run on PC, build needs FTC SDK
|
||||||
|
|
||||||
|
### "Build can't find FTC SDK"
|
||||||
|
→ Check `.weevil.toml` has correct `ftc_sdk_path`
|
||||||
|
→ Run `weevil init` if SDK is missing
|
||||||
|
|
||||||
|
### "Motor not cycling"
|
||||||
|
→ Check OpMode is selected and started on Driver Station
|
||||||
|
→ Verify motor is plugged in and configured correctly
|
||||||
|
|
||||||
|
## Learning More
|
||||||
|
|
||||||
|
- Read `ARCHITECTURE.md` for deep dive into design decisions
|
||||||
|
- Read `README.md` for overview
|
||||||
|
- Look at tests to see how each component works
|
||||||
|
- Modify values and re-run tests to see behavior change
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
✓ Write tests first (they're fast!)
|
||||||
|
✓ Keep subsystems independent
|
||||||
|
✓ Use interfaces for hardware
|
||||||
|
✓ Pass time as parameters
|
||||||
|
✓ Mock everything external
|
||||||
|
|
||||||
|
✗ Don't put hardware maps in subsystems
|
||||||
|
✗ Don't read System.currentTimeMillis() in logic
|
||||||
|
✗ Don't skip tests
|
||||||
|
✗ Don't mix hardware and logic code
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Remember: Test locally, deploy confidently!**
|
||||||
223
templates/testing/README.md.template
Normal file
223
templates/testing/README.md.template
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
# FTC Robot Testing Showcase
|
||||||
|
|
||||||
|
A comprehensive FTC robot project demonstrating **professional testing without hardware**.
|
||||||
|
|
||||||
|
## What This Demonstrates
|
||||||
|
|
||||||
|
This project shows how to build testable FTC robots using:
|
||||||
|
- **Hardware abstraction** - Interfaces separate logic from FTC SDK
|
||||||
|
- **Unit testing** - Test individual components in isolation
|
||||||
|
- **System testing** - Test complete autonomous sequences
|
||||||
|
- **Edge case testing** - Sensor failures, noise, boundary conditions
|
||||||
|
|
||||||
|
**All tests run instantly on Windows - no robot needed!**
|
||||||
|
|
||||||
|
## The Robot Systems
|
||||||
|
|
||||||
|
### 1. Motor Cycler
|
||||||
|
Continuously cycles a motor (2s ON, 1s OFF) - demonstrates timing logic
|
||||||
|
|
||||||
|
### 2. Wall Approach
|
||||||
|
Safely approaches a wall using distance sensor:
|
||||||
|
- Drives fast when far away
|
||||||
|
- Slows down as it gets closer
|
||||||
|
- Stops at target distance
|
||||||
|
- Handles sensor failures
|
||||||
|
|
||||||
|
### 3. Turn Controller
|
||||||
|
Turns robot to target heading using gyro:
|
||||||
|
- Proportional control (faster when far from target)
|
||||||
|
- Chooses shortest rotation path
|
||||||
|
- Handles 360° wraparound
|
||||||
|
- Compensates for drift
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
src/main/java/robot/
|
||||||
|
├── hardware/ # Hardware abstractions
|
||||||
|
│ ├── MotorController.java # ✅ Interface
|
||||||
|
│ ├── DistanceSensor.java # ✅ Interface
|
||||||
|
│ ├── GyroSensor.java # ✅ Interface
|
||||||
|
│ ├── FtcMotorController.java # ❌ FTC (excluded from tests)
|
||||||
|
│ ├── FtcDistanceSensor.java # ❌ FTC (excluded from tests)
|
||||||
|
│ └── FtcGyroSensor.java # ❌ FTC (excluded from tests)
|
||||||
|
│
|
||||||
|
├── subsystems/ # Robot logic (pure Java!)
|
||||||
|
│ ├── MotorCycler.java # ✅ Testable
|
||||||
|
│ ├── WallApproach.java # ✅ Testable
|
||||||
|
│ └── TurnController.java # ✅ Testable
|
||||||
|
│
|
||||||
|
└── opmodes/ # FTC integration
|
||||||
|
└── MotorCycleOpMode.java # ❌ FTC (excluded from tests)
|
||||||
|
|
||||||
|
src/test/java/robot/
|
||||||
|
├── hardware/ # Test mocks
|
||||||
|
│ ├── MockMotorController.java
|
||||||
|
│ ├── MockDistanceSensor.java
|
||||||
|
│ └── MockGyroSensor.java
|
||||||
|
│
|
||||||
|
└── subsystems/ # Tests
|
||||||
|
├── MotorCyclerTest.java # 8 tests
|
||||||
|
├── WallApproachTest.java # 13 tests
|
||||||
|
├── TurnControllerTest.java # 15 tests
|
||||||
|
└── AutonomousIntegrationTest.java # 5 system tests
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test Coverage
|
||||||
|
|
||||||
|
**41 Total Tests:**
|
||||||
|
- **Unit tests**: Individual component behaviors
|
||||||
|
- **System tests**: Complete autonomous missions
|
||||||
|
- **Edge cases**: Sensor failures, noise, boundaries
|
||||||
|
- **Integration**: Multiple subsystems working together
|
||||||
|
|
||||||
|
Run time: **< 2 seconds on Windows!**
|
||||||
|
|
||||||
|
## Building and Testing
|
||||||
|
|
||||||
|
### Run Tests (Windows JRE)
|
||||||
|
```bash
|
||||||
|
gradlew test
|
||||||
|
```
|
||||||
|
Tests run on your local machine without requiring Android or FTC SDK.
|
||||||
|
|
||||||
|
### Build APK for Robot (requires FTC SDK)
|
||||||
|
```bash
|
||||||
|
build.bat # Windows
|
||||||
|
./build.sh # Linux/Mac
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deploy to Robot
|
||||||
|
```bash
|
||||||
|
deploy.bat # Windows
|
||||||
|
./deploy.sh # Linux/Mac
|
||||||
|
```
|
||||||
|
|
||||||
|
## Hardware Configuration
|
||||||
|
|
||||||
|
Configure your FTC robot with:
|
||||||
|
- DC Motors named `"left_motor"` and `"right_motor"`
|
||||||
|
- Distance sensor (REV 2m or similar)
|
||||||
|
- IMU/Gyro sensor
|
||||||
|
|
||||||
|
## Testing Showcase
|
||||||
|
|
||||||
|
### Unit Test Example: Wall Approach
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testSlowsDownNearWall() {
|
||||||
|
sensor.setDistance(25.0); // 25cm from wall
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should slow down to 0.2 power
|
||||||
|
assertEquals(0.2, leftMotor.getPower(), 0.001);
|
||||||
|
assertEquals(WallApproachState.SLOWING, wallApproach.getState());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### System Test Example: Complete Mission
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testCompleteAutonomousMission() {
|
||||||
|
// Simulate entire autonomous:
|
||||||
|
// 1. Drive to wall (100cm → 10cm)
|
||||||
|
// 2. Turn 90° right
|
||||||
|
// 3. Drive forward again
|
||||||
|
// 4. Turn back to original heading
|
||||||
|
|
||||||
|
// All without a robot! Tests run in ~100ms
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Edge Case Example: Sensor Failure
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testSensorFailureHandling() {
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
// Sensor suddenly fails!
|
||||||
|
sensor.simulateFailure();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should safely stop
|
||||||
|
assertEquals(WallApproachState.ERROR, wallApproach.getState());
|
||||||
|
assertEquals(0.0, motor.getPower());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## What Tests Cover
|
||||||
|
|
||||||
|
**Unit Tests** (test individual behaviors):
|
||||||
|
- Motor timing and power levels
|
||||||
|
- Distance threshold detection
|
||||||
|
- Turn angle calculations
|
||||||
|
- State transitions
|
||||||
|
|
||||||
|
**System Tests** (test complete scenarios):
|
||||||
|
- Full autonomous sequences
|
||||||
|
- Multi-waypoint navigation
|
||||||
|
- Square pattern driving
|
||||||
|
- Sensor coordination
|
||||||
|
|
||||||
|
**Edge Cases** (test failure modes):
|
||||||
|
- Sensor failures and recovery
|
||||||
|
- Noise handling
|
||||||
|
- Boundary conditions
|
||||||
|
- Wraparound math (0° ↔ 359°)
|
||||||
|
|
||||||
|
**All 41 tests run in < 2 seconds on Windows!**
|
||||||
|
|
||||||
|
## The Pattern: Applies to Any Hardware
|
||||||
|
|
||||||
|
Same pattern works for **anything**:
|
||||||
|
|
||||||
|
### Servo Example
|
||||||
|
```java
|
||||||
|
// Interface
|
||||||
|
public interface ServoController {
|
||||||
|
void setPosition(double position);
|
||||||
|
}
|
||||||
|
|
||||||
|
// FTC impl (excluded from tests)
|
||||||
|
public class FtcServoController implements ServoController {
|
||||||
|
private final Servo servo; // FTC SDK class
|
||||||
|
...
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mock (for tests)
|
||||||
|
public class MockServoController implements ServoController {
|
||||||
|
private double position = 0.5;
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
See `TESTING_GUIDE.md` for more examples (sensors, encoders, vision, etc.)
|
||||||
|
|
||||||
|
## How It Works
|
||||||
|
|
||||||
|
The architecture demonstrates three layers:
|
||||||
|
|
||||||
|
1. **Hardware Abstraction** (`MotorController` interface)
|
||||||
|
- Defines what a motor can do
|
||||||
|
- Allows swapping implementations (real motor vs. mock)
|
||||||
|
|
||||||
|
2. **Business Logic** (`MotorCycler` class)
|
||||||
|
- Implements the cycling behavior
|
||||||
|
- Completely independent of FTC SDK
|
||||||
|
- Fully testable with mocks
|
||||||
|
|
||||||
|
3. **Integration** (`MotorCycleOpMode`)
|
||||||
|
- Wires everything together
|
||||||
|
- Minimal code, just connects the pieces
|
||||||
|
|
||||||
|
## Why This Matters
|
||||||
|
|
||||||
|
Traditional FTC projects force you to edit SDK files directly and make testing difficult.
|
||||||
|
Weevil's approach:
|
||||||
|
- ✓ Keep your code separate from the SDK
|
||||||
|
- ✓ Write unit tests that run instantly on your PC
|
||||||
|
- ✓ Build more reliable robots faster
|
||||||
|
- ✓ Learn better software engineering practices
|
||||||
126
templates/testing/SOLUTION.md
Normal file
126
templates/testing/SOLUTION.md
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
# Solution: Testing FTC Code Without Hardware
|
||||||
|
|
||||||
|
## The Problem
|
||||||
|
|
||||||
|
When you run `gradlew test`, it tries to compile ALL your code including FTC-dependent files:
|
||||||
|
```
|
||||||
|
FtcMotorController.java → needs com.qualcomm.robotcore.hardware.DcMotor
|
||||||
|
MotorCycleOpMode.java → needs com.qualcomm.robotcore.eventloop.opmode.OpMode
|
||||||
|
```
|
||||||
|
|
||||||
|
These classes don't exist on Windows → compilation fails → no tests.
|
||||||
|
|
||||||
|
## The Solution (One Line)
|
||||||
|
|
||||||
|
**Exclude FTC-dependent files from test compilation:**
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// build.gradle.kts
|
||||||
|
sourceSets {
|
||||||
|
main {
|
||||||
|
java {
|
||||||
|
exclude(
|
||||||
|
"robot/hardware/FtcMotorController.java",
|
||||||
|
"robot/opmodes/**/*.java"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Done. That's it.
|
||||||
|
|
||||||
|
## What Happens Now
|
||||||
|
|
||||||
|
### When You Run `gradlew test`:
|
||||||
|
- ✅ Compiles: MotorController.java (interface, no FTC deps)
|
||||||
|
- ✅ Compiles: MotorCycler.java (pure Java logic)
|
||||||
|
- ✅ Compiles: MockMotorController.java (test mock)
|
||||||
|
- ✅ Compiles: MotorCyclerTest.java (tests)
|
||||||
|
- ❌ Skips: FtcMotorController.java (EXCLUDED - has FTC deps)
|
||||||
|
- ❌ Skips: MotorCycleOpMode.java (EXCLUDED - has FTC deps)
|
||||||
|
|
||||||
|
Tests run on Windows in seconds!
|
||||||
|
|
||||||
|
### When You Run `build.bat`:
|
||||||
|
- Copies ALL files to FTC SDK TeamCode directory
|
||||||
|
- FTC SDK's Gradle compiles everything (it has the FTC SDK jars)
|
||||||
|
- Creates APK with all your code
|
||||||
|
|
||||||
|
## The Architecture Pattern
|
||||||
|
|
||||||
|
```
|
||||||
|
Interface (no FTC) → Logic uses interface → Test with mock
|
||||||
|
↓
|
||||||
|
FTC Implementation (excluded from tests)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example: Motor
|
||||||
|
```java
|
||||||
|
// 1. Interface (compiles for tests)
|
||||||
|
public interface MotorController {
|
||||||
|
void setPower(double power);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. FTC implementation (excluded from tests)
|
||||||
|
public class FtcMotorController implements MotorController {
|
||||||
|
private final DcMotor motor; // FTC SDK class
|
||||||
|
public void setPower(double p) { motor.setPower(p); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Mock (test only)
|
||||||
|
public class MockMotorController implements MotorController {
|
||||||
|
private double power;
|
||||||
|
public void setPower(double p) { this.power = p; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Logic (pure Java - testable!)
|
||||||
|
public class MotorCycler {
|
||||||
|
private final MotorController motor; // Uses interface!
|
||||||
|
// ... no FTC dependencies ...
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Test
|
||||||
|
@Test
|
||||||
|
void test() {
|
||||||
|
MockMotorController mock = new MockMotorController();
|
||||||
|
MotorCycler cycler = new MotorCycler(mock, 100, 50);
|
||||||
|
cycler.update(60);
|
||||||
|
assertEquals(0.5, mock.getPower());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Applies to Any Hardware
|
||||||
|
|
||||||
|
Same pattern for everything:
|
||||||
|
- **Motors** → MotorController interface + Ftc + Mock
|
||||||
|
- **Servos** → ServoController interface + Ftc + Mock
|
||||||
|
- **Sensors** (I2C, SPI, USB, etc.) → SensorInterface + Ftc + Mock
|
||||||
|
- **Gyros** → GyroSensor interface + Ftc + Mock
|
||||||
|
|
||||||
|
The FTC implementation is always just a thin wrapper. All your logic uses interfaces and is fully testable.
|
||||||
|
|
||||||
|
## Why This Works
|
||||||
|
|
||||||
|
**Test compilation:**
|
||||||
|
- Only compiles files WITHOUT FTC dependencies
|
||||||
|
- Pure Java logic + interfaces + mocks
|
||||||
|
- Runs on Windows JRE
|
||||||
|
|
||||||
|
**Robot compilation:**
|
||||||
|
- ALL files copied to TeamCode
|
||||||
|
- Compiled by FTC SDK (which has FTC jars)
|
||||||
|
- Creates APK with everything
|
||||||
|
|
||||||
|
Same logic runs in both places - no special test-only code!
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
1. Create interface (no FTC deps)
|
||||||
|
2. Create FTC implementation (add to exclude list)
|
||||||
|
3. Create mock for testing
|
||||||
|
4. Write pure Java logic using interface
|
||||||
|
5. Test instantly on PC
|
||||||
|
6. Deploy to robot - everything works
|
||||||
|
|
||||||
|
See TESTING_GUIDE.md for detailed examples.
|
||||||
554
templates/testing/TESTING_GUIDE.md
Normal file
554
templates/testing/TESTING_GUIDE.md
Normal file
@@ -0,0 +1,554 @@
|
|||||||
|
# Testing Guide: Mocking Hardware Without the Robot
|
||||||
|
|
||||||
|
## The Problem
|
||||||
|
|
||||||
|
When you run `gradlew test`, Gradle tries to compile **all** your main source code, including files that depend on the FTC SDK (like `FtcMotorController` and `MotorCycleOpMode`). Since the FTC SDK isn't available on your Windows machine, compilation fails.
|
||||||
|
|
||||||
|
## The Solution: Source Set Exclusion
|
||||||
|
|
||||||
|
Your `build.gradle.kts` now excludes FTC-dependent files from test compilation:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
sourceSets {
|
||||||
|
main {
|
||||||
|
java {
|
||||||
|
exclude(
|
||||||
|
"robot/hardware/FtcMotorController.java",
|
||||||
|
"robot/opmodes/**/*.java"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This means:
|
||||||
|
- ✅ `MotorController.java` (interface) - Compiles for tests
|
||||||
|
- ✅ `MotorCycler.java` (pure logic) - Compiles for tests
|
||||||
|
- ✅ `MockMotorController.java` (test mock) - Compiles for tests
|
||||||
|
- ❌ `FtcMotorController.java` (FTC SDK) - Skipped for tests
|
||||||
|
- ❌ `MotorCycleOpMode.java` (FTC SDK) - Skipped for tests
|
||||||
|
|
||||||
|
## Running Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# On Windows
|
||||||
|
gradlew test
|
||||||
|
|
||||||
|
# On Linux/Mac
|
||||||
|
./gradlew test
|
||||||
|
```
|
||||||
|
|
||||||
|
The tests run entirely on your Windows JRE - **no robot, no Android, no FTC SDK needed!**
|
||||||
|
|
||||||
|
## The Architecture Pattern
|
||||||
|
|
||||||
|
### 1. Interface (Hardware Abstraction)
|
||||||
|
```java
|
||||||
|
public interface MotorController {
|
||||||
|
void setPower(double power);
|
||||||
|
double getPower();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Real Implementation (FTC-dependent)
|
||||||
|
```java
|
||||||
|
public class FtcMotorController implements MotorController {
|
||||||
|
private final DcMotor motor; // FTC SDK class
|
||||||
|
|
||||||
|
public FtcMotorController(DcMotor motor) {
|
||||||
|
this.motor = motor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setPower(double power) {
|
||||||
|
motor.setPower(power);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getPower() {
|
||||||
|
return motor.getPower();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Mock Implementation (Testing)
|
||||||
|
```java
|
||||||
|
public class MockMotorController implements MotorController {
|
||||||
|
private double power = 0.0;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setPower(double power) {
|
||||||
|
this.power = power;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getPower() {
|
||||||
|
return power;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Business Logic (Pure Java)
|
||||||
|
```java
|
||||||
|
public class MotorCycler {
|
||||||
|
private final MotorController motor; // Interface, not FTC class!
|
||||||
|
|
||||||
|
public MotorCycler(MotorController motor, long onMs, long offMs) {
|
||||||
|
this.motor = motor;
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update(long currentTimeMs) {
|
||||||
|
// Time-based state machine
|
||||||
|
// No FTC SDK dependencies!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example: I2C Bump Sensor
|
||||||
|
|
||||||
|
Here's how you'd implement the pattern for an I2C bump sensor:
|
||||||
|
|
||||||
|
### Interface
|
||||||
|
```java
|
||||||
|
// src/main/java/robot/hardware/BumpSensor.java
|
||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
public interface BumpSensor {
|
||||||
|
/**
|
||||||
|
* Check if the sensor detects contact.
|
||||||
|
* @return true if bumped, false otherwise
|
||||||
|
*/
|
||||||
|
boolean isBumped();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the force reading (0.0 to 1.0).
|
||||||
|
* @return force value
|
||||||
|
*/
|
||||||
|
double getForce();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### FTC Implementation
|
||||||
|
```java
|
||||||
|
// src/main/java/robot/hardware/FtcBumpSensor.java
|
||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
import com.qualcomm.robotcore.hardware.I2cDevice;
|
||||||
|
import com.qualcomm.robotcore.hardware.I2cDeviceReader;
|
||||||
|
|
||||||
|
public class FtcBumpSensor implements BumpSensor {
|
||||||
|
private final I2cDevice sensor;
|
||||||
|
private final I2cDeviceReader reader;
|
||||||
|
private static final double BUMP_THRESHOLD = 0.5;
|
||||||
|
|
||||||
|
public FtcBumpSensor(I2cDevice sensor) {
|
||||||
|
this.sensor = sensor;
|
||||||
|
this.reader = new I2cDeviceReader(sensor, 0x00, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isBumped() {
|
||||||
|
return getForce() > BUMP_THRESHOLD;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getForce() {
|
||||||
|
byte[] data = reader.read();
|
||||||
|
// Convert I2C bytes to force value
|
||||||
|
int raw = ((data[0] & 0xFF) << 8) | (data[1] & 0xFF);
|
||||||
|
return raw / 65535.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Mock Implementation
|
||||||
|
```java
|
||||||
|
// src/test/java/robot/hardware/MockBumpSensor.java
|
||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
public class MockBumpSensor implements BumpSensor {
|
||||||
|
private double force = 0.0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate hitting a wall with given force.
|
||||||
|
*/
|
||||||
|
public void simulateImpact(double force) {
|
||||||
|
this.force = Math.max(0.0, Math.min(1.0, force));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate sensor returning to neutral.
|
||||||
|
*/
|
||||||
|
public void reset() {
|
||||||
|
this.force = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isBumped() {
|
||||||
|
return force > 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getForce() {
|
||||||
|
return force;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Business Logic Using Sensor
|
||||||
|
```java
|
||||||
|
// src/main/java/robot/subsystems/CollisionDetector.java
|
||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import robot.hardware.BumpSensor;
|
||||||
|
import robot.hardware.MotorController;
|
||||||
|
|
||||||
|
public class CollisionDetector {
|
||||||
|
private final BumpSensor sensor;
|
||||||
|
private final MotorController motor;
|
||||||
|
private boolean collisionDetected = false;
|
||||||
|
|
||||||
|
public CollisionDetector(BumpSensor sensor, MotorController motor) {
|
||||||
|
this.sensor = sensor;
|
||||||
|
this.motor = motor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update() {
|
||||||
|
if (sensor.isBumped() && !collisionDetected) {
|
||||||
|
// First detection - stop the motor
|
||||||
|
motor.setPower(0.0);
|
||||||
|
collisionDetected = true;
|
||||||
|
} else if (!sensor.isBumped() && collisionDetected) {
|
||||||
|
// Sensor cleared - reset flag
|
||||||
|
collisionDetected = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasCollision() {
|
||||||
|
return collisionDetected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Test with Simulated Wall Hit
|
||||||
|
```java
|
||||||
|
// src/test/java/robot/subsystems/CollisionDetectorTest.java
|
||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import robot.hardware.MockBumpSensor;
|
||||||
|
import robot.hardware.MockMotorController;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class CollisionDetectorTest {
|
||||||
|
private MockBumpSensor sensor;
|
||||||
|
private MockMotorController motor;
|
||||||
|
private CollisionDetector detector;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
sensor = new MockBumpSensor();
|
||||||
|
motor = new MockMotorController();
|
||||||
|
detector = new CollisionDetector(sensor, motor);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testWallImpactStopsMotor() {
|
||||||
|
// Robot is driving
|
||||||
|
motor.setPower(0.8);
|
||||||
|
assertEquals(0.8, motor.getPower(), 0.001);
|
||||||
|
|
||||||
|
// Simulate hitting a wall with high force
|
||||||
|
sensor.simulateImpact(0.9);
|
||||||
|
detector.update();
|
||||||
|
|
||||||
|
// Motor should stop
|
||||||
|
assertEquals(0.0, motor.getPower(), 0.001);
|
||||||
|
assertTrue(detector.hasCollision());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGentleContactDetected() {
|
||||||
|
// Simulate gentle touch (above threshold)
|
||||||
|
sensor.simulateImpact(0.6);
|
||||||
|
detector.update();
|
||||||
|
|
||||||
|
assertTrue(detector.hasCollision());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testBelowThresholdIgnored() {
|
||||||
|
motor.setPower(0.5);
|
||||||
|
|
||||||
|
// Simulate light vibration (below threshold)
|
||||||
|
sensor.simulateImpact(0.3);
|
||||||
|
detector.update();
|
||||||
|
|
||||||
|
// Should not register as collision
|
||||||
|
assertFalse(detector.hasCollision());
|
||||||
|
assertEquals(0.5, motor.getPower(), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCollisionClearsWhenSensorReleased() {
|
||||||
|
// Hit wall
|
||||||
|
sensor.simulateImpact(0.8);
|
||||||
|
detector.update();
|
||||||
|
assertTrue(detector.hasCollision());
|
||||||
|
|
||||||
|
// Back away from wall
|
||||||
|
sensor.reset();
|
||||||
|
detector.update();
|
||||||
|
|
||||||
|
// Collision flag should clear
|
||||||
|
assertFalse(detector.hasCollision());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testMultipleImpacts() {
|
||||||
|
// First impact
|
||||||
|
sensor.simulateImpact(0.7);
|
||||||
|
detector.update();
|
||||||
|
assertTrue(detector.hasCollision());
|
||||||
|
|
||||||
|
// Clear
|
||||||
|
sensor.reset();
|
||||||
|
detector.update();
|
||||||
|
assertFalse(detector.hasCollision());
|
||||||
|
|
||||||
|
// Second impact
|
||||||
|
sensor.simulateImpact(0.8);
|
||||||
|
detector.update();
|
||||||
|
assertTrue(detector.hasCollision());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Benefits
|
||||||
|
|
||||||
|
### 1. **Test Real Scenarios Without Hardware**
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testRobotBouncesOffWall() {
|
||||||
|
// Simulate approach
|
||||||
|
motor.setPower(0.8);
|
||||||
|
|
||||||
|
// Hit wall
|
||||||
|
sensor.simulateImpact(0.9);
|
||||||
|
detector.update();
|
||||||
|
|
||||||
|
// Verify emergency stop
|
||||||
|
assertEquals(0.0, motor.getPower());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. **Test Edge Cases**
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testSensorNoise() {
|
||||||
|
// Simulate sensor flutter at threshold
|
||||||
|
sensor.simulateImpact(0.49);
|
||||||
|
detector.update();
|
||||||
|
assertFalse(detector.hasCollision());
|
||||||
|
|
||||||
|
sensor.simulateImpact(0.51);
|
||||||
|
detector.update();
|
||||||
|
assertTrue(detector.hasCollision());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. **Test Timing Issues**
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testRapidImpacts() {
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
sensor.simulateImpact(0.8);
|
||||||
|
detector.update();
|
||||||
|
assertTrue(detector.hasCollision());
|
||||||
|
|
||||||
|
sensor.reset();
|
||||||
|
detector.update();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. **Integration Tests**
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testFullDriveSequence() {
|
||||||
|
// Drive forward
|
||||||
|
motor.setPower(0.5);
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
detector.update();
|
||||||
|
assertFalse(detector.hasCollision());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hit obstacle
|
||||||
|
sensor.simulateImpact(0.8);
|
||||||
|
detector.update();
|
||||||
|
assertEquals(0.0, motor.getPower());
|
||||||
|
|
||||||
|
// Back up
|
||||||
|
motor.setPower(-0.3);
|
||||||
|
sensor.reset();
|
||||||
|
detector.update();
|
||||||
|
|
||||||
|
// Continue backing
|
||||||
|
for (int i = 0; i < 5; i++) {
|
||||||
|
detector.update();
|
||||||
|
assertEquals(-0.3, motor.getPower());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## File Organization
|
||||||
|
|
||||||
|
```
|
||||||
|
my-robot/
|
||||||
|
├── src/main/java/robot/
|
||||||
|
│ ├── hardware/ # Abstractions
|
||||||
|
│ │ ├── MotorController.java ✅ Tests compile
|
||||||
|
│ │ ├── BumpSensor.java ✅ Tests compile
|
||||||
|
│ │ ├── FtcMotorController.java ❌ Excluded from tests
|
||||||
|
│ │ └── FtcBumpSensor.java ❌ Excluded from tests
|
||||||
|
│ │
|
||||||
|
│ ├── subsystems/ # Business Logic
|
||||||
|
│ │ ├── MotorCycler.java ✅ Tests compile
|
||||||
|
│ │ └── CollisionDetector.java ✅ Tests compile
|
||||||
|
│ │
|
||||||
|
│ └── opmodes/ # FTC Integration
|
||||||
|
│ └── MotorCycleOpMode.java ❌ Excluded from tests
|
||||||
|
│
|
||||||
|
└── src/test/java/robot/
|
||||||
|
├── hardware/ # Mocks
|
||||||
|
│ ├── MockMotorController.java
|
||||||
|
│ └── MockBumpSensor.java
|
||||||
|
│
|
||||||
|
└── subsystems/ # Tests
|
||||||
|
├── MotorCyclerTest.java
|
||||||
|
└── CollisionDetectorTest.java
|
||||||
|
```
|
||||||
|
|
||||||
|
## Build Configuration Rules
|
||||||
|
|
||||||
|
In `build.gradle.kts`:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
sourceSets {
|
||||||
|
main {
|
||||||
|
java {
|
||||||
|
// Exclude all FTC-dependent code from test compilation
|
||||||
|
exclude(
|
||||||
|
"robot/hardware/Ftc*.java", // All FTC implementations
|
||||||
|
"robot/opmodes/**/*.java" // All OpModes
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This pattern ensures:
|
||||||
|
- ✅ Interfaces and pure logic compile for tests
|
||||||
|
- ✅ Mocks are available in test classpath
|
||||||
|
- ✅ Tests run on Windows JRE instantly
|
||||||
|
- ✅ FTC-dependent code is deployed and compiled on robot
|
||||||
|
- ✅ Same logic runs in tests and on robot
|
||||||
|
|
||||||
|
## Advanced Mocking Patterns
|
||||||
|
|
||||||
|
### Stateful Mock (Servo with Position Memory)
|
||||||
|
```java
|
||||||
|
public class MockServo implements ServoController {
|
||||||
|
private double position = 0.5;
|
||||||
|
private double speed = 1.0; // Instant by default
|
||||||
|
|
||||||
|
public void setSpeed(double speed) {
|
||||||
|
this.speed = speed;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setPosition(double target) {
|
||||||
|
// Simulate gradual movement
|
||||||
|
double delta = target - position;
|
||||||
|
position += delta * speed;
|
||||||
|
position = Math.max(0.0, Math.min(1.0, position));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getPosition() {
|
||||||
|
return position;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Mock with Latency
|
||||||
|
```java
|
||||||
|
public class MockGyro implements GyroSensor {
|
||||||
|
private double heading = 0.0;
|
||||||
|
private long lastUpdateTime = 0;
|
||||||
|
private double drift = 0.1; // Degrees per second drift
|
||||||
|
|
||||||
|
public void simulateRotation(double degrees, long timeMs) {
|
||||||
|
heading += degrees;
|
||||||
|
heading = (heading + 360) % 360;
|
||||||
|
lastUpdateTime = timeMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getHeading(long currentTime) {
|
||||||
|
// Simulate sensor drift over time
|
||||||
|
long elapsed = currentTime - lastUpdateTime;
|
||||||
|
double driftError = (elapsed / 1000.0) * drift;
|
||||||
|
return (heading + driftError) % 360;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Mock with Failure Modes
|
||||||
|
```java
|
||||||
|
public class MockDistanceSensor implements DistanceSensor {
|
||||||
|
private double distance = 100.0;
|
||||||
|
private boolean connected = true;
|
||||||
|
private double noise = 0.0;
|
||||||
|
|
||||||
|
public void simulateDisconnect() {
|
||||||
|
connected = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNoise(double stdDev) {
|
||||||
|
this.noise = stdDev;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getDistance() throws SensorException {
|
||||||
|
if (!connected) {
|
||||||
|
throw new SensorException("Sensor disconnected");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add Gaussian noise
|
||||||
|
double noisyDistance = distance + (Math.random() - 0.5) * noise;
|
||||||
|
return Math.max(0, noisyDistance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Why This Matters
|
||||||
|
|
||||||
|
Traditional FTC development:
|
||||||
|
- ❌ Can't test without robot
|
||||||
|
- ❌ Long iteration cycles (code → deploy → test → repeat)
|
||||||
|
- ❌ Hard to test edge cases
|
||||||
|
- ❌ Integration issues found late
|
||||||
|
|
||||||
|
Weevil + proper mocking:
|
||||||
|
- ✅ Test instantly on PC
|
||||||
|
- ✅ Rapid iteration (code → test → fix)
|
||||||
|
- ✅ Comprehensive edge case coverage
|
||||||
|
- ✅ Catch bugs before robot practice
|
||||||
|
|
||||||
|
**You're not just testing motor values - you're simulating complete scenarios: wall collisions, sensor failures, timing issues, state machines, everything!**
|
||||||
|
|
||||||
|
This is professional robotics software engineering.
|
||||||
410
templates/testing/TESTING_SHOWCASE.md
Normal file
410
templates/testing/TESTING_SHOWCASE.md
Normal file
@@ -0,0 +1,410 @@
|
|||||||
|
# Testing Showcase: Professional Robotics Without Hardware
|
||||||
|
|
||||||
|
This project demonstrates **industry-standard testing practices** for robotics code.
|
||||||
|
|
||||||
|
## The Revolutionary Idea
|
||||||
|
|
||||||
|
**You can test robot logic without a robot!**
|
||||||
|
|
||||||
|
Traditional FTC:
|
||||||
|
- Write code
|
||||||
|
- Deploy to robot (5+ minutes)
|
||||||
|
- Test on robot
|
||||||
|
- Find bug
|
||||||
|
- Repeat...
|
||||||
|
|
||||||
|
With proper testing:
|
||||||
|
- Write code
|
||||||
|
- Run tests (2 seconds)
|
||||||
|
- Fix bugs instantly
|
||||||
|
- Deploy confident code to robot
|
||||||
|
|
||||||
|
## Test Categories in This Project
|
||||||
|
|
||||||
|
### 1. Unit Tests (Component-Level)
|
||||||
|
|
||||||
|
Test individual behaviors in isolation.
|
||||||
|
|
||||||
|
**Example: Motor Power Levels**
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testFullSpeedWhenFar() {
|
||||||
|
sensor.setDistance(100.0); // Far from wall
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
assertEquals(0.6, motor.getPower(), 0.001, // Full speed
|
||||||
|
"Should drive at full speed when far");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**What this tests:**
|
||||||
|
- Speed control logic
|
||||||
|
- Distance threshold detection
|
||||||
|
- Motor power calculation
|
||||||
|
|
||||||
|
**Time to run:** ~5 milliseconds
|
||||||
|
|
||||||
|
### 2. System Tests (Complete Scenarios)
|
||||||
|
|
||||||
|
Test entire sequences working together.
|
||||||
|
|
||||||
|
**Example: Complete Autonomous Mission**
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testCompleteAutonomousMission() {
|
||||||
|
// Phase 1: Drive 100cm to wall
|
||||||
|
distanceSensor.setDistance(100.0);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
while (wallApproach.getState() != STOPPED) {
|
||||||
|
wallApproach.update();
|
||||||
|
distanceSensor.approach(motor.getPower() * 2.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phase 2: Turn 90° right
|
||||||
|
turnController.turnTo(90);
|
||||||
|
|
||||||
|
while (turnController.getState() == TURNING) {
|
||||||
|
turnController.update();
|
||||||
|
gyro.rotate(motor.getPower() * 2.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify complete mission success
|
||||||
|
assertEquals(STOPPED, wallApproach.getState());
|
||||||
|
assertEquals(90, gyro.getHeading(), 2.0);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**What this tests:**
|
||||||
|
- Multiple subsystems coordinating
|
||||||
|
- State transitions between phases
|
||||||
|
- Sensor data flowing correctly
|
||||||
|
- Complete mission execution
|
||||||
|
|
||||||
|
**Time to run:** ~50 milliseconds
|
||||||
|
|
||||||
|
### 3. Edge Case Tests (Failure Modes)
|
||||||
|
|
||||||
|
Test things that are hard/dangerous to test on a real robot.
|
||||||
|
|
||||||
|
**Example: Sensor Failure**
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testSensorFailureHandling() {
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
// Sensor suddenly disconnects!
|
||||||
|
sensor.simulateFailure();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Robot should safely stop
|
||||||
|
assertEquals(ERROR, wallApproach.getState());
|
||||||
|
assertEquals(0.0, motor.getPower());
|
||||||
|
assertTrue(wallApproach.hasSensorError());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**What this tests:**
|
||||||
|
- Error detection
|
||||||
|
- Safe shutdown procedures
|
||||||
|
- Graceful degradation
|
||||||
|
- Diagnostic reporting
|
||||||
|
|
||||||
|
**Time to run:** ~2 milliseconds
|
||||||
|
|
||||||
|
**Why this matters:**
|
||||||
|
- Can't safely disconnect sensors on real robot during testing
|
||||||
|
- Would risk crashing robot into wall
|
||||||
|
- Tests this scenario hundreds of times instantly
|
||||||
|
|
||||||
|
### 4. Integration Tests (System-Level)
|
||||||
|
|
||||||
|
Test multiple subsystems interacting realistically.
|
||||||
|
|
||||||
|
**Example: Square Pattern Navigation**
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testSquarePattern() {
|
||||||
|
for (int side = 1; side <= 4; side++) {
|
||||||
|
// Drive forward to wall
|
||||||
|
distanceSensor.setDistance(50.0);
|
||||||
|
wallApproach.start();
|
||||||
|
simulateDriving();
|
||||||
|
|
||||||
|
// Turn 90° right
|
||||||
|
turnController.turnTo(side * 90);
|
||||||
|
simulateTurning();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should complete square and face original direction
|
||||||
|
assertTrue(Math.abs(gyro.getHeading()) <= 2.0);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**What this tests:**
|
||||||
|
- Sequential operations
|
||||||
|
- Repeated patterns
|
||||||
|
- Accumulated errors
|
||||||
|
- Return to starting position
|
||||||
|
|
||||||
|
**Time to run:** ~200 milliseconds
|
||||||
|
|
||||||
|
## Real-World Scenarios You Can Test
|
||||||
|
|
||||||
|
### Scenario 1: Approaching Moving Target
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testApproachingMovingTarget() {
|
||||||
|
distanceSensor.setDistance(100.0);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
for (int i = 0; i < 50; i++) {
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Target is also moving away!
|
||||||
|
distanceSensor.approach(motor.getPower() * 2.0 - 0.5);
|
||||||
|
|
||||||
|
// Robot should still eventually catch up
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(distanceSensor.getDistanceCm() < 15.0);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scenario 2: Noisy Sensor Data
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testHandlesNoisySensors() {
|
||||||
|
sensor.setNoise(2.0); // ±2cm random jitter
|
||||||
|
sensor.setDistance(50.0);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
// Run 100 updates with noisy data
|
||||||
|
for (int i = 0; i < 100; i++) {
|
||||||
|
wallApproach.update();
|
||||||
|
sensor.approach(0.5);
|
||||||
|
|
||||||
|
// Should not oscillate wildly or crash
|
||||||
|
assertTrue(motor.getPower() >= 0);
|
||||||
|
assertTrue(motor.getPower() <= 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scenario 3: Gyro Drift Compensation
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testCompensatesForGyroDrift() {
|
||||||
|
gyro.setHeading(0);
|
||||||
|
gyro.setDrift(0.5); // 0.5° per second drift
|
||||||
|
|
||||||
|
turnController.turnTo(90);
|
||||||
|
|
||||||
|
// Simulate turn with drift
|
||||||
|
for (int i = 0; i < 100; i++) {
|
||||||
|
turnController.update();
|
||||||
|
gyro.rotate(motor.getPower() * 2.0);
|
||||||
|
Thread.sleep(10); // Let drift accumulate
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should still reach target despite drift
|
||||||
|
assertTrue(Math.abs(gyro.getHeading() - 90) <= 2.0);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scenario 4: Battery Voltage Drop
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testLowBatteryCompensation() {
|
||||||
|
MockBattery battery = new MockBattery();
|
||||||
|
MotorController motor = new VoltageCompensatedMotor(battery);
|
||||||
|
|
||||||
|
// Full battery
|
||||||
|
battery.setVoltage(12.5);
|
||||||
|
motor.setPower(0.5);
|
||||||
|
assertEquals(0.5, motor.getActualPower());
|
||||||
|
|
||||||
|
// Low battery
|
||||||
|
battery.setVoltage(11.0);
|
||||||
|
motor.setPower(0.5);
|
||||||
|
assertTrue(motor.getActualPower() > 0.5, // Compensated up
|
||||||
|
"Should increase power to compensate for voltage drop");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing Benefits
|
||||||
|
|
||||||
|
### Speed
|
||||||
|
- **41 tests run in < 2 seconds**
|
||||||
|
- No deployment time
|
||||||
|
- No robot setup time
|
||||||
|
- Instant feedback
|
||||||
|
|
||||||
|
### Reliability
|
||||||
|
- Test edge cases safely
|
||||||
|
- Test failure modes
|
||||||
|
- Test thousands of scenarios
|
||||||
|
- Catch bugs before robot time
|
||||||
|
|
||||||
|
### Confidence
|
||||||
|
- Know code works before deploying
|
||||||
|
- Automated regression testing
|
||||||
|
- Safe refactoring
|
||||||
|
- Professional quality
|
||||||
|
|
||||||
|
### Learning
|
||||||
|
- Students learn professional practices
|
||||||
|
- Industry-standard patterns
|
||||||
|
- Test-driven development
|
||||||
|
- Debugging without hardware
|
||||||
|
|
||||||
|
## Test Metrics
|
||||||
|
|
||||||
|
```
|
||||||
|
Total Tests: 41
|
||||||
|
- MotorCyclerTest: 8 tests
|
||||||
|
- WallApproachTest: 13 tests
|
||||||
|
- TurnControllerTest: 15 tests
|
||||||
|
- AutonomousIntegrationTest: 5 tests
|
||||||
|
|
||||||
|
Total Runtime: < 2 seconds
|
||||||
|
Lines of Test Code: ~1,200
|
||||||
|
Lines of Production Code: ~500
|
||||||
|
Test Coverage: Excellent
|
||||||
|
|
||||||
|
Bugs Caught Before Robot Testing: Countless!
|
||||||
|
```
|
||||||
|
|
||||||
|
## The Pattern for Students
|
||||||
|
|
||||||
|
Teaching students this approach gives them:
|
||||||
|
|
||||||
|
1. **Immediate feedback** - No waiting for robot
|
||||||
|
2. **Safe experimentation** - Can't break robot in tests
|
||||||
|
3. **Professional skills** - Industry-standard practices
|
||||||
|
4. **Better code** - Testable code is well-designed code
|
||||||
|
5. **Confidence** - Know it works before deploying
|
||||||
|
|
||||||
|
## Comparison
|
||||||
|
|
||||||
|
### Traditional FTC Development
|
||||||
|
|
||||||
|
```
|
||||||
|
Write code (10 min)
|
||||||
|
↓
|
||||||
|
Deploy to robot (5 min)
|
||||||
|
↓
|
||||||
|
Test on robot (10 min)
|
||||||
|
↓
|
||||||
|
Find bug
|
||||||
|
↓
|
||||||
|
Repeat...
|
||||||
|
|
||||||
|
Time per iteration: ~25 minutes
|
||||||
|
Bugs found: Late (on robot)
|
||||||
|
Risk: High (can damage robot)
|
||||||
|
```
|
||||||
|
|
||||||
|
### With Testing
|
||||||
|
|
||||||
|
```
|
||||||
|
Write code (10 min)
|
||||||
|
↓
|
||||||
|
Run tests (2 sec)
|
||||||
|
↓
|
||||||
|
Fix bugs immediately (5 min)
|
||||||
|
↓
|
||||||
|
Deploy confident code (5 min)
|
||||||
|
↓
|
||||||
|
Works on robot!
|
||||||
|
|
||||||
|
Time per iteration: ~20 minutes (first deploy!)
|
||||||
|
Bugs found: Early (in tests)
|
||||||
|
Risk: Low (robot rarely crashes)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Testing Patterns
|
||||||
|
|
||||||
|
### Parameterized Tests
|
||||||
|
|
||||||
|
Test the same logic with different inputs:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@ParameterizedTest
|
||||||
|
@ValueSource(doubles = {10, 20, 30, 40, 50})
|
||||||
|
void testDifferentStopDistances(double distance) {
|
||||||
|
sensor.setDistance(100.0);
|
||||||
|
wallApproach = new WallApproach(sensor, motor, distance);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
simulateDriving();
|
||||||
|
|
||||||
|
assertTrue(sensor.getDistanceCm() <= distance + 2);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### State Machine Verification
|
||||||
|
|
||||||
|
Test all state transitions:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testAllStateTransitions() {
|
||||||
|
// INIT → APPROACHING
|
||||||
|
wallApproach.start();
|
||||||
|
assertEquals(APPROACHING, wallApproach.getState());
|
||||||
|
|
||||||
|
// APPROACHING → SLOWING
|
||||||
|
sensor.setDistance(25.0);
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(SLOWING, wallApproach.getState());
|
||||||
|
|
||||||
|
// SLOWING → STOPPED
|
||||||
|
sensor.setDistance(10.0);
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(STOPPED, wallApproach.getState());
|
||||||
|
|
||||||
|
// STOPPED → STOPPED (stays stopped)
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(STOPPED, wallApproach.getState());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Performance Testing
|
||||||
|
|
||||||
|
Verify code runs fast enough:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void testUpdatePerformance() {
|
||||||
|
long startTime = System.nanoTime();
|
||||||
|
|
||||||
|
for (int i = 0; i < 1000; i++) {
|
||||||
|
wallApproach.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
long elapsedMs = (System.nanoTime() - startTime) / 1_000_000;
|
||||||
|
|
||||||
|
assertTrue(elapsedMs < 100,
|
||||||
|
"1000 updates should complete in < 100ms");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Conclusion
|
||||||
|
|
||||||
|
Testing without hardware is **not a compromise** - it's actually **better**:
|
||||||
|
|
||||||
|
- Faster development
|
||||||
|
- Safer testing
|
||||||
|
- More thorough coverage
|
||||||
|
- Professional practices
|
||||||
|
|
||||||
|
This is how real robotics companies (Boston Dynamics, Tesla, SpaceX) develop robots.
|
||||||
|
|
||||||
|
Your students are learning the same techniques used to land rockets and build autonomous vehicles!
|
||||||
80
templates/testing/build.gradle
Normal file
80
templates/testing/build.gradle
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java'
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
google()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// Testing (runs on PC without SDK)
|
||||||
|
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0'
|
||||||
|
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||||
|
testImplementation 'org.mockito:mockito-core:5.5.0'
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_11
|
||||||
|
targetCompatibility = JavaVersion.VERSION_11
|
||||||
|
}
|
||||||
|
|
||||||
|
// CRITICAL: Exclude FTC-dependent files from test compilation
|
||||||
|
sourceSets {
|
||||||
|
main {
|
||||||
|
java {
|
||||||
|
exclude 'robot/hardware/FtcMotorController.java'
|
||||||
|
exclude 'robot/hardware/FtcDistanceSensor.java'
|
||||||
|
exclude 'robot/hardware/FtcGyroSensor.java'
|
||||||
|
exclude 'robot/opmodes/**/*.java'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test {
|
||||||
|
useJUnitPlatform()
|
||||||
|
testLogging {
|
||||||
|
events "passed", "skipped", "failed"
|
||||||
|
showStandardStreams = false
|
||||||
|
exceptionFormat = 'full'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Task to deploy code to FTC SDK
|
||||||
|
task deployToSDK(type: Copy) {
|
||||||
|
group = 'ftc'
|
||||||
|
description = 'Copy code to FTC SDK TeamCode for deployment'
|
||||||
|
|
||||||
|
def sdkDir = 'C:\\Users\\Eric\\.weevil\\ftc-sdk'
|
||||||
|
|
||||||
|
from('src/main/java') {
|
||||||
|
include 'robot/**/*.java'
|
||||||
|
}
|
||||||
|
|
||||||
|
into "$sdkDir/TeamCode/src/main/java"
|
||||||
|
|
||||||
|
doLast {
|
||||||
|
println '✓ Code deployed to TeamCode'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Task to build APK
|
||||||
|
task buildApk(type: Exec) {
|
||||||
|
group = 'ftc'
|
||||||
|
description = 'Build APK using FTC SDK'
|
||||||
|
|
||||||
|
dependsOn deployToSDK
|
||||||
|
|
||||||
|
def sdkDir = 'C:\\Users\\Eric\\.weevil\\ftc-sdk'
|
||||||
|
workingDir = file(sdkDir)
|
||||||
|
|
||||||
|
if (System.getProperty('os.name').toLowerCase().contains('windows')) {
|
||||||
|
commandLine 'cmd', '/c', 'gradlew.bat', 'assembleDebug'
|
||||||
|
} else {
|
||||||
|
commandLine './gradlew', 'assembleDebug'
|
||||||
|
}
|
||||||
|
|
||||||
|
doLast {
|
||||||
|
println '✓ APK built successfully'
|
||||||
|
}
|
||||||
|
}
|
||||||
84
templates/testing/build.gradle.kts
Normal file
84
templates/testing/build.gradle.kts
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
plugins {
|
||||||
|
java
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
google()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// Testing (runs on PC without SDK)
|
||||||
|
testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
|
||||||
|
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||||
|
testImplementation("org.mockito:mockito-core:5.5.0")
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_11
|
||||||
|
targetCompatibility = JavaVersion.VERSION_11
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure source sets to exclude FTC-dependent code from test compilation
|
||||||
|
sourceSets {
|
||||||
|
main {
|
||||||
|
java {
|
||||||
|
// Exclude FTC-dependent files from test compilation
|
||||||
|
// These files use FTC SDK classes that don't exist on Windows
|
||||||
|
exclude(
|
||||||
|
"robot/hardware/FtcMotorController.java",
|
||||||
|
"robot/hardware/FtcDistanceSensor.java",
|
||||||
|
"robot/hardware/FtcGyroSensor.java",
|
||||||
|
"robot/opmodes/**/*.java"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.test {
|
||||||
|
useJUnitPlatform()
|
||||||
|
testLogging {
|
||||||
|
events("passed", "skipped", "failed")
|
||||||
|
showStandardStreams = false
|
||||||
|
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Task to deploy code to FTC SDK
|
||||||
|
tasks.register<Copy>("deployToSDK") {
|
||||||
|
group = "ftc"
|
||||||
|
description = "Copy code to FTC SDK TeamCode for deployment"
|
||||||
|
|
||||||
|
val sdkDir = "C:\\Users\\Eric\\.weevil\\ftc-sdk"
|
||||||
|
|
||||||
|
from("src/main/java") {
|
||||||
|
include("robot/**/*.java")
|
||||||
|
}
|
||||||
|
|
||||||
|
into(layout.projectDirectory.dir("$sdkDir/TeamCode/src/main/java"))
|
||||||
|
|
||||||
|
doLast {
|
||||||
|
println("✓ Code deployed to TeamCode")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Task to build APK
|
||||||
|
tasks.register<Exec>("buildApk") {
|
||||||
|
group = "ftc"
|
||||||
|
description = "Build APK using FTC SDK"
|
||||||
|
|
||||||
|
dependsOn("deployToSDK")
|
||||||
|
|
||||||
|
val sdkDir = "C:\\Users\\Eric\\.weevil\\ftc-sdk"
|
||||||
|
workingDir = file(sdkDir)
|
||||||
|
|
||||||
|
commandLine = if (System.getProperty("os.name").lowercase().contains("windows")) {
|
||||||
|
listOf("cmd", "/c", "gradlew.bat", "assembleDebug")
|
||||||
|
} else {
|
||||||
|
listOf("./gradlew", "assembleDebug")
|
||||||
|
}
|
||||||
|
|
||||||
|
doLast {
|
||||||
|
println("✓ APK built successfully")
|
||||||
|
}
|
||||||
|
}
|
||||||
62
templates/testing/build.gradle.template
Normal file
62
templates/testing/build.gradle.template
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
// Build configuration for {{PROJECT_NAME}}
|
||||||
|
// This file is managed by the FTC SDK
|
||||||
|
|
||||||
|
buildscript {
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
google()
|
||||||
|
}
|
||||||
|
dependencies {
|
||||||
|
classpath 'com.android.tools.build:gradle:8.1.0'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
apply plugin: 'com.android.application'
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace 'org.firstinspires.ftc.{{PACKAGE_NAME}}'
|
||||||
|
compileSdk 34
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId 'org.firstinspires.ftc.{{PACKAGE_NAME}}'
|
||||||
|
minSdk 24
|
||||||
|
//noinspection ExpiredTargetSdkVersion
|
||||||
|
targetSdk 28
|
||||||
|
|
||||||
|
versionCode 1
|
||||||
|
versionName "1.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility JavaVersion.VERSION_1_8
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceSets {
|
||||||
|
main {
|
||||||
|
java {
|
||||||
|
srcDir 'src/main/java'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
test {
|
||||||
|
java {
|
||||||
|
srcDir 'src/test/java'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
google()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation 'org.firstinspires.ftc:RobotCore:10.1.1'
|
||||||
|
implementation 'org.firstinspires.ftc:Hardware:10.1.1'
|
||||||
|
implementation 'org.firstinspires.ftc:FtcCommon:10.1.1'
|
||||||
|
implementation 'androidx.appcompat:appcompat:1.6.1'
|
||||||
|
|
||||||
|
testImplementation 'junit:junit:4.13.2'
|
||||||
|
testImplementation 'org.mockito:mockito-core:5.3.1'
|
||||||
|
}
|
||||||
1
templates/testing/settings.gradle.kts
Normal file
1
templates/testing/settings.gradle.kts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
rootProject.name = "my-robot"
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for distance sensors (ultrasonic, time-of-flight, etc.).
|
||||||
|
* This abstraction allows testing distance-based behaviors without physical sensors.
|
||||||
|
*/
|
||||||
|
public interface DistanceSensor {
|
||||||
|
/**
|
||||||
|
* Get the current distance reading in centimeters.
|
||||||
|
* @return distance in cm, or -1 if sensor error
|
||||||
|
*/
|
||||||
|
double getDistanceCm();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the sensor has valid data.
|
||||||
|
* @return true if sensor is working and has valid reading
|
||||||
|
*/
|
||||||
|
boolean isValid();
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
import com.qualcomm.robotcore.hardware.DistanceSensor;
|
||||||
|
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FTC implementation of DistanceSensor interface.
|
||||||
|
* This file will be EXCLUDED from test compilation.
|
||||||
|
*/
|
||||||
|
public class FtcDistanceSensor implements robot.hardware.DistanceSensor {
|
||||||
|
private final DistanceSensor sensor;
|
||||||
|
|
||||||
|
public FtcDistanceSensor(DistanceSensor sensor) {
|
||||||
|
this.sensor = sensor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getDistanceCm() {
|
||||||
|
return sensor.getDistance(DistanceUnit.CM);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isValid() {
|
||||||
|
double dist = getDistanceCm();
|
||||||
|
return dist > 0 && dist < 8190; // Valid range for REV sensors
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
import com.qualcomm.robotcore.hardware.IMU;
|
||||||
|
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
|
||||||
|
import org.firstinspires.ftc.robotcore.external.navigation.YawPitchRollAngles;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FTC implementation of GyroSensor using REV Hub IMU.
|
||||||
|
* This file will be EXCLUDED from test compilation.
|
||||||
|
*/
|
||||||
|
public class FtcGyroSensor implements GyroSensor {
|
||||||
|
private final IMU imu;
|
||||||
|
|
||||||
|
public FtcGyroSensor(IMU imu) {
|
||||||
|
this.imu = imu;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getHeading() {
|
||||||
|
YawPitchRollAngles angles = imu.getRobotYawPitchRollAngles();
|
||||||
|
double heading = angles.getYaw(AngleUnit.DEGREES);
|
||||||
|
|
||||||
|
// Normalize to 0-359
|
||||||
|
while (heading < 0) heading += 360;
|
||||||
|
while (heading >= 360) heading -= 360;
|
||||||
|
|
||||||
|
return heading;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
imu.resetYaw();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isCalibrated() {
|
||||||
|
return imu.getRobotYawPitchRollAngles() != null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
import com.qualcomm.robotcore.hardware.DcMotor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FTC SDK implementation of MotorController.
|
||||||
|
* This wraps the FTC DcMotor class and will only be available when deployed to the robot.
|
||||||
|
*/
|
||||||
|
public class FtcMotorController implements MotorController {
|
||||||
|
private final DcMotor motor;
|
||||||
|
|
||||||
|
public FtcMotorController(DcMotor motor) {
|
||||||
|
this.motor = motor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setPower(double power) {
|
||||||
|
motor.setPower(power);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getPower() {
|
||||||
|
return motor.getPower();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for gyroscope/IMU sensors.
|
||||||
|
* Provides heading information for navigation and autonomous driving.
|
||||||
|
*/
|
||||||
|
public interface GyroSensor {
|
||||||
|
/**
|
||||||
|
* Get the current heading in degrees.
|
||||||
|
* @return heading from 0-359 degrees (0 = initial orientation)
|
||||||
|
*/
|
||||||
|
double getHeading();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset the heading to zero.
|
||||||
|
*/
|
||||||
|
void reset();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the gyro is calibrated and ready.
|
||||||
|
* @return true if gyro is working properly
|
||||||
|
*/
|
||||||
|
boolean isCalibrated();
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for motor control.
|
||||||
|
* This abstraction allows us to test our logic without actual hardware.
|
||||||
|
*/
|
||||||
|
public interface MotorController {
|
||||||
|
/**
|
||||||
|
* Set the motor power.
|
||||||
|
* @param power Power level from -1.0 (full reverse) to 1.0 (full forward)
|
||||||
|
*/
|
||||||
|
void setPower(double power);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current motor power setting.
|
||||||
|
* @return Current power level
|
||||||
|
*/
|
||||||
|
double getPower();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the motor is currently running.
|
||||||
|
* @return true if power is non-zero
|
||||||
|
*/
|
||||||
|
default boolean isRunning() {
|
||||||
|
return Math.abs(getPower()) > 0.001;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package robot.opmodes;
|
||||||
|
|
||||||
|
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
|
||||||
|
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
|
||||||
|
import com.qualcomm.robotcore.hardware.DcMotor;
|
||||||
|
|
||||||
|
import robot.hardware.FtcMotorController;
|
||||||
|
import robot.subsystems.MotorCycler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simple TeleOp mode that cycles a motor on/off.
|
||||||
|
*
|
||||||
|
* This demonstrates:
|
||||||
|
* - Clean separation between hardware abstraction and logic
|
||||||
|
* - Testable subsystems (MotorCycler can be tested without FTC SDK)
|
||||||
|
* - Simple, readable OpMode code
|
||||||
|
*/
|
||||||
|
@TeleOp(name = "Motor Cycle Demo", group = "Demo")
|
||||||
|
public class MotorCycleOpMode extends OpMode {
|
||||||
|
private MotorCycler motorCycler;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init() {
|
||||||
|
// Get the motor from the hardware map
|
||||||
|
DcMotor motor = hardwareMap.get(DcMotor.class, "motor");
|
||||||
|
|
||||||
|
// Wrap it in our abstraction
|
||||||
|
FtcMotorController motorController = new FtcMotorController(motor);
|
||||||
|
|
||||||
|
// Create the cycler: 2 seconds on, 1 second off
|
||||||
|
motorCycler = new MotorCycler(motorController, 2000, 1000, 0.5);
|
||||||
|
motorCycler.init();
|
||||||
|
|
||||||
|
telemetry.addData("Status", "Initialized - Ready to cycle motor");
|
||||||
|
telemetry.addData("Pattern", "2s ON, 1s OFF");
|
||||||
|
telemetry.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void loop() {
|
||||||
|
// Update the cycler with current time
|
||||||
|
motorCycler.update(System.currentTimeMillis());
|
||||||
|
|
||||||
|
// Display status
|
||||||
|
telemetry.addData("Motor State", motorCycler.getState());
|
||||||
|
telemetry.addData("Time in State", "%.1f seconds",
|
||||||
|
motorCycler.getTimeInState(System.currentTimeMillis()) / 1000.0);
|
||||||
|
telemetry.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stop() {
|
||||||
|
motorCycler.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import robot.hardware.MotorController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subsystem that cycles a motor on and off with specific timing.
|
||||||
|
* This demonstrates clean separation between logic and hardware.
|
||||||
|
*/
|
||||||
|
public class MotorCycler {
|
||||||
|
private final MotorController motor;
|
||||||
|
private final long onDurationMs;
|
||||||
|
private final long offDurationMs;
|
||||||
|
private final double motorPower;
|
||||||
|
|
||||||
|
private MotorCycleState state;
|
||||||
|
private long stateStartTime;
|
||||||
|
|
||||||
|
public enum MotorCycleState {
|
||||||
|
ON, OFF
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a motor cycler with custom timing.
|
||||||
|
* @param motor The motor to control
|
||||||
|
* @param onDurationMs How long to run the motor (milliseconds)
|
||||||
|
* @param offDurationMs How long to pause between runs (milliseconds)
|
||||||
|
* @param motorPower Power level to use when on (0.0 to 1.0)
|
||||||
|
*/
|
||||||
|
public MotorCycler(MotorController motor, long onDurationMs, long offDurationMs, double motorPower) {
|
||||||
|
this.motor = motor;
|
||||||
|
this.onDurationMs = onDurationMs;
|
||||||
|
this.offDurationMs = offDurationMs;
|
||||||
|
this.motorPower = motorPower;
|
||||||
|
this.state = MotorCycleState.OFF;
|
||||||
|
this.stateStartTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a motor cycler with default power (0.5).
|
||||||
|
*/
|
||||||
|
public MotorCycler(MotorController motor, long onDurationMs, long offDurationMs) {
|
||||||
|
this(motor, onDurationMs, offDurationMs, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the cycler (call once at startup).
|
||||||
|
*/
|
||||||
|
public void init() {
|
||||||
|
state = MotorCycleState.OFF;
|
||||||
|
stateStartTime = System.currentTimeMillis();
|
||||||
|
motor.setPower(0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the motor state based on elapsed time.
|
||||||
|
* Call this repeatedly in your main loop.
|
||||||
|
* @param currentTimeMs Current time in milliseconds
|
||||||
|
*/
|
||||||
|
public void update(long currentTimeMs) {
|
||||||
|
long elapsed = currentTimeMs - stateStartTime;
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
case OFF:
|
||||||
|
if (elapsed >= offDurationMs) {
|
||||||
|
// Time to turn on
|
||||||
|
motor.setPower(motorPower);
|
||||||
|
state = MotorCycleState.ON;
|
||||||
|
stateStartTime = currentTimeMs;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ON:
|
||||||
|
if (elapsed >= onDurationMs) {
|
||||||
|
// Time to turn off
|
||||||
|
motor.setPower(0.0);
|
||||||
|
state = MotorCycleState.OFF;
|
||||||
|
stateStartTime = currentTimeMs;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop the motor and reset to initial state.
|
||||||
|
*/
|
||||||
|
public void stop() {
|
||||||
|
motor.setPower(0.0);
|
||||||
|
state = MotorCycleState.OFF;
|
||||||
|
stateStartTime = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current cycle state.
|
||||||
|
*/
|
||||||
|
public MotorCycleState getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get how long we've been in the current state (ms).
|
||||||
|
*/
|
||||||
|
public long getTimeInState(long currentTimeMs) {
|
||||||
|
return currentTimeMs - stateStartTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import robot.hardware.GyroSensor;
|
||||||
|
import robot.hardware.MotorController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subsystem that turns the robot to a target heading using gyro feedback.
|
||||||
|
*
|
||||||
|
* This demonstrates closed-loop control:
|
||||||
|
* - Proportional control (turn faster when far from target)
|
||||||
|
* - Threshold detection (when close enough to target)
|
||||||
|
* - Direction selection (shortest path to target)
|
||||||
|
*
|
||||||
|
* Pure Java - fully testable without hardware!
|
||||||
|
*/
|
||||||
|
public class TurnController {
|
||||||
|
private final GyroSensor gyro;
|
||||||
|
private final MotorController leftMotor;
|
||||||
|
private final MotorController rightMotor;
|
||||||
|
|
||||||
|
// Control parameters
|
||||||
|
private final double HEADING_TOLERANCE = 2.0; // Within 2 degrees = success
|
||||||
|
private final double MIN_TURN_POWER = 0.15; // Minimum power to overcome friction
|
||||||
|
private final double MAX_TURN_POWER = 0.5; // Maximum turn speed
|
||||||
|
private final double KP = 0.02; // Proportional gain
|
||||||
|
|
||||||
|
// State
|
||||||
|
private double targetHeading = 0.0;
|
||||||
|
private TurnState state = TurnState.IDLE;
|
||||||
|
|
||||||
|
public enum TurnState {
|
||||||
|
IDLE, // Not turning
|
||||||
|
TURNING, // Actively turning to target
|
||||||
|
COMPLETE // Reached target heading
|
||||||
|
}
|
||||||
|
|
||||||
|
public TurnController(GyroSensor gyro, MotorController leftMotor, MotorController rightMotor) {
|
||||||
|
this.gyro = gyro;
|
||||||
|
this.leftMotor = leftMotor;
|
||||||
|
this.rightMotor = rightMotor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start turning to a target heading.
|
||||||
|
*
|
||||||
|
* @param targetDegrees target heading (0-359)
|
||||||
|
*/
|
||||||
|
public void turnTo(double targetDegrees) {
|
||||||
|
this.targetHeading = normalizeHeading(targetDegrees);
|
||||||
|
this.state = TurnState.TURNING;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the turn controller.
|
||||||
|
* Call this repeatedly in your main loop.
|
||||||
|
*/
|
||||||
|
public void update() {
|
||||||
|
if (state != TurnState.TURNING) {
|
||||||
|
return; // Not actively turning
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!gyro.isCalibrated()) {
|
||||||
|
stop();
|
||||||
|
state = TurnState.IDLE;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
double currentHeading = gyro.getHeading();
|
||||||
|
double error = calculateShortestError(currentHeading, targetHeading);
|
||||||
|
|
||||||
|
// Check if we've reached the target
|
||||||
|
if (Math.abs(error) <= HEADING_TOLERANCE) {
|
||||||
|
stop();
|
||||||
|
state = TurnState.COMPLETE;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Proportional control: turn power proportional to error
|
||||||
|
double turnPower = error * KP;
|
||||||
|
|
||||||
|
// Clamp to min/max power
|
||||||
|
if (Math.abs(turnPower) < MIN_TURN_POWER) {
|
||||||
|
turnPower = Math.signum(turnPower) * MIN_TURN_POWER;
|
||||||
|
}
|
||||||
|
if (Math.abs(turnPower) > MAX_TURN_POWER) {
|
||||||
|
turnPower = Math.signum(turnPower) * MAX_TURN_POWER;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply power: positive error = turn right
|
||||||
|
leftMotor.setPower(turnPower);
|
||||||
|
rightMotor.setPower(-turnPower);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop turning.
|
||||||
|
*/
|
||||||
|
public void stop() {
|
||||||
|
leftMotor.setPower(0.0);
|
||||||
|
rightMotor.setPower(0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate the shortest angular error between two headings.
|
||||||
|
* Returns positive for clockwise, negative for counter-clockwise.
|
||||||
|
*
|
||||||
|
* Example: current=10, target=350 → error=-20 (turn left 20°)
|
||||||
|
* current=350, target=10 → error=+20 (turn right 20°)
|
||||||
|
*/
|
||||||
|
private double calculateShortestError(double current, double target) {
|
||||||
|
double error = target - current;
|
||||||
|
|
||||||
|
// Normalize to -180 to +180
|
||||||
|
while (error > 180) error -= 360;
|
||||||
|
while (error < -180) error += 360;
|
||||||
|
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize heading to 0-359 range.
|
||||||
|
*/
|
||||||
|
private double normalizeHeading(double degrees) {
|
||||||
|
while (degrees < 0) degrees += 360;
|
||||||
|
while (degrees >= 360) degrees -= 360;
|
||||||
|
return degrees;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Getters for testing
|
||||||
|
|
||||||
|
public TurnState getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getTargetHeading() {
|
||||||
|
return targetHeading;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getCurrentHeading() {
|
||||||
|
return gyro.getHeading();
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getHeadingError() {
|
||||||
|
return calculateShortestError(gyro.getHeading(), targetHeading);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import robot.hardware.DistanceSensor;
|
||||||
|
import robot.hardware.MotorController;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subsystem that safely approaches a wall using distance sensor feedback.
|
||||||
|
*
|
||||||
|
* This demonstrates a real robotics control problem:
|
||||||
|
* - Drive fast when far away
|
||||||
|
* - Slow down as you get closer
|
||||||
|
* - Stop before hitting the wall
|
||||||
|
* - Handle sensor failures gracefully
|
||||||
|
*
|
||||||
|
* This is PURE JAVA - no FTC dependencies!
|
||||||
|
* Can be tested instantly on Windows without a robot.
|
||||||
|
*/
|
||||||
|
public class WallApproach {
|
||||||
|
// Hardware interfaces (not FTC classes!)
|
||||||
|
private final DistanceSensor sensor;
|
||||||
|
private final MotorController leftMotor;
|
||||||
|
private final MotorController rightMotor;
|
||||||
|
|
||||||
|
// Configuration constants
|
||||||
|
private final double STOP_DISTANCE_CM = 10.0; // Stop 10cm from wall
|
||||||
|
private final double SLOW_DISTANCE_CM = 30.0; // Start slowing at 30cm
|
||||||
|
private final double FAST_SPEED = 0.6; // Full speed when far
|
||||||
|
private final double SLOW_SPEED = 0.2; // Slow speed when near
|
||||||
|
|
||||||
|
// State tracking
|
||||||
|
private WallApproachState state = WallApproachState.INIT;
|
||||||
|
private boolean sensorError = false;
|
||||||
|
|
||||||
|
public enum WallApproachState {
|
||||||
|
INIT, // Not started
|
||||||
|
APPROACHING, // Driving toward wall
|
||||||
|
SLOWING, // Close to wall, slowing down
|
||||||
|
STOPPED, // At target distance
|
||||||
|
ERROR // Sensor failure
|
||||||
|
}
|
||||||
|
|
||||||
|
public WallApproach(DistanceSensor sensor, MotorController leftMotor, MotorController rightMotor) {
|
||||||
|
this.sensor = sensor;
|
||||||
|
this.leftMotor = leftMotor;
|
||||||
|
this.rightMotor = rightMotor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start the approach sequence.
|
||||||
|
*/
|
||||||
|
public void start() {
|
||||||
|
state = WallApproachState.APPROACHING;
|
||||||
|
sensorError = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the approach logic.
|
||||||
|
* Call this repeatedly in your main loop.
|
||||||
|
*/
|
||||||
|
public void update() {
|
||||||
|
// Check for sensor errors
|
||||||
|
if (!sensor.isValid()) {
|
||||||
|
state = WallApproachState.ERROR;
|
||||||
|
sensorError = true;
|
||||||
|
stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
double distance = sensor.getDistanceCm();
|
||||||
|
|
||||||
|
// State machine logic
|
||||||
|
switch (state) {
|
||||||
|
case INIT:
|
||||||
|
// Do nothing until started
|
||||||
|
break;
|
||||||
|
|
||||||
|
case APPROACHING:
|
||||||
|
if (distance <= STOP_DISTANCE_CM) {
|
||||||
|
// Too close - stop immediately!
|
||||||
|
stop();
|
||||||
|
state = WallApproachState.STOPPED;
|
||||||
|
} else if (distance <= SLOW_DISTANCE_CM) {
|
||||||
|
// Getting close - slow down
|
||||||
|
setMotors(SLOW_SPEED);
|
||||||
|
state = WallApproachState.SLOWING;
|
||||||
|
} else {
|
||||||
|
// Far away - drive fast
|
||||||
|
setMotors(FAST_SPEED);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case SLOWING:
|
||||||
|
if (distance <= STOP_DISTANCE_CM) {
|
||||||
|
// Reached target distance
|
||||||
|
stop();
|
||||||
|
state = WallApproachState.STOPPED;
|
||||||
|
} else if (distance > SLOW_DISTANCE_CM) {
|
||||||
|
// Drifted backward? Speed up again
|
||||||
|
setMotors(FAST_SPEED);
|
||||||
|
state = WallApproachState.APPROACHING;
|
||||||
|
} else {
|
||||||
|
// Continue at slow speed
|
||||||
|
setMotors(SLOW_SPEED);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case STOPPED:
|
||||||
|
// Stay stopped
|
||||||
|
stop();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case ERROR:
|
||||||
|
// Stay stopped in error state
|
||||||
|
stop();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emergency stop.
|
||||||
|
*/
|
||||||
|
public void stop() {
|
||||||
|
leftMotor.setPower(0.0);
|
||||||
|
rightMotor.setPower(0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set both motors to the same speed.
|
||||||
|
*/
|
||||||
|
private void setMotors(double power) {
|
||||||
|
leftMotor.setPower(power);
|
||||||
|
rightMotor.setPower(power);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Getters for testing
|
||||||
|
|
||||||
|
public WallApproachState getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasSensorError() {
|
||||||
|
return sensorError;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double getCurrentDistance() {
|
||||||
|
return sensor.isValid() ? sensor.getDistanceCm() : -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mock implementation of DistanceSensor for testing.
|
||||||
|
*
|
||||||
|
* This mock can simulate:
|
||||||
|
* - Setting specific distances
|
||||||
|
* - Sensor noise/jitter
|
||||||
|
* - Sensor failures
|
||||||
|
* - Gradual distance changes (approaching/retreating)
|
||||||
|
*
|
||||||
|
* Example usage in tests:
|
||||||
|
* MockDistanceSensor sensor = new MockDistanceSensor();
|
||||||
|
* sensor.setDistance(50.0); // Robot is 50cm from wall
|
||||||
|
* sensor.addNoise(2.0); // Add ±2cm random noise
|
||||||
|
*/
|
||||||
|
public class MockDistanceSensor implements DistanceSensor {
|
||||||
|
private double distance = 100.0; // Default: far away
|
||||||
|
private double noiseLevel = 0.0; // Standard deviation of noise
|
||||||
|
private boolean valid = true;
|
||||||
|
private Random random = new Random(12345); // Seeded for reproducible tests
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the distance reading.
|
||||||
|
* @param distanceCm distance in centimeters
|
||||||
|
*/
|
||||||
|
public void setDistance(double distanceCm) {
|
||||||
|
this.distance = distanceCm;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add Gaussian noise to the readings.
|
||||||
|
* Simulates real-world sensor jitter.
|
||||||
|
*
|
||||||
|
* @param stdDev standard deviation of noise in cm
|
||||||
|
*/
|
||||||
|
public void setNoise(double stdDev) {
|
||||||
|
this.noiseLevel = stdDev;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate sensor failure/disconnection.
|
||||||
|
*/
|
||||||
|
public void simulateFailure() {
|
||||||
|
this.valid = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restore sensor to working state.
|
||||||
|
*/
|
||||||
|
public void restore() {
|
||||||
|
this.valid = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate gradual approach (like robot driving toward wall).
|
||||||
|
* @param deltaCm how much closer to get (negative = moving away)
|
||||||
|
*/
|
||||||
|
public void approach(double deltaCm) {
|
||||||
|
this.distance = Math.max(0, this.distance - deltaCm);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getDistanceCm() {
|
||||||
|
if (!valid) {
|
||||||
|
return -1; // Error value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add random noise if configured
|
||||||
|
double noise = 0;
|
||||||
|
if (noiseLevel > 0) {
|
||||||
|
noise = random.nextGaussian() * noiseLevel;
|
||||||
|
}
|
||||||
|
|
||||||
|
return distance + noise;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isValid() {
|
||||||
|
return valid && distance >= 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mock implementation of GyroSensor for testing.
|
||||||
|
*
|
||||||
|
* This mock can simulate:
|
||||||
|
* - Precise heading control for testing turns
|
||||||
|
* - Gyro drift over time (realistic behavior)
|
||||||
|
* - Calibration states
|
||||||
|
* - Rotation simulation
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* MockGyroSensor gyro = new MockGyroSensor();
|
||||||
|
* gyro.setHeading(90); // Robot facing 90 degrees
|
||||||
|
* gyro.rotate(45); // Robot turns 45 more degrees
|
||||||
|
*/
|
||||||
|
public class MockGyroSensor implements GyroSensor {
|
||||||
|
private double heading = 0.0;
|
||||||
|
private boolean calibrated = true;
|
||||||
|
private double driftPerSecond = 0.0; // Degrees of drift per second
|
||||||
|
private long lastUpdateTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the gyro heading directly.
|
||||||
|
* Useful for setting up test scenarios.
|
||||||
|
*
|
||||||
|
* @param degrees heading in degrees (will be normalized to 0-359)
|
||||||
|
*/
|
||||||
|
public void setHeading(double degrees) {
|
||||||
|
this.heading = normalizeHeading(degrees);
|
||||||
|
this.lastUpdateTime = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate the robot rotating.
|
||||||
|
* Positive = clockwise, negative = counter-clockwise.
|
||||||
|
*
|
||||||
|
* @param degrees how many degrees to rotate
|
||||||
|
*/
|
||||||
|
public void rotate(double degrees) {
|
||||||
|
this.heading = normalizeHeading(this.heading + degrees);
|
||||||
|
this.lastUpdateTime = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate gyro drift (realistic behavior).
|
||||||
|
* Real gyros drift slightly over time.
|
||||||
|
*
|
||||||
|
* @param degreesPerSecond how much the gyro drifts per second
|
||||||
|
*/
|
||||||
|
public void setDrift(double degreesPerSecond) {
|
||||||
|
this.driftPerSecond = degreesPerSecond;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulate uncalibrated state.
|
||||||
|
*/
|
||||||
|
public void setUncalibrated() {
|
||||||
|
this.calibrated = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getHeading() {
|
||||||
|
if (!calibrated) {
|
||||||
|
return 0.0; // Return zero if not calibrated
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply drift based on time elapsed
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
double elapsedSeconds = (now - lastUpdateTime) / 1000.0;
|
||||||
|
double drift = driftPerSecond * elapsedSeconds;
|
||||||
|
|
||||||
|
lastUpdateTime = now;
|
||||||
|
heading = normalizeHeading(heading + drift);
|
||||||
|
|
||||||
|
return heading;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
this.heading = 0.0;
|
||||||
|
this.lastUpdateTime = System.currentTimeMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isCalibrated() {
|
||||||
|
return calibrated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize heading to 0-359 range.
|
||||||
|
*/
|
||||||
|
private double normalizeHeading(double degrees) {
|
||||||
|
while (degrees < 0) degrees += 360;
|
||||||
|
while (degrees >= 360) degrees -= 360;
|
||||||
|
return degrees;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package robot.hardware;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mock implementation of MotorController for testing.
|
||||||
|
* Tracks power settings without requiring actual hardware.
|
||||||
|
*/
|
||||||
|
public class MockMotorController implements MotorController {
|
||||||
|
private double power = 0.0;
|
||||||
|
private int powerSetCount = 0;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setPower(double power) {
|
||||||
|
this.power = power;
|
||||||
|
this.powerSetCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getPower() {
|
||||||
|
return power;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get how many times setPower was called (useful for testing).
|
||||||
|
*/
|
||||||
|
public int getPowerSetCount() {
|
||||||
|
return powerSetCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset the mock to initial state.
|
||||||
|
*/
|
||||||
|
public void reset() {
|
||||||
|
power = 0.0;
|
||||||
|
powerSetCount = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import robot.hardware.*;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* INTEGRATION TEST: Complete autonomous sequence.
|
||||||
|
*
|
||||||
|
* This test demonstrates SYSTEM-LEVEL testing without a robot!
|
||||||
|
*
|
||||||
|
* Scenario:
|
||||||
|
* 1. Start 100cm from wall
|
||||||
|
* 2. Drive straight toward wall
|
||||||
|
* 3. Stop at 10cm from wall
|
||||||
|
* 4. Turn 90° right
|
||||||
|
* 5. Drive forward again
|
||||||
|
* 6. Turn back to original heading
|
||||||
|
*
|
||||||
|
* This tests:
|
||||||
|
* - Multiple subsystems working together
|
||||||
|
* - State transitions
|
||||||
|
* - Sensor coordination
|
||||||
|
* - Complete mission simulation
|
||||||
|
*
|
||||||
|
* ALL WITHOUT A PHYSICAL ROBOT!
|
||||||
|
*/
|
||||||
|
@DisplayName("Autonomous Sequence Integration Test")
|
||||||
|
class AutonomousIntegrationTest {
|
||||||
|
|
||||||
|
// Mock hardware
|
||||||
|
private MockDistanceSensor distanceSensor;
|
||||||
|
private MockGyroSensor gyro;
|
||||||
|
private MockMotorController leftMotor;
|
||||||
|
private MockMotorController rightMotor;
|
||||||
|
|
||||||
|
// Subsystems
|
||||||
|
private WallApproach wallApproach;
|
||||||
|
private TurnController turnController;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
// Create mock hardware (no FTC SDK needed!)
|
||||||
|
distanceSensor = new MockDistanceSensor();
|
||||||
|
gyro = new MockGyroSensor();
|
||||||
|
leftMotor = new MockMotorController();
|
||||||
|
rightMotor = new MockMotorController();
|
||||||
|
|
||||||
|
// Create subsystems
|
||||||
|
wallApproach = new WallApproach(distanceSensor, leftMotor, rightMotor);
|
||||||
|
turnController = new TurnController(gyro, leftMotor, rightMotor);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Full autonomous mission simulation")
|
||||||
|
void testCompleteAutonomousMission() {
|
||||||
|
System.out.println("=== Starting Autonomous Mission ===");
|
||||||
|
|
||||||
|
// ========== PHASE 1: Approach Wall ==========
|
||||||
|
System.out.println("\n--- Phase 1: Approaching Wall ---");
|
||||||
|
|
||||||
|
distanceSensor.setDistance(100.0); // Start 100cm away
|
||||||
|
gyro.setHeading(0); // Facing forward
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
int phaseUpdates = 0;
|
||||||
|
while (wallApproach.getState() != WallApproach.WallApproachState.STOPPED && phaseUpdates < 200) {
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Simulate robot actually moving
|
||||||
|
// Movement speed proportional to motor power
|
||||||
|
double moveSpeed = leftMotor.getPower() * 2.0; // 2cm per update at full power
|
||||||
|
distanceSensor.approach(moveSpeed);
|
||||||
|
|
||||||
|
phaseUpdates++;
|
||||||
|
|
||||||
|
// Log state changes
|
||||||
|
if (phaseUpdates % 20 == 0) {
|
||||||
|
System.out.printf(" Update %d: State=%s, Distance=%.1fcm, Power=%.2f\n",
|
||||||
|
phaseUpdates,
|
||||||
|
wallApproach.getState(),
|
||||||
|
distanceSensor.getDistanceCm(),
|
||||||
|
leftMotor.getPower());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify Phase 1 completed successfully
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState(),
|
||||||
|
"Phase 1: Should successfully stop at wall");
|
||||||
|
assertTrue(distanceSensor.getDistanceCm() <= 12.0,
|
||||||
|
"Phase 1: Should be close to target distance");
|
||||||
|
System.out.printf("Phase 1 Complete: Stopped at %.1fcm in %d updates\n",
|
||||||
|
distanceSensor.getDistanceCm(), phaseUpdates);
|
||||||
|
|
||||||
|
// ========== PHASE 2: Turn 90° Right ==========
|
||||||
|
System.out.println("\n--- Phase 2: Turning 90° Right ---");
|
||||||
|
|
||||||
|
turnController.turnTo(90);
|
||||||
|
|
||||||
|
phaseUpdates = 0;
|
||||||
|
while (turnController.getState() == TurnController.TurnState.TURNING && phaseUpdates < 200) {
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Simulate robot actually turning
|
||||||
|
double turnSpeed = leftMotor.getPower() * 2.0; // 2° per update at full power
|
||||||
|
gyro.rotate(turnSpeed);
|
||||||
|
|
||||||
|
phaseUpdates++;
|
||||||
|
|
||||||
|
if (phaseUpdates % 10 == 0) {
|
||||||
|
System.out.printf(" Update %d: Heading=%.1f°, Error=%.1f°, Power=%.2f\n",
|
||||||
|
phaseUpdates,
|
||||||
|
gyro.getHeading(),
|
||||||
|
turnController.getHeadingError(),
|
||||||
|
leftMotor.getPower());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify Phase 2 completed successfully
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState(),
|
||||||
|
"Phase 2: Turn should complete");
|
||||||
|
assertTrue(Math.abs(gyro.getHeading() - 90) <= 2.0,
|
||||||
|
"Phase 2: Should be facing 90°");
|
||||||
|
System.out.printf("Phase 2 Complete: Turned to %.1f° in %d updates\n",
|
||||||
|
gyro.getHeading(), phaseUpdates);
|
||||||
|
|
||||||
|
// ========== PHASE 3: Drive Forward (new direction) ==========
|
||||||
|
System.out.println("\n--- Phase 3: Driving Forward (after turn) ---");
|
||||||
|
|
||||||
|
// Reset distance sensor for new direction
|
||||||
|
distanceSensor.setDistance(80.0);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
phaseUpdates = 0;
|
||||||
|
while (wallApproach.getState() != WallApproach.WallApproachState.STOPPED && phaseUpdates < 200) {
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
double moveSpeed = leftMotor.getPower() * 2.0;
|
||||||
|
distanceSensor.approach(moveSpeed);
|
||||||
|
|
||||||
|
phaseUpdates++;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState(),
|
||||||
|
"Phase 3: Should stop at wall in new direction");
|
||||||
|
System.out.printf("Phase 3 Complete: Stopped at %.1fcm\n",
|
||||||
|
distanceSensor.getDistanceCm());
|
||||||
|
|
||||||
|
// ========== PHASE 4: Turn back to original heading ==========
|
||||||
|
System.out.println("\n--- Phase 4: Returning to Original Heading ---");
|
||||||
|
|
||||||
|
turnController.turnTo(0); // Turn back to 0°
|
||||||
|
|
||||||
|
phaseUpdates = 0;
|
||||||
|
while (turnController.getState() == TurnController.TurnState.TURNING && phaseUpdates < 200) {
|
||||||
|
turnController.update();
|
||||||
|
double turnSpeed = leftMotor.getPower() * 2.0;
|
||||||
|
gyro.rotate(turnSpeed);
|
||||||
|
phaseUpdates++;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState(),
|
||||||
|
"Phase 4: Should complete return turn");
|
||||||
|
assertTrue(Math.abs(gyro.getHeading()) <= 2.0,
|
||||||
|
"Phase 4: Should be back to original heading");
|
||||||
|
System.out.printf("Phase 4 Complete: Returned to %.1f°\n", gyro.getHeading());
|
||||||
|
|
||||||
|
System.out.println("\n=== Mission Complete! ===");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Mission handles sensor failure gracefully")
|
||||||
|
void testMissionWithSensorFailure() {
|
||||||
|
System.out.println("=== Testing Mission with Sensor Failure ===");
|
||||||
|
|
||||||
|
// Start approaching wall
|
||||||
|
distanceSensor.setDistance(50.0);
|
||||||
|
gyro.setHeading(0);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
// Run for a bit
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
wallApproach.update();
|
||||||
|
distanceSensor.approach(leftMotor.getPower() * 2.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// SENSOR FAILS!
|
||||||
|
System.out.println("--- Simulating sensor failure ---");
|
||||||
|
distanceSensor.simulateFailure();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// System should detect failure and stop
|
||||||
|
assertEquals(WallApproach.WallApproachState.ERROR, wallApproach.getState(),
|
||||||
|
"Should enter error state on sensor failure");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Should stop motors on sensor failure");
|
||||||
|
assertTrue(wallApproach.hasSensorError(),
|
||||||
|
"Should report sensor error");
|
||||||
|
|
||||||
|
System.out.println("Mission safely aborted due to sensor failure");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Mission handles unexpected obstacles")
|
||||||
|
void testMissionWithObstacle() {
|
||||||
|
System.out.println("=== Testing Mission with Unexpected Obstacle ===");
|
||||||
|
|
||||||
|
// Start normal approach
|
||||||
|
distanceSensor.setDistance(100.0);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
// Robot driving toward wall
|
||||||
|
for (int i = 0; i < 20; i++) {
|
||||||
|
wallApproach.update();
|
||||||
|
distanceSensor.approach(leftMotor.getPower() * 2.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// UNEXPECTED OBSTACLE APPEARS!
|
||||||
|
System.out.println("--- Obstacle detected! ---");
|
||||||
|
distanceSensor.setDistance(8.0); // Suddenly very close!
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should immediately stop
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState(),
|
||||||
|
"Should immediately stop when obstacle detected");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Motors should stop");
|
||||||
|
|
||||||
|
System.out.println("Emergency stop successful");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Multi-waypoint navigation")
|
||||||
|
void testMultiWaypointNavigation() {
|
||||||
|
System.out.println("=== Testing Multi-Waypoint Navigation ===");
|
||||||
|
|
||||||
|
// Simulate driving to multiple waypoints:
|
||||||
|
// 1. Drive forward, turn 90° right
|
||||||
|
// 2. Drive forward, turn 90° right
|
||||||
|
// 3. Drive forward, turn 90° right
|
||||||
|
// 4. Drive forward, turn 90° right
|
||||||
|
// = Square pattern!
|
||||||
|
|
||||||
|
gyro.setHeading(0);
|
||||||
|
|
||||||
|
for (int waypoint = 1; waypoint <= 4; waypoint++) {
|
||||||
|
System.out.printf("\n--- Waypoint %d ---\n", waypoint);
|
||||||
|
|
||||||
|
// Drive forward
|
||||||
|
distanceSensor.setDistance(50.0);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
while (wallApproach.getState() != WallApproach.WallApproachState.STOPPED) {
|
||||||
|
wallApproach.update();
|
||||||
|
distanceSensor.approach(leftMotor.getPower() * 2.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.printf("Reached waypoint %d\n", waypoint);
|
||||||
|
|
||||||
|
// Turn 90° right
|
||||||
|
double targetHeading = (waypoint * 90) % 360;
|
||||||
|
turnController.turnTo(targetHeading);
|
||||||
|
|
||||||
|
while (turnController.getState() == TurnController.TurnState.TURNING) {
|
||||||
|
turnController.update();
|
||||||
|
gyro.rotate(leftMotor.getPower() * 2.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.printf("Turned to %.0f°\n", gyro.getHeading());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should complete the square and face original direction
|
||||||
|
assertTrue(Math.abs(gyro.getHeading()) <= 2.0 ||
|
||||||
|
Math.abs(gyro.getHeading() - 360) <= 2.0,
|
||||||
|
"Should complete square and face original direction");
|
||||||
|
|
||||||
|
System.out.println("\nSquare pattern complete!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Concurrent sensor updates")
|
||||||
|
void testConcurrentSensorUpdates() {
|
||||||
|
// Test that system handles sensors updating at different rates
|
||||||
|
|
||||||
|
distanceSensor.setDistance(50.0);
|
||||||
|
gyro.setHeading(0);
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
// Simulate 100 updates where sensors might not always have new data
|
||||||
|
for (int i = 0; i < 100; i++) {
|
||||||
|
// Distance sensor updates every cycle
|
||||||
|
wallApproach.update();
|
||||||
|
distanceSensor.approach(leftMotor.getPower() * 1.0);
|
||||||
|
|
||||||
|
// Gyro might update less frequently (every 3 cycles)
|
||||||
|
if (i % 3 == 0) {
|
||||||
|
gyro.rotate(0.1); // Slight drift
|
||||||
|
}
|
||||||
|
|
||||||
|
// System should remain stable
|
||||||
|
assertNotEquals(WallApproach.WallApproachState.ERROR, wallApproach.getState(),
|
||||||
|
"System should remain stable with varying sensor update rates");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import robot.hardware.MockMotorController;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for MotorCycler subsystem.
|
||||||
|
* These tests run on the PC without requiring FTC SDK or Android.
|
||||||
|
*/
|
||||||
|
class MotorCyclerTest {
|
||||||
|
private MockMotorController motor;
|
||||||
|
private MotorCycler cycler;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
motor = new MockMotorController();
|
||||||
|
// Create cycler: 100ms on, 50ms off, 0.75 power
|
||||||
|
cycler = new MotorCycler(motor, 100, 50, 0.75);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testInitialization() {
|
||||||
|
cycler.init();
|
||||||
|
assertEquals(0.0, motor.getPower(), 0.001,
|
||||||
|
"Motor should be off after init");
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.OFF, cycler.getState(),
|
||||||
|
"Should start in OFF state");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFirstCycle_TurnsOnAfterOffPeriod() {
|
||||||
|
cycler.init();
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// Should stay off during the off period
|
||||||
|
cycler.update(startTime + 25);
|
||||||
|
assertEquals(0.0, motor.getPower(), 0.001);
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.OFF, cycler.getState());
|
||||||
|
|
||||||
|
// Should turn on after off period completes
|
||||||
|
cycler.update(startTime + 50);
|
||||||
|
assertEquals(0.75, motor.getPower(), 0.001,
|
||||||
|
"Motor should turn on after off period");
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.ON, cycler.getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCycleFromOnToOff() {
|
||||||
|
cycler.init();
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// Skip to motor being on
|
||||||
|
cycler.update(startTime + 50);
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.ON, cycler.getState());
|
||||||
|
|
||||||
|
// Should stay on during on period
|
||||||
|
cycler.update(startTime + 100);
|
||||||
|
assertEquals(0.75, motor.getPower(), 0.001);
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.ON, cycler.getState());
|
||||||
|
|
||||||
|
// Should turn off after on period completes
|
||||||
|
cycler.update(startTime + 150);
|
||||||
|
assertEquals(0.0, motor.getPower(), 0.001,
|
||||||
|
"Motor should turn off after on period");
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.OFF, cycler.getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testFullCycle() {
|
||||||
|
cycler.init();
|
||||||
|
long time = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// Start OFF
|
||||||
|
cycler.update(time);
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.OFF, cycler.getState());
|
||||||
|
assertEquals(0.0, motor.getPower(), 0.001);
|
||||||
|
|
||||||
|
// After 50ms: turn ON
|
||||||
|
time += 50;
|
||||||
|
cycler.update(time);
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.ON, cycler.getState());
|
||||||
|
assertEquals(0.75, motor.getPower(), 0.001);
|
||||||
|
|
||||||
|
// After another 100ms: turn OFF
|
||||||
|
time += 100;
|
||||||
|
cycler.update(time);
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.OFF, cycler.getState());
|
||||||
|
assertEquals(0.0, motor.getPower(), 0.001);
|
||||||
|
|
||||||
|
// After another 50ms: turn ON again
|
||||||
|
time += 50;
|
||||||
|
cycler.update(time);
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.ON, cycler.getState());
|
||||||
|
assertEquals(0.75, motor.getPower(), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testTimeInState() {
|
||||||
|
cycler.init();
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// Check time in initial OFF state
|
||||||
|
assertEquals(0, cycler.getTimeInState(startTime));
|
||||||
|
assertEquals(25, cycler.getTimeInState(startTime + 25));
|
||||||
|
|
||||||
|
// Transition to ON
|
||||||
|
cycler.update(startTime + 50);
|
||||||
|
assertEquals(0, cycler.getTimeInState(startTime + 50));
|
||||||
|
assertEquals(30, cycler.getTimeInState(startTime + 80));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testStop() {
|
||||||
|
cycler.init();
|
||||||
|
long time = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// Get motor running
|
||||||
|
cycler.update(time + 50);
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.ON, cycler.getState());
|
||||||
|
assertEquals(0.75, motor.getPower(), 0.001);
|
||||||
|
|
||||||
|
// Stop should turn off motor and reset to OFF state
|
||||||
|
cycler.stop();
|
||||||
|
assertEquals(MotorCycler.MotorCycleState.OFF, cycler.getState());
|
||||||
|
assertEquals(0.0, motor.getPower(), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testDefaultPower() {
|
||||||
|
// Create cycler with default power
|
||||||
|
MotorCycler defaultCycler = new MotorCycler(motor, 100, 50);
|
||||||
|
defaultCycler.init();
|
||||||
|
long time = System.currentTimeMillis();
|
||||||
|
|
||||||
|
// Skip to ON state
|
||||||
|
defaultCycler.update(time + 50);
|
||||||
|
|
||||||
|
// Should use default power of 0.5
|
||||||
|
assertEquals(0.5, motor.getPower(), 0.001,
|
||||||
|
"Default power should be 0.5");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testMotorControllerIsRunning() {
|
||||||
|
motor.setPower(0.0);
|
||||||
|
assertFalse(motor.isRunning(), "Motor with 0 power should not be running");
|
||||||
|
|
||||||
|
motor.setPower(0.5);
|
||||||
|
assertTrue(motor.isRunning(), "Motor with positive power should be running");
|
||||||
|
|
||||||
|
motor.setPower(-0.3);
|
||||||
|
assertTrue(motor.isRunning(), "Motor with negative power should be running");
|
||||||
|
|
||||||
|
motor.setPower(0.0001);
|
||||||
|
assertFalse(motor.isRunning(), "Motor with tiny power should not be running");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,383 @@
|
|||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import robot.hardware.MockGyroSensor;
|
||||||
|
import robot.hardware.MockMotorController;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Comprehensive tests for TurnController subsystem.
|
||||||
|
*
|
||||||
|
* Tests cover:
|
||||||
|
* - Basic turn mechanics
|
||||||
|
* - Shortest path selection (clockwise vs counter-clockwise)
|
||||||
|
* - Proportional control behavior
|
||||||
|
* - Gyro drift handling
|
||||||
|
* - 360-degree wraparound cases
|
||||||
|
*/
|
||||||
|
@DisplayName("Turn Controller Subsystem Tests")
|
||||||
|
class TurnControllerTest {
|
||||||
|
|
||||||
|
private MockGyroSensor gyro;
|
||||||
|
private MockMotorController leftMotor;
|
||||||
|
private MockMotorController rightMotor;
|
||||||
|
private TurnController turnController;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
gyro = new MockGyroSensor();
|
||||||
|
leftMotor = new MockMotorController();
|
||||||
|
rightMotor = new MockMotorController();
|
||||||
|
turnController = new TurnController(gyro, leftMotor, rightMotor);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== UNIT TESTS: Basic Functionality ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Unit: Initial state is IDLE")
|
||||||
|
void testInitialState() {
|
||||||
|
assertEquals(TurnController.TurnState.IDLE, turnController.getState(),
|
||||||
|
"Turn controller should start in IDLE state");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Unit: turnTo() starts turning")
|
||||||
|
void testTurnToStartsTurning() {
|
||||||
|
turnController.turnTo(90);
|
||||||
|
|
||||||
|
assertEquals(TurnController.TurnState.TURNING, turnController.getState(),
|
||||||
|
"Should enter TURNING state after turnTo()");
|
||||||
|
assertEquals(90, turnController.getTargetHeading(), 0.001,
|
||||||
|
"Target heading should be set");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Unit: Completes when within tolerance")
|
||||||
|
void testCompletesWithinTolerance() {
|
||||||
|
gyro.setHeading(88.5); // Very close to 90
|
||||||
|
|
||||||
|
turnController.turnTo(90);
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Should complete (within 2 degree tolerance)
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState(),
|
||||||
|
"Should complete when within 2 degrees of target");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Motors should stop when turn complete");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== SHORTEST PATH TESTS ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Path: Simple clockwise turn (0° → 90°)")
|
||||||
|
void testSimpleClockwiseTurn() {
|
||||||
|
gyro.setHeading(0);
|
||||||
|
turnController.turnTo(90);
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Should turn right (positive power on left motor)
|
||||||
|
assertTrue(leftMotor.getPower() > 0,
|
||||||
|
"Left motor should be positive for clockwise turn");
|
||||||
|
assertTrue(rightMotor.getPower() < 0,
|
||||||
|
"Right motor should be negative for clockwise turn");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Path: Simple counter-clockwise turn (90° → 0°)")
|
||||||
|
void testSimpleCounterClockwiseTurn() {
|
||||||
|
gyro.setHeading(90);
|
||||||
|
turnController.turnTo(0);
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Should turn left (negative power on left motor)
|
||||||
|
assertTrue(leftMotor.getPower() < 0,
|
||||||
|
"Left motor should be negative for counter-clockwise turn");
|
||||||
|
assertTrue(rightMotor.getPower() > 0,
|
||||||
|
"Right motor should be positive for counter-clockwise turn");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Path: Wraparound clockwise (350° → 10°)")
|
||||||
|
void testWraparoundClockwise() {
|
||||||
|
// Currently at 350°, want to turn to 10°
|
||||||
|
// Shortest path is clockwise through 0° (20° turn)
|
||||||
|
gyro.setHeading(350);
|
||||||
|
turnController.turnTo(10);
|
||||||
|
|
||||||
|
double error = turnController.getHeadingError();
|
||||||
|
|
||||||
|
// Error should be positive (clockwise)
|
||||||
|
assertTrue(error > 0,
|
||||||
|
"Should choose clockwise path (positive error)");
|
||||||
|
assertEquals(20, error, 0.001,
|
||||||
|
"Shortest path from 350° to 10° is 20° clockwise");
|
||||||
|
|
||||||
|
turnController.update();
|
||||||
|
assertTrue(leftMotor.getPower() > 0,
|
||||||
|
"Should turn clockwise");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Path: Wraparound counter-clockwise (10° → 350°)")
|
||||||
|
void testWraparoundCounterClockwise() {
|
||||||
|
// Currently at 10°, want to turn to 350°
|
||||||
|
// Shortest path is counter-clockwise through 0° (20° turn)
|
||||||
|
gyro.setHeading(10);
|
||||||
|
turnController.turnTo(350);
|
||||||
|
|
||||||
|
double error = turnController.getHeadingError();
|
||||||
|
|
||||||
|
// Error should be negative (counter-clockwise)
|
||||||
|
assertTrue(error < 0,
|
||||||
|
"Should choose counter-clockwise path (negative error)");
|
||||||
|
assertEquals(-20, error, 0.001,
|
||||||
|
"Shortest path from 10° to 350° is 20° counter-clockwise");
|
||||||
|
|
||||||
|
turnController.update();
|
||||||
|
assertTrue(leftMotor.getPower() < 0,
|
||||||
|
"Should turn counter-clockwise");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Path: Exactly opposite heading (180° ambiguous)")
|
||||||
|
void testOppositeHeading() {
|
||||||
|
gyro.setHeading(0);
|
||||||
|
turnController.turnTo(180);
|
||||||
|
|
||||||
|
double error = turnController.getHeadingError();
|
||||||
|
|
||||||
|
// Either direction is valid, should pick one consistently
|
||||||
|
assertEquals(180, Math.abs(error), 0.001,
|
||||||
|
"180° turn should be exactly 180° either direction");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== PROPORTIONAL CONTROL TESTS ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Control: Turn power proportional to error")
|
||||||
|
void testProportionalControl() {
|
||||||
|
// Large error should produce large turn power
|
||||||
|
gyro.setHeading(0);
|
||||||
|
turnController.turnTo(90);
|
||||||
|
turnController.update();
|
||||||
|
double largePower = Math.abs(leftMotor.getPower());
|
||||||
|
|
||||||
|
// Small error should produce small turn power
|
||||||
|
leftMotor.setPower(0); // Reset
|
||||||
|
gyro.setHeading(85);
|
||||||
|
turnController.update();
|
||||||
|
double smallPower = Math.abs(leftMotor.getPower());
|
||||||
|
|
||||||
|
assertTrue(largePower > smallPower,
|
||||||
|
"Larger heading error should produce larger turn power");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Control: Minimum power enforced")
|
||||||
|
void testMinimumPower() {
|
||||||
|
// Very small error (but not within tolerance)
|
||||||
|
gyro.setHeading(88); // 2° away, at tolerance threshold
|
||||||
|
turnController.turnTo(90);
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// If not complete, should use minimum power (0.15)
|
||||||
|
if (turnController.getState() == TurnController.TurnState.TURNING) {
|
||||||
|
assertTrue(Math.abs(leftMotor.getPower()) >= 0.15,
|
||||||
|
"Should enforce minimum turn power to overcome friction");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Control: Maximum power capped")
|
||||||
|
void testMaximumPower() {
|
||||||
|
// Very large error
|
||||||
|
gyro.setHeading(0);
|
||||||
|
turnController.turnTo(179); // Almost opposite
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Power should be capped at 0.5
|
||||||
|
assertTrue(Math.abs(leftMotor.getPower()) <= 0.5,
|
||||||
|
"Turn power should be capped at maximum");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== SYSTEM TESTS: Complete Turns ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("System: Complete 90° turn")
|
||||||
|
void testComplete90DegreeTurn() {
|
||||||
|
gyro.setHeading(0);
|
||||||
|
turnController.turnTo(90);
|
||||||
|
|
||||||
|
// Simulate turning (gyro updates as robot turns)
|
||||||
|
int maxIterations = 200; // Increased from 100
|
||||||
|
int iteration = 0;
|
||||||
|
|
||||||
|
while (turnController.getState() == TurnController.TurnState.TURNING && iteration < maxIterations) {
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Simulate robot actually turning
|
||||||
|
// Turn speed proportional to motor power
|
||||||
|
double turnSpeed = leftMotor.getPower() * 3.0; // Increased from 2.0 for faster simulation
|
||||||
|
gyro.rotate(turnSpeed);
|
||||||
|
|
||||||
|
iteration++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should complete
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState(),
|
||||||
|
"Turn should complete");
|
||||||
|
assertTrue(Math.abs(gyro.getHeading() - 90) <= 2.0,
|
||||||
|
"Should be within 2° of target");
|
||||||
|
assertTrue(iteration < maxIterations,
|
||||||
|
"Should complete in reasonable time");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("System: Complete wraparound turn")
|
||||||
|
void testCompleteWraparoundTurn() {
|
||||||
|
gyro.setHeading(350);
|
||||||
|
turnController.turnTo(10);
|
||||||
|
|
||||||
|
int maxIterations = 100;
|
||||||
|
int iteration = 0;
|
||||||
|
|
||||||
|
while (turnController.getState() == TurnController.TurnState.TURNING && iteration < maxIterations) {
|
||||||
|
turnController.update();
|
||||||
|
double turnSpeed = leftMotor.getPower() * 2.0;
|
||||||
|
gyro.rotate(turnSpeed);
|
||||||
|
iteration++;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState());
|
||||||
|
|
||||||
|
// Should be at ~10°
|
||||||
|
double finalHeading = gyro.getHeading();
|
||||||
|
assertTrue(Math.abs(finalHeading - 10) <= 2.0,
|
||||||
|
"Should complete wraparound turn accurately");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== EDGE CASE TESTS ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Handles uncalibrated gyro")
|
||||||
|
void testUncalibratedGyro() {
|
||||||
|
gyro.setUncalibrated();
|
||||||
|
|
||||||
|
turnController.turnTo(90);
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Should stop and return to idle
|
||||||
|
assertEquals(TurnController.TurnState.IDLE, turnController.getState(),
|
||||||
|
"Should not turn with uncalibrated gyro");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Motors should stop with uncalibrated gyro");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Handles gyro drift during turn")
|
||||||
|
void testGyrodrift() {
|
||||||
|
gyro.setHeading(0);
|
||||||
|
gyro.setDrift(0.5); // 0.5° per second drift
|
||||||
|
|
||||||
|
turnController.turnTo(90);
|
||||||
|
|
||||||
|
// Simulate turn with drift
|
||||||
|
for (int i = 0; i < 50; i++) {
|
||||||
|
turnController.update();
|
||||||
|
double turnSpeed = leftMotor.getPower() * 2.0;
|
||||||
|
gyro.rotate(turnSpeed);
|
||||||
|
|
||||||
|
// Drift adds a bit each update
|
||||||
|
try {
|
||||||
|
Thread.sleep(10); // 10ms per update
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// Ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should still complete despite drift
|
||||||
|
// (Controller will compensate for drift)
|
||||||
|
assertTrue(turnController.getState() == TurnController.TurnState.COMPLETE ||
|
||||||
|
turnController.getState() == TurnController.TurnState.TURNING,
|
||||||
|
"Should handle drift gracefully");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Multiple turns in sequence")
|
||||||
|
void testSequentialTurns() {
|
||||||
|
gyro.setHeading(0);
|
||||||
|
|
||||||
|
// First turn: 0 → 90
|
||||||
|
turnController.turnTo(90);
|
||||||
|
simulateTurn();
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState());
|
||||||
|
|
||||||
|
// Second turn: 90 → 180
|
||||||
|
turnController.turnTo(180);
|
||||||
|
simulateTurn();
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState());
|
||||||
|
|
||||||
|
// Third turn: 180 → 0 (shortest is through 270)
|
||||||
|
turnController.turnTo(0);
|
||||||
|
simulateTurn();
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState());
|
||||||
|
|
||||||
|
assertTrue(Math.abs(gyro.getHeading()) <= 2.0,
|
||||||
|
"Should complete all turns accurately");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Manual stop during turn")
|
||||||
|
void testManualStopDuringTurn() {
|
||||||
|
gyro.setHeading(0);
|
||||||
|
turnController.turnTo(90);
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Motors should be running
|
||||||
|
assertTrue(Math.abs(leftMotor.getPower()) > 0);
|
||||||
|
|
||||||
|
// Manual stop
|
||||||
|
turnController.stop();
|
||||||
|
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Stop should immediately halt motors");
|
||||||
|
assertEquals(0.0, rightMotor.getPower(), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Turn to current heading (no-op)")
|
||||||
|
void testTurnToCurrentHeading() {
|
||||||
|
gyro.setHeading(45);
|
||||||
|
turnController.turnTo(45);
|
||||||
|
turnController.update();
|
||||||
|
|
||||||
|
// Should immediately complete
|
||||||
|
assertEquals(TurnController.TurnState.COMPLETE, turnController.getState(),
|
||||||
|
"Turning to current heading should immediately complete");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"No motor power needed");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== HELPER METHODS ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper to simulate a turn completing.
|
||||||
|
*/
|
||||||
|
private void simulateTurn() {
|
||||||
|
int maxIterations = 300; // Increased from 200
|
||||||
|
int iteration = 0;
|
||||||
|
|
||||||
|
while (turnController.getState() == TurnController.TurnState.TURNING && iteration < maxIterations) {
|
||||||
|
turnController.update();
|
||||||
|
double turnSpeed = leftMotor.getPower() * 3.0; // Match testComplete90DegreeTurn
|
||||||
|
gyro.rotate(turnSpeed);
|
||||||
|
iteration++;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertTrue(iteration < maxIterations,
|
||||||
|
"Turn should complete in reasonable time");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
package robot.subsystems;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import robot.hardware.MockDistanceSensor;
|
||||||
|
import robot.hardware.MockMotorController;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Comprehensive tests for WallApproach subsystem.
|
||||||
|
*
|
||||||
|
* These tests demonstrate:
|
||||||
|
* - Unit testing (individual behaviors)
|
||||||
|
* - System testing (complete scenarios)
|
||||||
|
* - Edge case testing (sensor failures, noise)
|
||||||
|
* - State machine testing
|
||||||
|
*
|
||||||
|
* All tests run on Windows JRE - no robot needed!
|
||||||
|
*/
|
||||||
|
@DisplayName("Wall Approach Subsystem Tests")
|
||||||
|
class WallApproachTest {
|
||||||
|
|
||||||
|
private MockDistanceSensor sensor;
|
||||||
|
private MockMotorController leftMotor;
|
||||||
|
private MockMotorController rightMotor;
|
||||||
|
private WallApproach wallApproach;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
// Create mock hardware (no FTC SDK needed!)
|
||||||
|
sensor = new MockDistanceSensor();
|
||||||
|
leftMotor = new MockMotorController();
|
||||||
|
rightMotor = new MockMotorController();
|
||||||
|
|
||||||
|
// Create the subsystem we're testing
|
||||||
|
wallApproach = new WallApproach(sensor, leftMotor, rightMotor);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== UNIT TESTS: Individual Behaviors ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Unit: Initial state should be INIT")
|
||||||
|
void testInitialState() {
|
||||||
|
assertEquals(WallApproach.WallApproachState.INIT, wallApproach.getState(),
|
||||||
|
"Wall approach should start in INIT state");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Unit: Starting approach transitions to APPROACHING state")
|
||||||
|
void testStartTransition() {
|
||||||
|
sensor.setDistance(100.0); // Far from wall
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
assertEquals(WallApproach.WallApproachState.APPROACHING, wallApproach.getState(),
|
||||||
|
"After start(), should be in APPROACHING state");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Unit: Drives at full speed when far from wall")
|
||||||
|
void testFullSpeedWhenFar() {
|
||||||
|
sensor.setDistance(100.0); // 100cm = far away
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should drive at full speed (0.6)
|
||||||
|
assertEquals(0.6, leftMotor.getPower(), 0.001,
|
||||||
|
"Left motor should be at full speed when far from wall");
|
||||||
|
assertEquals(0.6, rightMotor.getPower(), 0.001,
|
||||||
|
"Right motor should be at full speed when far from wall");
|
||||||
|
assertEquals(WallApproach.WallApproachState.APPROACHING, wallApproach.getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Unit: Slows down when approaching threshold")
|
||||||
|
void testSlowsDownNearWall() {
|
||||||
|
sensor.setDistance(25.0); // 25cm = within slow zone (< 30cm)
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should slow down to 0.2
|
||||||
|
assertEquals(0.2, leftMotor.getPower(), 0.001,
|
||||||
|
"Should slow to 0.2 when within 30cm of wall");
|
||||||
|
assertEquals(0.2, rightMotor.getPower(), 0.001);
|
||||||
|
assertEquals(WallApproach.WallApproachState.SLOWING, wallApproach.getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Unit: Stops at target distance")
|
||||||
|
void testStopsAtTarget() {
|
||||||
|
sensor.setDistance(10.0); // Exactly at stop distance
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should stop
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Should stop when reaching target distance");
|
||||||
|
assertEquals(0.0, rightMotor.getPower(), 0.001);
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== SYSTEM TESTS: Complete Scenarios ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("System: Complete approach from far to stopped")
|
||||||
|
void testCompleteApproachSequence() {
|
||||||
|
// Start far away
|
||||||
|
sensor.setDistance(100.0);
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
// Phase 1: Fast approach (100cm → 35cm)
|
||||||
|
for (int i = 0; i < 13; i++) { // 13 updates at 5cm each
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(0.6, leftMotor.getPower(), 0.001,
|
||||||
|
"Should maintain full speed while far");
|
||||||
|
sensor.approach(5.0); // Get 5cm closer each update
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now at ~35cm - one more update should trigger slowing
|
||||||
|
wallApproach.update();
|
||||||
|
sensor.approach(5.0); // Now at 30cm
|
||||||
|
|
||||||
|
// Phase 2: Slow approach (30cm → 10cm)
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(WallApproach.WallApproachState.SLOWING, wallApproach.getState(),
|
||||||
|
"Should be slowing when distance < 30cm");
|
||||||
|
assertEquals(0.2, leftMotor.getPower(), 0.001,
|
||||||
|
"Should be at slow speed");
|
||||||
|
|
||||||
|
for (int i = 0; i < 4; i++) { // 4 updates at 5cm each
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(0.2, leftMotor.getPower(), 0.001);
|
||||||
|
sensor.approach(5.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phase 3: Stop at target
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState(),
|
||||||
|
"Should stop at 10cm");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Motors should be stopped");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("System: Handles sensor noise gracefully")
|
||||||
|
void testHandlesSensorNoise() {
|
||||||
|
sensor.setDistance(50.0);
|
||||||
|
sensor.setNoise(2.0); // Add ±2cm noise
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
// Run 20 updates with noisy sensor
|
||||||
|
for (int i = 0; i < 20; i++) {
|
||||||
|
wallApproach.update();
|
||||||
|
sensor.approach(0.5); // Get slightly closer each time
|
||||||
|
|
||||||
|
// Should not crash or behave erratically
|
||||||
|
assertTrue(leftMotor.getPower() >= 0,
|
||||||
|
"Motor power should never be negative");
|
||||||
|
assertTrue(leftMotor.getPower() <= 1.0,
|
||||||
|
"Motor power should never exceed 1.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should still be in a valid state
|
||||||
|
assertNotEquals(WallApproach.WallApproachState.ERROR, wallApproach.getState(),
|
||||||
|
"Should not enter error state with valid noisy sensor");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("System: Emergency stop if too close initially")
|
||||||
|
void testEmergencyStopIfTooClose() {
|
||||||
|
// Robot is already too close!
|
||||||
|
sensor.setDistance(5.0);
|
||||||
|
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should immediately stop
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState(),
|
||||||
|
"Should immediately stop if already too close");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001);
|
||||||
|
assertEquals(0.0, rightMotor.getPower(), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== EDGE CASE TESTS ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Handles sensor failure")
|
||||||
|
void testSensorFailureHandling() {
|
||||||
|
sensor.setDistance(50.0);
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Motors should be running
|
||||||
|
assertTrue(leftMotor.getPower() > 0);
|
||||||
|
|
||||||
|
// Sensor fails!
|
||||||
|
sensor.simulateFailure();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should enter error state and stop
|
||||||
|
assertEquals(WallApproach.WallApproachState.ERROR, wallApproach.getState(),
|
||||||
|
"Should enter ERROR state on sensor failure");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Should stop motors on sensor failure");
|
||||||
|
assertTrue(wallApproach.hasSensorError(),
|
||||||
|
"Should report sensor error");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Recovers if pushed backward")
|
||||||
|
void testRecoveryFromBackwardMotion() {
|
||||||
|
// Start in slow zone
|
||||||
|
sensor.setDistance(25.0);
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
assertEquals(WallApproach.WallApproachState.SLOWING, wallApproach.getState());
|
||||||
|
assertEquals(0.2, leftMotor.getPower(), 0.001);
|
||||||
|
|
||||||
|
// Robot gets pushed backward (human intervention, etc.)
|
||||||
|
sensor.setDistance(35.0);
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should speed up again
|
||||||
|
assertEquals(WallApproach.WallApproachState.APPROACHING, wallApproach.getState(),
|
||||||
|
"Should transition back to APPROACHING if pushed back");
|
||||||
|
assertEquals(0.6, leftMotor.getPower(), 0.001,
|
||||||
|
"Should speed up when far again");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Stays stopped once reached")
|
||||||
|
void testStaysStoppedOnceReached() {
|
||||||
|
sensor.setDistance(10.0);
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Should be stopped
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState());
|
||||||
|
|
||||||
|
// Run multiple more updates - should stay stopped
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState(),
|
||||||
|
"Should remain stopped");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Motors should stay off");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Manual stop works in any state")
|
||||||
|
void testManualStop() {
|
||||||
|
sensor.setDistance(50.0);
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
|
||||||
|
// Motors running
|
||||||
|
assertTrue(leftMotor.getPower() > 0);
|
||||||
|
|
||||||
|
// Manual stop
|
||||||
|
wallApproach.stop();
|
||||||
|
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Stop should immediately halt motors");
|
||||||
|
assertEquals(0.0, rightMotor.getPower(), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Edge: Threshold boundary behavior")
|
||||||
|
void testThresholdBoundaries() {
|
||||||
|
// Test exact boundary values
|
||||||
|
|
||||||
|
// Just above slow threshold (30cm)
|
||||||
|
sensor.setDistance(30.1);
|
||||||
|
wallApproach.start();
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(0.6, leftMotor.getPower(), 0.001,
|
||||||
|
"At 30.1cm should still be full speed");
|
||||||
|
|
||||||
|
// Just below slow threshold
|
||||||
|
sensor.setDistance(29.9);
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(0.2, leftMotor.getPower(), 0.001,
|
||||||
|
"At 29.9cm should be slow speed");
|
||||||
|
|
||||||
|
// Just above stop threshold (10cm)
|
||||||
|
sensor.setDistance(10.1);
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(0.2, leftMotor.getPower(), 0.001,
|
||||||
|
"At 10.1cm should still be moving slowly");
|
||||||
|
|
||||||
|
// Just below stop threshold
|
||||||
|
sensor.setDistance(9.9);
|
||||||
|
wallApproach.update();
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"At 9.9cm should be stopped");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== INTEGRATION TEST ==========
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Integration: Full realistic approach with noise and variance")
|
||||||
|
void testRealisticApproachScenario() {
|
||||||
|
// Simulate a realistic approach with:
|
||||||
|
// - Sensor noise
|
||||||
|
// - Non-uniform distance changes
|
||||||
|
// - Multiple updates per cm traveled
|
||||||
|
|
||||||
|
sensor.setDistance(80.0);
|
||||||
|
sensor.setNoise(1.5); // Realistic noise level
|
||||||
|
wallApproach.start();
|
||||||
|
|
||||||
|
int updateCount = 0;
|
||||||
|
WallApproach.WallApproachState lastState = wallApproach.getState();
|
||||||
|
|
||||||
|
// Simulate approach with varying speeds
|
||||||
|
while (sensor.getDistanceCm() > 10.0 && updateCount < 300) { // Increased from 200
|
||||||
|
wallApproach.update();
|
||||||
|
updateCount++;
|
||||||
|
|
||||||
|
// Approach speed varies (not constant)
|
||||||
|
if (sensor.getDistanceCm() > 30) {
|
||||||
|
sensor.approach(1.5); // Reduced from 2.0 for more realistic simulation
|
||||||
|
} else {
|
||||||
|
sensor.approach(0.3); // Reduced from 0.5 for slower approach
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track state transitions
|
||||||
|
WallApproach.WallApproachState currentState = wallApproach.getState();
|
||||||
|
if (currentState != lastState) {
|
||||||
|
System.out.println("State transition: " + lastState + " → " + currentState +
|
||||||
|
" at " + String.format("%.1f", sensor.getDistanceCm()) + "cm");
|
||||||
|
lastState = currentState;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should have completed successfully
|
||||||
|
assertEquals(WallApproach.WallApproachState.STOPPED, wallApproach.getState(),
|
||||||
|
"Should successfully stop at target distance");
|
||||||
|
assertTrue(sensor.getDistanceCm() <= 11.0,
|
||||||
|
"Should stop very close to target (within noise tolerance)");
|
||||||
|
assertEquals(0.0, leftMotor.getPower(), 0.001,
|
||||||
|
"Motors should be stopped at end");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
// Intentionally hardcoded. When you bump the version in Cargo.toml,
|
// Intentionally hardcoded. When you bump the version in Cargo.toml,
|
||||||
// tests will fail here until you update this to match.
|
// tests will fail here until you update this to match.
|
||||||
pub const EXPECTED_VERSION: &str = "1.1.0-beta.1";
|
pub const EXPECTED_VERSION: &str = "1.1.0-rc1";
|
||||||
309
tests/template_tests.rs
Normal file
309
tests/template_tests.rs
Normal file
@@ -0,0 +1,309 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use std::fs;
|
||||||
|
use std::process::Command;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
// Import the template system
|
||||||
|
use weevil::templates::{TemplateManager, TemplateContext};
|
||||||
|
|
||||||
|
/// Helper to create a test template context
|
||||||
|
fn test_context(project_name: &str) -> TemplateContext {
|
||||||
|
TemplateContext {
|
||||||
|
project_name: project_name.to_string(),
|
||||||
|
package_name: project_name.to_lowercase().replace("-", "").replace("_", ""),
|
||||||
|
creation_date: "2026-02-02T12:00:00Z".to_string(),
|
||||||
|
weevil_version: "1.1.0-test".to_string(),
|
||||||
|
template_name: "basic".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_template_manager_creation() {
|
||||||
|
let mgr = TemplateManager::new();
|
||||||
|
assert!(mgr.is_ok(), "TemplateManager should be created successfully");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_template_exists() {
|
||||||
|
let mgr = TemplateManager::new().unwrap();
|
||||||
|
|
||||||
|
assert!(mgr.template_exists("basic"), "basic template should exist");
|
||||||
|
assert!(mgr.template_exists("testing"), "testing template should exist");
|
||||||
|
assert!(!mgr.template_exists("nonexistent"), "nonexistent template should not exist");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_list_templates() {
|
||||||
|
let mgr = TemplateManager::new().unwrap();
|
||||||
|
let templates = mgr.list_templates();
|
||||||
|
|
||||||
|
assert_eq!(templates.len(), 3, "Should have exactly 3 templates");
|
||||||
|
assert!(templates.iter().any(|t| t.contains("basic")), "Should list basic template");
|
||||||
|
assert!(templates.iter().any(|t| t.contains("testing")), "Should list testing template");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_basic_template_extraction() -> Result<()> {
|
||||||
|
let mgr = TemplateManager::new()?;
|
||||||
|
let temp_dir = TempDir::new()?;
|
||||||
|
let project_dir = temp_dir.path().join("test-robot");
|
||||||
|
fs::create_dir(&project_dir)?;
|
||||||
|
|
||||||
|
let context = test_context("test-robot");
|
||||||
|
let file_count = mgr.extract_template("basic", &project_dir, &context)?;
|
||||||
|
|
||||||
|
assert!(file_count > 0, "Should extract at least one file from basic template");
|
||||||
|
|
||||||
|
// Verify key files exist (basic template has minimal files)
|
||||||
|
assert!(project_dir.join(".gitignore").exists(), ".gitignore should exist");
|
||||||
|
assert!(project_dir.join("README.md").exists(), "README.md should exist (processed from .template)");
|
||||||
|
assert!(project_dir.join("settings.gradle").exists(), "settings.gradle should exist");
|
||||||
|
|
||||||
|
// Note: .weevil.toml and build.gradle are created by ProjectBuilder, not template
|
||||||
|
|
||||||
|
// Verify OpMode exists
|
||||||
|
let opmode_path = project_dir.join("src/main/java/robot/opmodes/BasicOpMode.java");
|
||||||
|
assert!(opmode_path.exists(), "BasicOpMode.java should exist");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_testing_template_extraction() -> Result<()> {
|
||||||
|
let mgr = TemplateManager::new()?;
|
||||||
|
let temp_dir = TempDir::new()?;
|
||||||
|
let project_dir = temp_dir.path().join("test-showcase");
|
||||||
|
fs::create_dir(&project_dir)?;
|
||||||
|
|
||||||
|
let mut context = test_context("test-showcase");
|
||||||
|
context.template_name = "testing".to_string();
|
||||||
|
|
||||||
|
let file_count = mgr.extract_template("testing", &project_dir, &context)?;
|
||||||
|
|
||||||
|
assert!(file_count > 20, "Testing template should have 20+ files, got {}", file_count);
|
||||||
|
|
||||||
|
// Verify documentation files
|
||||||
|
assert!(project_dir.join("README.md").exists(), "README.md should exist");
|
||||||
|
assert!(project_dir.join("DESIGN_AND_TEST_PLAN.md").exists(), "DESIGN_AND_TEST_PLAN.md should exist");
|
||||||
|
assert!(project_dir.join("TESTING_GUIDE.md").exists(), "TESTING_GUIDE.md should exist");
|
||||||
|
|
||||||
|
// Verify subsystems
|
||||||
|
assert!(project_dir.join("src/main/java/robot/subsystems/MotorCycler.java").exists(), "MotorCycler.java should exist");
|
||||||
|
assert!(project_dir.join("src/main/java/robot/subsystems/WallApproach.java").exists(), "WallApproach.java should exist");
|
||||||
|
assert!(project_dir.join("src/main/java/robot/subsystems/TurnController.java").exists(), "TurnController.java should exist");
|
||||||
|
|
||||||
|
// Verify hardware interfaces and implementations
|
||||||
|
assert!(project_dir.join("src/main/java/robot/hardware/MotorController.java").exists(), "MotorController interface should exist");
|
||||||
|
assert!(project_dir.join("src/main/java/robot/hardware/FtcMotorController.java").exists(), "FtcMotorController should exist");
|
||||||
|
assert!(project_dir.join("src/main/java/robot/hardware/DistanceSensor.java").exists(), "DistanceSensor interface should exist");
|
||||||
|
assert!(project_dir.join("src/main/java/robot/hardware/FtcDistanceSensor.java").exists(), "FtcDistanceSensor should exist");
|
||||||
|
|
||||||
|
// Verify test files
|
||||||
|
assert!(project_dir.join("src/test/java/robot/subsystems/MotorCyclerTest.java").exists(), "MotorCyclerTest.java should exist");
|
||||||
|
assert!(project_dir.join("src/test/java/robot/subsystems/WallApproachTest.java").exists(), "WallApproachTest.java should exist");
|
||||||
|
assert!(project_dir.join("src/test/java/robot/subsystems/TurnControllerTest.java").exists(), "TurnControllerTest.java should exist");
|
||||||
|
|
||||||
|
// Verify mock implementations
|
||||||
|
assert!(project_dir.join("src/test/java/robot/hardware/MockMotorController.java").exists(), "MockMotorController should exist");
|
||||||
|
assert!(project_dir.join("src/test/java/robot/hardware/MockDistanceSensor.java").exists(), "MockDistanceSensor should exist");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_template_variable_substitution() -> Result<()> {
|
||||||
|
let mgr = TemplateManager::new()?;
|
||||||
|
let temp_dir = TempDir::new()?;
|
||||||
|
let project_dir = temp_dir.path().join("my-test-robot");
|
||||||
|
fs::create_dir(&project_dir)?;
|
||||||
|
|
||||||
|
let context = test_context("my-test-robot");
|
||||||
|
mgr.extract_template("basic", &project_dir, &context)?;
|
||||||
|
|
||||||
|
// Check README.md for variable substitution
|
||||||
|
let readme_path = project_dir.join("README.md");
|
||||||
|
let readme_content = fs::read_to_string(readme_path)?;
|
||||||
|
|
||||||
|
assert!(readme_content.contains("my-test-robot"), "README should contain project name");
|
||||||
|
assert!(readme_content.contains("1.1.0-test"), "README should contain weevil version");
|
||||||
|
assert!(!readme_content.contains("{{PROJECT_NAME}}"), "README should not contain template variable");
|
||||||
|
assert!(!readme_content.contains("{{WEEVIL_VERSION}}"), "README should not contain template variable");
|
||||||
|
|
||||||
|
// Check BasicOpMode.java for variable substitution
|
||||||
|
let opmode_path = project_dir.join("src/main/java/robot/opmodes/BasicOpMode.java");
|
||||||
|
let opmode_content = fs::read_to_string(opmode_path)?;
|
||||||
|
|
||||||
|
assert!(opmode_content.contains("my-test-robot"), "BasicOpMode should contain project name");
|
||||||
|
assert!(!opmode_content.contains("{{PROJECT_NAME}}"), "BasicOpMode should not contain template variable");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_invalid_template_extraction() {
|
||||||
|
let mgr = TemplateManager::new().unwrap();
|
||||||
|
let temp_dir = TempDir::new().unwrap();
|
||||||
|
let project_dir = temp_dir.path().join("test-robot");
|
||||||
|
fs::create_dir(&project_dir).unwrap();
|
||||||
|
|
||||||
|
let context = test_context("test-robot");
|
||||||
|
let result = mgr.extract_template("nonexistent", &project_dir, &context);
|
||||||
|
|
||||||
|
assert!(result.is_err(), "Should fail for nonexistent template");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_package_name_sanitization() {
|
||||||
|
// Test that the helper creates correct package names
|
||||||
|
let context1 = test_context("my-robot");
|
||||||
|
assert_eq!(context1.package_name, "myrobot", "Hyphens should be removed");
|
||||||
|
|
||||||
|
let context2 = test_context("team_1234_bot");
|
||||||
|
assert_eq!(context2.package_name, "team1234bot", "Underscores should be removed");
|
||||||
|
|
||||||
|
let context3 = test_context("My-Cool_Bot");
|
||||||
|
assert_eq!(context3.package_name, "mycoolbot", "Mixed case and separators should be handled");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Integration test: Create a project with testing template and run gradle tests
|
||||||
|
/// This is marked with #[ignore] by default since it requires:
|
||||||
|
/// - Java installed
|
||||||
|
/// - Network access (first time to download gradle wrapper)
|
||||||
|
/// - Takes ~1-2 minutes to run
|
||||||
|
///
|
||||||
|
/// Run with: cargo test test_testing_template_gradle_build -- --ignored --nocapture
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn test_testing_template_gradle_build() -> Result<()> {
|
||||||
|
println!("Testing complete gradle build and test execution...");
|
||||||
|
|
||||||
|
let mgr = TemplateManager::new()?;
|
||||||
|
let temp_dir = TempDir::new()?;
|
||||||
|
let project_dir = temp_dir.path().join("gradle-test-robot");
|
||||||
|
fs::create_dir(&project_dir)?;
|
||||||
|
|
||||||
|
// Extract testing template
|
||||||
|
let mut context = test_context("gradle-test-robot");
|
||||||
|
context.template_name = "testing".to_string();
|
||||||
|
|
||||||
|
let file_count = mgr.extract_template("testing", &project_dir, &context)?;
|
||||||
|
println!("Extracted {} files from testing template", file_count);
|
||||||
|
|
||||||
|
// Check if gradlew exists (should be in testing template)
|
||||||
|
let gradlew = if cfg!(windows) {
|
||||||
|
project_dir.join("gradlew.bat")
|
||||||
|
} else {
|
||||||
|
project_dir.join("gradlew")
|
||||||
|
};
|
||||||
|
|
||||||
|
if !gradlew.exists() {
|
||||||
|
println!("WARNING: gradlew not found in template, skipping gradle test");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make gradlew executable on Unix
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let mut perms = fs::metadata(&gradlew)?.permissions();
|
||||||
|
perms.set_mode(0o755);
|
||||||
|
fs::set_permissions(&gradlew, perms)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("Running gradle test...");
|
||||||
|
|
||||||
|
// Run gradlew test
|
||||||
|
let output = Command::new(&gradlew)
|
||||||
|
.arg("test")
|
||||||
|
.current_dir(&project_dir)
|
||||||
|
.output()?;
|
||||||
|
|
||||||
|
println!("=== Gradle Output ===");
|
||||||
|
println!("{}", String::from_utf8_lossy(&output.stdout));
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
println!("=== Gradle Errors ===");
|
||||||
|
println!("{}", String::from_utf8_lossy(&output.stderr));
|
||||||
|
panic!("Gradle tests failed with status: {}", output.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify test output mentions 45 tests
|
||||||
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||||
|
|
||||||
|
// Look for test success indicators
|
||||||
|
let has_success = stdout.contains("BUILD SUCCESSFUL") ||
|
||||||
|
stdout.contains("45 tests") ||
|
||||||
|
stdout.to_lowercase().contains("tests passed");
|
||||||
|
|
||||||
|
assert!(has_success, "Gradle test output should indicate success");
|
||||||
|
|
||||||
|
println!("✓ All 45 tests passed!");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test that basic template creates a valid directory structure
|
||||||
|
#[test]
|
||||||
|
fn test_basic_template_directory_structure() -> Result<()> {
|
||||||
|
let mgr = TemplateManager::new()?;
|
||||||
|
let temp_dir = TempDir::new()?;
|
||||||
|
let project_dir = temp_dir.path().join("structure-test");
|
||||||
|
fs::create_dir(&project_dir)?;
|
||||||
|
|
||||||
|
let context = test_context("structure-test");
|
||||||
|
mgr.extract_template("basic", &project_dir, &context)?;
|
||||||
|
|
||||||
|
// Verify directory structure
|
||||||
|
assert!(project_dir.join("src").is_dir(), "src directory should exist");
|
||||||
|
assert!(project_dir.join("src/main").is_dir(), "src/main directory should exist");
|
||||||
|
assert!(project_dir.join("src/main/java").is_dir(), "src/main/java directory should exist");
|
||||||
|
assert!(project_dir.join("src/main/java/robot").is_dir(), "src/main/java/robot directory should exist");
|
||||||
|
assert!(project_dir.join("src/main/java/robot/opmodes").is_dir(), "opmodes directory should exist");
|
||||||
|
assert!(project_dir.join("src/test/java/robot").is_dir(), "test directory should exist");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test that .gitignore is not named ".gitignore.template"
|
||||||
|
#[test]
|
||||||
|
fn test_gitignore_naming() -> Result<()> {
|
||||||
|
let mgr = TemplateManager::new()?;
|
||||||
|
let temp_dir = TempDir::new()?;
|
||||||
|
let project_dir = temp_dir.path().join("gitignore-test");
|
||||||
|
fs::create_dir(&project_dir)?;
|
||||||
|
|
||||||
|
let context = test_context("gitignore-test");
|
||||||
|
mgr.extract_template("basic", &project_dir, &context)?;
|
||||||
|
|
||||||
|
assert!(project_dir.join(".gitignore").exists(), ".gitignore should exist");
|
||||||
|
assert!(!project_dir.join(".gitignore.template").exists(), ".gitignore.template should NOT exist");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test that template extraction doesn't fail with unusual project names
|
||||||
|
#[test]
|
||||||
|
fn test_unusual_project_names() -> Result<()> {
|
||||||
|
let mgr = TemplateManager::new()?;
|
||||||
|
|
||||||
|
let test_names = vec![
|
||||||
|
"robot-2024",
|
||||||
|
"team_1234",
|
||||||
|
"FTC_Bot",
|
||||||
|
"my-awesome-bot",
|
||||||
|
];
|
||||||
|
|
||||||
|
for name in test_names {
|
||||||
|
let temp_dir = TempDir::new()?;
|
||||||
|
let project_dir = temp_dir.path().join(name);
|
||||||
|
fs::create_dir(&project_dir)?;
|
||||||
|
|
||||||
|
let context = test_context(name);
|
||||||
|
let result = mgr.extract_template("basic", &project_dir, &context);
|
||||||
|
|
||||||
|
assert!(result.is_ok(), "Should handle project name: {}", name);
|
||||||
|
assert!(project_dir.join("README.md").exists(), "README should exist for {}", name);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user