# MyParking Parking Robot

[简体中文](README.md) | [English](README_en.md)

## Rewrite Roadmap and Current Status

This repository is a rewrite of the parking-robot control software. Development follows this order:

1. Implement the basic functions of one parking robot first;
2. Add parking-operation features after the single-robot loop is stable;
3. Improve tracking with bench and physical-vehicle data;
4. Consider multi-robot communication, formation, and coordination last.

The current work remains focused on the **single robot** and is in chassis integration, feature development, and tracking experiments. Multi-robot settings remain inside the `#if false` section of `MultiWheelC/PilotConfig.cs`, while `Shared/Fleet/FleetKinematics.cs` is still a placeholder. These files do not represent an implemented multi-robot system.

| Stage | Current status | Notes |
| --- | --- | --- |
| 1. Basic single-robot functions | Integration in progress | Motion control, MCU communication, wheel feedback, emergency-stop I/O, battery, lights, remote control, and diagnostics are connected in code; physical validation is ongoing |
| 2. Add parking functions | Partially started | Clamp control, limits, and alarms are connected; the clamp movement tests are currently commented out, while tire recognition, vehicle entry, and the complete parking workflow are not implemented |
| 3. Improve tracking | Started | Legacy `SendMotion` tests remain, with new Stanley lateral + PID longitudinal control, composite motion plans, experiment CSVs, and a new plotting tool |
| 4. Multi-robot scenarios | Deferred | Multi-robot R&D settings are excluded from the build, and the current version provides no fleet coordination |

## Overview

MyParking is a C# project for a multi-wheel parking-robot chassis. It covers upper-layer actions, shared kinematics, lower-layer hardware adaptation, and experiment-data analysis.

Main modules:

- `MultiWheelC`: Clumsy upper layer (C layer) for actions, tracking, manual tests, and experiment recording;
- `MedullaAdapter`: Medulla lower layer (M layer) for MCU, CAN, serial, wheel, clamp, remote-control, and alarm adaptation;
- `Shared`: M/C-shared 2D coordinates, chassis commands, frame transforms, and multi-wheel adaptation (no standalone `.csproj`; compiled into both ends);
- `CommonUsage-MultiVehicleSync/commonusage`: in-repository source for the `CommonUsage` chassis library;
- `data_process`: Python tools for tracking experiments and steering-response analysis.

No ROS/ROS 2, Docker, or Web simulator project is present. The plugins are loaded by Clumsy / Medulla hosts and cannot be started independently with `dotnet run`.

## Currently Integrated Capabilities

| Module | Current code capability |
| --- | --- |
| Single-robot motion | Straight, arc, and S-curve paths; forward, crab, and in-place rotation |
| Chassis commands | `SendMotion`, `SendXYThSpeed`, and a virtual-Ackermann test backend |
| Mode switching | Normal, crab, and spin modes; stop, pre-steer, and wait for wheel alignment before motion |
| Tracking | Legacy destination, line, and crab tracking; new Stanley lateral control, PID longitudinal control, front/rear GCP allocation, path-deviation protection, and terminal-state checks |
| State estimation | Detour pose and differentiated velocity; new experiments can retain the Detour pose while replacing its differentiated longitudinal velocity with a low-pass-filtered body velocity derived from steer-wheel feedback |
| Clamp | Left/right speed commands, position feedback, soft limits, driver alarms, physical/virtual remote control, and target-position actions |
| MCU communication | Bridge open/reset, version/state queries, digital I/O, synchronous serial/CAN access, and asynchronous callbacks |
| Drive and feedback | Commands and speed/position/steering feedback for eight drive motors and four steer modules, plus remote-frame state |
| Vehicle state | Emergency stop, start/stop, brake, lights, battery SOC/SOH, and drive-enable state |
| Diagnostics | CAN wheel-speed events, periodic snapshot CSVs, tracking CSVs, command recording, and Detour pose recording |

The presence of code and test entries does not mean every operating condition has passed physical acceptance testing.

## Software Architecture

```text
Clumsy host
    │
    ▼
MultiWheelC ───────────────┐
    │                      │
    ▼                      │ experiment CSV
Shared / CommonUsage       ├──────────► data_process
    │                      │
    ▼                      │
Medulla host               │
    │                      │
    ▼                      │
MedullaAdapter             │
    │ P/Invoke             │
    ▼                      │
mcu_serial_bridge.dll      │
    │                      │
    ▼                      │
MCU ─► CAN / Serial / IO ──┘
```

`MultiWheelC` and `MedullaAdapter` build as plugin libraries that require their respective hosts. `CommonUsage` is an independent chassis library and must not depend back on `Shared`, the M layer, or the C layer.

## Coordinates and Units

- `Shared` uses SI units: m, m/s, rad, rad/s.
- Body frame: X forward, Y left, counterclockwise positive.
- Legacy API units are converted only at boundaries.
- Angle normalization, shortest angular difference, and degree/radian conversion use `Shared/Mathematics/AngleMath.cs`.
- Radian normalization range is `[-π, π)`; degree normalization range is `[-180°, 180°)`.
- Vehicle heading may use the shortest circular difference; mechanical steering error under the `[-120°, 120°]` limit must use target minus actual directly.

## Repository Layout

```text
MyParking/
├── ParkingRobot.sln                 # Root solution (CommonUsage / M / C)
├── build-and-package.ps1            # Official build and M/C packaging script
├── AGENTS.md                        # Collaboration and coding rules
├── MultiWheelC/                     # C-layer actions, tracking, tests, and recording
├── MedullaAdapter/                  # M-layer MCU, CAN, wheel, clamp, remote, and alarms
├── Shared/                          # Shared models, math, and chassis adapter
├── CommonUsage-MultiVehicleSync/
│   └── commonusage/                 # CommonUsage chassis-library source
├── ref/                             # Generated CommonUsage.dll (do not overwrite by hand)
├── data_process/
│   ├── plot_new_controller_experiment.py # Six-panel plots for new-controller trials
│   ├── 新版控制器轨迹测试处理/      # Python dependencies for the new plotting tool
│   ├── 旧版控制器轨迹测试处理/      # Legacy trajectory, error, and response plots
│   └── 电机响应处理/                # Steering-response snapshot analysis
├── docs/
│   ├── SteeringConstraintDesign.md  # Steering-limit design notes
│   ├── chassis参考.json             # Sample chassis parameters
│   ├── 测试方案.txt                 # Single-robot tracking experiment plan
│   └── 记录.txt                     # Project debugging notes
└── output/                          # Packaging output (gitignored)
    ├── M/                           # MedullaAdapter.dll + CommonUsage.dll
    └── C/                           # MultiWheelC.dll + CommonUsage.dll
```

The root `ParkingRobot.sln` includes `CommonUsage`, `MedullaAdapter`, and `MultiWheelC` for opening the repo in Visual Studio. `Shared` has no standalone project and is compiled into the M/C projects. Packaging still uses `build-and-package.ps1`.

## Development Environment and Dependencies

- Windows development and physical-runtime environment;
- Visual Studio 2022, or a .NET SDK supporting .NET 8.0 and .NET Standard 2.0;
- A Python environment for optional experiment plotting;
- Internal Clumsy / Medulla framework assemblies under each project's `ref` directory;
- `mcu_serial_bridge.dll` for physical operation; this file is not currently in the repository;
- Compatible hosts capable of loading `MultiWheelC.dll` and `MedullaAdapter.dll`; the hosts are not included.

Primary dependencies:

- `MultiWheelC` (`netstandard2.0`): `Newtonsoft.Json 13.0.3` and `System.Numerics.Vectors 4.6.1`;
- `MedullaAdapter` (`net8.0`): no NuGet PackageReferences; depends on local `ref` assemblies;
- `CommonUsage` (`netstandard2.0`): `MQTTnet 4.3.7.1207`, `Newtonsoft.Json 13.0.3`, and related packages;
- `data_process`: see each subdirectory's `requirements.txt`.

## Build and Packaging

From the `MyParking` directory, run the official script (Debug by default):

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\build-and-package.ps1
```

Release build:

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File .\build-and-package.ps1 -Configuration Release
```

Script flow:

1. Build `CommonUsage` and copy `CommonUsage.dll` to the root `ref/` directory;
2. Build `MedullaAdapter` and `MultiWheelC`;
3. Package M/C outputs into `output/M` and `output/C`, both using the same `CommonUsage.dll`.

After a fresh clone or dependency change, if `--no-restore` fails, restore first and then package:

```powershell
dotnet restore CommonUsage-MultiVehicleSync\commonusage\CommonUsage.csproj
dotnet restore MedullaAdapter\MedullaAdapter.csproj
dotnet restore MultiWheelC\MultiWheelC.csproj
```

Primary intermediate outputs:

```text
MedullaAdapter/build/Medulla/plugins/MedullaAdapter.dll
MultiWheelC/build/Clumsy/MultiWheelC.dll
```

Do not edit artifacts under `bin`, `obj`, `build`, or `output`, and do not manually overwrite `ref/CommonUsage.dll`.

## Physical Runtime and MCU Configuration

The physical-robot plugins cannot be started independently with `dotnet run`. Compatible Clumsy / Medulla hosts must load:

```text
output/C/MultiWheelC.dll
output/M/MedullaAdapter.dll
```

The required host versions, deployment directories, and complete startup procedure have not yet been provided.

MCU defaults confirmed from the current source:

| Setting | Default |
| --- | --- |
| MCU port | `COM4` |
| MCU connection baud rate | `1000000` |
| CAN | One channel at `500000 bit/s`, with a `10 ms` retry time |
| Serial | Three channels at `9600 bit/s`, with a `10 ms` receive-frame time |
| Battery port index | `3` |
| Maximum remote-control spin rate | `30 deg/s` |
| Wheel-speed diagnostic directory | `logs\wheel-speed` |

`docs/chassis参考.json` is a chassis-parameter example. No automatic loader for it was found in the source. Treat the actual host configuration as authoritative.

Before physical testing, verify the port, vehicle ID, steering zero and limits, speed units, motor direction, clamp limits, and emergency-stop chain. Begin with lifted drive wheels or a segregated low-speed, short-distance test area and retain an independent physical emergency stop; never rely on software stopping alone.

## Single-Robot Test Entries

`MultiWheelC/Experiments` currently enables these host test entries:

- `准备：四个舵轮与车头方向一致`
- `SendMotion：连续前进4m`
- `SendXYThSpeed：输入角度原地自转`
- `SendMotion：左转90°半径2m圆弧`
- `SendMotion：蟹行直线4m`
- `SendMotion：蟹行左转90°半径2m圆弧`
- `SendMotion：4m S型曲线`
- `新版控制器：4m直线轨迹跟踪`
- `新版控制器：直线-左半圆-直线轨迹跟踪`
- `新版控制器：直线-圆弧-折线组合测试`

These are run through the Clumsy host's test interface and are not an automated `dotnet test` suite. Motion tests record the experiment number, reference path, Detour pose, wheel-derived velocity, and control commands according to their configuration. The clamp tests in `MultiWheelC/Experiments/ClampTests.cs` are currently commented out in full and are not registered with the host.

## Experiment Data Analysis

The tracking recorder saves CSV files under the host application's:

```text
TrackingExperiments/
```

Medulla wheel-speed diagnostics can be controlled with the `StartWheelSpeedDiagnostic` and `StopWheelSpeedDiagnostic` utility buttons. Their default output directory is:

```text
logs/wheel-speed/
```

### New-controller trajectory processing

```powershell
python -m pip install -r data_process\新版控制器轨迹测试处理\requirements.txt
python data_process\plot_new_controller_experiment.py "path\trial1.csv" "path\trial2.csv" --output-dir "path\plots"
```

This tool creates one six-panel summary for each new-controller CSV, covering the path, lateral/heading errors, speed, and front/rear GCP and four-wheel steering angles. When no CSV is passed, it scans only the `data_process` root and its `data` subdirectory.

### Legacy-controller trajectory processing

```powershell
python -m pip install -r data_process\旧版控制器轨迹测试处理\requirements.txt
python data_process\旧版控制器轨迹测试处理\run_all_plots.py "path\trial1.csv" "path\trial2.csv" --output-dir "path\plots"
```

The legacy tool defaults to `20 Hz` resampling and a `0.55 s` filter window; use `--frequency` and `--window` to change them.

### Steering-response processing

```powershell
python -m pip install -r data_process\电机响应处理\requirements.txt
python data_process\电机响应处理\plot_steering_response.py
```

By default this reads the latest `*_snapshot.csv` under `logs\wheel-speed`. See [`data_process/电机响应处理/README.md`](data_process/电机响应处理/README.md).

## Incomplete or Pending Validation

- Lidar point clouds, tire recognition, automatic vehicle entry, vehicle release, and the complete parking-operation state machine;
- Full physical acceptance, fault injection, and long-duration testing for current motion and clamp functions;
- Steering soft-limit prediction and automatic body reorientation; only the design document [`docs/SteeringConstraintDesign.md`](docs/SteeringConstraintDesign.md) exists today;
- Automated unit tests and continuous integration;
- Multi-robot communication, formation, synchronization, and safety fallback; `FleetKinematics.cs` is currently only a placeholder;
- Host versions, plugin deployment directories, configuration-file locations, and the release process.

## Contributing

1. Prioritize single-robot closed-loop behavior, parking functions, and tracking quality; do not enable multi-robot code prematurely.
2. Preserve the boundaries among `CommonUsage`, `Shared`, `MedullaAdapter`, and `MultiWheelC`.
3. Document coordinate frames, units, defaults, applicable vehicle types, and safe ranges for new parameters.
4. After changing the related projects, run `build-and-package.ps1` and confirm that the M/C packages use the same `CommonUsage.dll`.
5. Do not change velocity or steering signs, CAN IDs, remote-control mappings, mechanical limits, or mode-switch policy unless explicitly requested.
6. The team still needs to document its branch, review, and release processes.

See [`AGENTS.md`](AGENTS.md) for more detailed collaboration rules.

## License

No license file is currently included. Use and distribution must follow internal company policy.
