feat(lon): acceleration EQ + accel logger

Port the accel-eq feature onto testing:
- AccelEq (accel_eq.py): tunable max-accel curve read from the
  dp_lon_accel_profiles param (validated, stock fallback, mtime-gated,
  personality-linked), feeding the accel clip.
- AccelLogger (accel_logger.py): logs clean human-acceleration samples to
  /realdata/accel_log.csv.
- Wired both into the ACM/AEM/APM longitudinal planner.
- Feature README at dragonpilot/accel-eq.md.

params_keys.h is generated from the settings entry at build (not committed
here). Dashy web UI handled separately.
This commit is contained in:
Rick Lan
2026-06-29 15:26:28 +08:00
parent 0344359479
commit a8272966b5
13 changed files with 1193 additions and 38 deletions
+254
View File
@@ -0,0 +1,254 @@
# Acceleration EQ
User-tunable longitudinal acceleration. The driver edits EQ-style **speed → max
acceleration** curves, grouped into named **profiles**, in the dashy web UI; the
longitudinal planner reads the active profile and uses its curve as the accel
ceiling. A companion **logger** records the driver's own acceleration (when they
control the throttle) so the UI can later show "where you actually accelerate".
The dashy web UI lives in a **separate repo**; this doc covers the
dragonpilot/planner side (the contract, the planner reader, the logger) and
summarizes the dashy side it integrates with.
---
## Architecture
```
┌─ dashy web UI (separate repo) ─┐ GET/POST ┌─ serverd ──────────┐
│ EQ editor · profiles · the │ ──────────► │ params REST API + │
│ personality→profile links │ /api/... │ /api/accel_eq/config│
└────────────────────────────────┘ └─────────┬──────────┘
│ Params
dp_lon_accel_profiles (JSON param)
┌─ longitudinal_planner.py ────────────────────▼───────────────┐
│ AccelEq (accel_eq.py): read+cache JSON (mtime-gated), resolve │
│ the active profile by personality/active → max_accel(v) │
│ AccelLogger (accel_logger.py): log clean human-accel samples │
│ → /data/media/0/realdata/accel_log.csv │
└─────────────────────────────────────────────────────────────────┘
```
Two stores, opposite directions:
| Store | Holds | Written by | Read by |
|---|---|---|---|
| `dp_lon_accel_profiles` (JSON param) | the whole EQ doc — profiles + curves, the manual `active` selection, the personality links | dashy | planner |
| `/data/media/0/realdata/accel_log.csv` | the driver's natural-acceleration samples (`vEgo,aEgo`) | **planner** (AccelLogger) | dashy overlay (future) |
The param is declared in `dragonpilot/settings/min-feat.lon.accel-eq.py`
(generated into `common/params_keys.h` at build). The CSV is telemetry, not
config, so it lives on the drive-log partition, not in the params store.
---
## Data contract — `dp_lon_accel_profiles`
The authoritative shape is what dashy's `serializeDoc` writes and the planner
reads. Example:
```json
{
"active": "Sport",
"use_personality": false,
"personality_map": { "0": "Sport", "1": "Stock", "2": "Eco" },
"profiles": [
{ "name": "Stock", "max": {"bp": [0, 10, 25, 40], "v": [1.6, 1.2, 0.8, 0.6]} },
{ "name": "Eco", "source": "Stock", "max": {"bp": [0, 12, 30, 40], "v": [1.0, 0.8, 0.6, 0.5]} }
]
}
```
- **`profiles`** — ordered list. Each has a non-empty **unique** `name` and a
`max` curve `{bp:[m/s…], v:[m/s²…]}`. Speeds (`bp`) are stored in **m/s**
regardless of the UI display unit. A missing/invalid `max` → that profile uses
stock.
- **`active`** — the manually selected profile name (used when `use_personality`
is off). There is **no separate `active` param** — it lives in this doc.
- **`use_personality`** + **`personality_map`** — the personality link (below).
- **`source`** (optional) — UI lineage only (the duplicate-from profile, drawn
as the grey reference line). The planner ignores it and any other unknown key.
> **"Stock"** is a UI-protected baseline (not renamable/deletable, read-only in
> the editor). The planner treats it as a **live mirror of the injected stock
> table** — it ignores any stored curve named "Stock", so a planner stock change
> always wins.
There is **no `version` field and no turn-limit curve**: schema changes are
handled by versioning the release (or, if ever incompatible, the param key); the
turn-accel limit is the planner's stock `_A_TOTAL_MAX_*` and is not tunable.
---
## Profile selection
Resolved on init, whenever the param mtime changes, and whenever the personality
changes. The rule:
```
read/cache the JSON doc
doc invalid / empty / missing → STOCK (regardless of personality)
doc valid:
use_personality == true → personality_map[personality]
use_personality == false → active
→ resolve that name to a profile (exact match) and validate its curve
matched + valid → that profile's curve
unmapped / unset / no match / Stock / invalid curve → STOCK
```
**Stock is the single universal fallback.** No "first profile" fallback, and
when `use_personality` is on an unmapped personality falls to Stock (not to the
manual `active`).
| `use_personality` | situation | result |
|---|---|---|
| true | personality mapped → real profile, valid curve | that profile |
| true | personality unmapped | **Stock** |
| false | `active` → real profile, valid curve | that profile |
| false | `active` unset/empty | **Stock** |
| either | name points at a missing profile / is "Stock" / curve invalid | **Stock** |
| either | doc missing / empty / unparseable / not a usable dict | **Stock** |
### Personality link
For each openpilot personality the driver links a profile, stored in
`personality_map` keyed by the `LongitudinalPersonality` enum int — **`"0"`
aggressive, `"1"` standard, `"2"` relaxed**. With `use_personality` on, the
existing **personality button** selects the profile (no new onroad control).
The planner reads the live personality from `selfdriveState.personality.raw`
(the int) — the same source the MPC uses — not from the param.
> **Coupling, by design:** `LongitudinalPersonality` also drives openpilot's
> follow distance, so a personality link makes the button a single "aggression"
> dial (accel feel + following together). Turn the link off to set them
> independently (manual `active`).
---
## Planner: `AccelEq` (`dragonpilot/selfdrive/controls/lib/accel_eq.py`)
Instantiated in `LongitudinalPlanner` and pure-observation safe — any failure
falls back to stock and never raises into planning.
- **Stock is injected**, not hardcoded: the planner owns the canonical
`A_CRUISE_MAX_*` table and passes it in (`AccelEq(A_CRUISE_MAX_BP,
A_CRUISE_MAX_VALS)`). This keeps a single source of truth and lets `accel_eq`
stay a leaf module (it never imports the planner — that would be circular).
- **Read is mtime-gated; the parsed doc is cached.** `maybe_refresh(personality)`
`stat()`s the param each frame; only an **mtime change** triggers a re-read
(`_reload_doc``Params.get`). A **personality change** just re-resolves the
cached doc (`_resolve`) — zero I/O.
- **`max_accel(v_ego)`** = `np.interp` over the active curve, feeding the
planner's accel clip. The default personality is a `-1` sentinel so the first
real `maybe_refresh` always resolves.
`limit_accel_in_turns` is unchanged stock (uses `_A_TOTAL_MAX_*`).
### Validation is a safety boundary — `_validate_curve`
The param is externally writable (hand-edit, script, an older/buggy dashy), so
the planner never trusts it. `_validate_curve` re-sorts and bounds every curve
before it can shape the accel ceiling:
- shape: dict with equal-length `bp`/`v` lists, `MIN_PTS(2) ≤ n ≤ MAX_PTS(12)`,
all finite numbers;
- **sort** pairs by speed (required — `np.interp` needs increasing `bp`);
- clamp speed to `[0, SPEED_CEIL(60)]`; reject if any adjacent gap `< MIN_GAP(0.5)`;
- **clamp value to `[0, MAX_ACCEL_CEIL]`** (`= ACCEL_MAX`, 2.0 m/s²) — the actual
accel cap.
Anything that fails → that curve is unusable → stock. dashy mirrors these exact
rules client-side (UX) so the editor can't author a curve the planner rejects;
the planner's copy is the guarantee.
---
## Logger: `AccelLogger` (`dragonpilot/selfdrive/controls/lib/accel_logger.py`)
Logs the driver's **natural** acceleration so the data reflects *their*
preference, not openpilot's. Only "clean free human-acceleration" samples are
kept — `_should_log` requires **all** of:
| condition | signal |
|---|---|
| op long not active (human owns throttle) | `controlsState.longControlState == off` |
| accelerating on the gas | `gasPressed and aEgo > 0` |
| not braking | `not brakePressed` |
| no blinker (not turning/lane-changing) | `not (leftBlinker or rightBlinker)` |
| in Drive | `gearShifter == drive` |
| moving (not creeping/stopped) | `not standstill and vEgo > 1.0` |
| no near lead | no lead, or `dRel / max(vEgo, 0.1) > 2.0 s` |
| straight (not in a curve) | lateral accel `< 1.0 m/s²` |
Behavior: buffer matching `(vEgo, aEgo)` in RAM and **append to the CSV once a
minute** (`FLUSH_DT`, frame-counted) — one write/min spares the flash; up to
~1 min of samples is lost on a hard shutdown (negligible for an aggregate).
Fully exception-isolated; on a write failure it drops the buffered rows and
no-ops (e.g. path not writable in dev). The clean-sample gate makes growth slow,
so there is no size cap. CSV columns: `vEgo,aEgo` (m/s, m/s²).
---
## Constants — single source of truth
`accel_eq.py` owns the contract constants (`SPEED_CEIL`, `MIN_GAP`, `MIN_PTS`,
`MAX_PTS`, `MAX_ACCEL_CEIL`). serverd serves them at `GET /api/accel_eq/config`
and the dashy model applies them over its built-in fallback defaults at load, so
the editor's limits can't drift from the planner. (`MAX_PTS` especially must
match: a curve above the planner cap would be silently rejected → stock.)
---
## Persistence round-trip
dashy serializes the doc to a **JSON string**; the planner reads a parsed
**dict**. serverd bridges them:
1. dashy `POST /api/settings/params/dp_lon_accel_profiles` with the JSON string.
2. serverd `_save_param` detects the JSON-typed param and `json.loads`-es the
string, then `Params.put(key, dict)` (the `(dict, JSON)` caster stores it).
Malformed JSON → **400**, not 500.
3. planner `Params.get(...)` → parsed dict → `AccelEq._reload_doc` caches it.
`dp_lon_accel_profiles` is allowlisted in serverd's `_param_allowed`.
---
## Dashy side (separate repo)
The web UI implements: the canvas **EQ editor** (drag points, add/remove,
numeric entry, reset, undo/redo, a live "you are here" speed marker), **profile
management** (create/duplicate/rename/delete, quick-switch), the
**personality→profile pickers**, and a client-side **mirror of
`_validate_curve`** so the editor enforces the planner's limits. It talks to
serverd's params REST API and `/api/accel_eq/config`. The display unit follows
`IsMetric`; storage is always m/s.
---
## Files (this repo)
| File | Role |
|---|---|
| `dragonpilot/selfdrive/controls/lib/accel_eq.py` | `AccelEq` — profile reader/resolver |
| `dragonpilot/selfdrive/controls/lib/accel_logger.py` | `AccelLogger` — accel CSV logger |
| `dragonpilot/selfdrive/controls/lib/tests/test_accel_eq.py` | AccelEq tests |
| `dragonpilot/selfdrive/controls/lib/tests/test_accel_logger.py` | AccelLogger tests |
| `dragonpilot/settings/min-feat.lon.accel-eq.py` | declares `dp_lon_accel_profiles` |
| `selfdrive/controls/lib/longitudinal_planner.py` | owns `A_CRUISE_MAX_*`, wires in `AccelEq` + `AccelLogger` |
Run tests: `uv run python -m pytest dragonpilot/selfdrive/controls/lib/tests/ -q`
---
## Notes / future
- **Habit overlay** in dashy — read `accel_log.csv` (server-side aggregate to an
85th-percentile band) and draw it behind the EQ curve. Needs no new param.
- The **turn-limit channel** is intentionally not tunable (dropped from the UI
and the planner; turn limit stays stock).
- dashy follow-ups to keep in sync with this side: trim serverd's
`ACCEL_EQ_CONFIG` to the constants `accel_eq` still exposes, and mirror the
Stock-fallback selection rule in the dashy model.
+231 -10
View File
@@ -51,6 +51,14 @@ from openpilot.system.hardware import PC, HARDWARE
from openpilot.system.ui.lib.multilang import multilang as base_multilang
from dragonpilot.settings import SETTINGS
# dragonpilot's translation catalog (.mo) is where dashy's JS strings are merged
# by update_translations.py; used to build the web UI's translation map. Falls
# back to base multilang if the dragonpilot wrapper isn't importable.
try:
from dragonpilot.system.ui.lib.multilang import multilang as dp_multilang
except Exception:
dp_multilang = base_multilang
try:
from openpilot.system.version import get_build_metadata as _get_build_metadata
except Exception:
@@ -61,6 +69,26 @@ DEFAULT_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), '..') if
WEB_DIST_PATH = os.path.join(os.path.dirname(__file__), "web", "dist")
CAR_PARAMS_CACHE_TTL = 30 # seconds
# Accel-EQ contract constants — single source of truth is the planner's
# accel_eq.py. Served to the web UI so its model can't drift from the
# planner (a curve the planner would reject must be un-authorable in the editor).
# Guarded: standalone/dev dashy without the dragonpilot tree falls back to the
# web model's own built-in defaults (ACCEL_EQ_CONFIG stays None → /api endpoint
# 404s → JS keeps defaults).
try:
from dragonpilot.selfdrive.controls.lib import accel_eq as _AC
# Only the scalar contract constants accel_eq still owns. Turn and the
# schema version were dropped; stock is no longer an accel_eq constant —
# it's injected into AccelEq from the planner's A_CRUISE_MAX table, so it
# isn't served here (the dashy model keeps its built-in stock default,
# which matches A_CRUISE_MAX).
ACCEL_EQ_CONFIG = {
"max_pts": _AC.MAX_PTS, "min_pts": _AC.MIN_PTS, "min_gap": _AC.MIN_GAP,
"speed_ceil": _AC.SPEED_CEIL, "max_accel_ceil": _AC.MAX_ACCEL_CEIL,
}
except Exception:
ACCEL_EQ_CONFIG = None
logger = logging.getLogger("dashy")
@@ -147,6 +175,14 @@ class AppCache:
except Exception:
return False
def lang_switch_available(self):
"""Whether the dashy language switcher should be offered — always.
Native language selection isn't device-gated, and the switcher is
harmless even where a native one exists, so dashy offers it on every
device (previously excluded comma 3/3x)."""
return True
def _is_release_channel(self):
if _get_build_metadata is None:
return False
@@ -279,21 +315,70 @@ _CONTROL_PARAMS = {
'dp_dev_go_off_road', # Controls tab: force-offroad toggle
'DoReboot', # Controls tab: reboot button
'ExperimentalMode', # Tesla HUD: tap set-speed circle to toggle
'LanguageSetting', # Settings tab: language switch (comma-4; "main_<code>")
'dp_lon_accel_profiles', # Accel EQ: profile library (JSON) — includes the active selection
}
# Control params whose value is a string/JSON, not a bool. The generic
# control-param GET path reads bools (get_bool); these must be read as
# their raw string so the web UI gets the actual value back. POST already
# stores them as strings via _save_param's default branch.
_RAW_STRING_PARAMS = {
'dp_lon_accel_profiles',
}
assert _RAW_STRING_PARAMS <= _CONTROL_PARAMS, "raw-string params must also be allowlisted in _CONTROL_PARAMS"
def _param_allowed(key):
return key in _PARAM_SETTINGS or key in _CONTROL_PARAMS
def _sync_language(params):
"""Apply the current LanguageSetting param to multilang.
The language switch only writes the param; this makes the translation
catalog reflect it (so served strings / the i18n map use the right language)."""
current_lang = params.get("LanguageSetting")
if not current_lang:
return
lang_str = current_lang.decode() if isinstance(current_lang, bytes) else str(current_lang)
lang_str = lang_str.removeprefix("main_")
if lang_str != base_multilang.language and lang_str in base_multilang.languages.values():
base_multilang._language = lang_str
base_multilang.setup()
def _build_i18n_map():
"""Translation map {english: translated} for the active language, consumed
by the web UI's tr(). Sourced from the dragonpilot .mo catalog, where dashy's
JS strings are merged by update_translations.py. Empty for English / when no
catalog is loaded → the web tr() falls back to the original English text."""
try:
dp_multilang._ensure_loaded()
catalog = getattr(dp_multilang._dragon_translation, '_catalog', None)
except Exception:
catalog = None
if not catalog:
return {}
# GNUTranslations._catalog keys are msgid strings; skip the "" header entry
# and the '\x00'-joined plural keys, and drop empty translations.
return {k: v for k, v in catalog.items()
if isinstance(k, str) and k and '\x00' not in k and v}
# --- API Endpoints ---
@api_handler
async def init_api(request):
"""Provide initial data to the client."""
cache: AppCache = request.app['cache']
_sync_language(cache.params)
return web.json_response({
'dp_dev_dashy': cache.get_bool_safe("dp_dev_dashy", True),
'isOffroad': cache.get_bool_safe("IsOffroad", False),
# Translation map for the web UI's tr() — shipped at boot so strings are
# localized before the settings panel can open.
'i18n': _build_i18n_map(),
})
@@ -384,14 +469,8 @@ async def get_settings_config_api(request):
params = cache.params
# Update language if changed
current_lang = params.get("LanguageSetting")
if current_lang:
lang_str = current_lang.decode() if isinstance(current_lang, bytes) else str(current_lang)
lang_str = lang_str.removeprefix("main_")
if lang_str != base_multilang.language and lang_str in base_multilang.languages.values():
base_multilang._language = lang_str
base_multilang.setup()
# Apply the current LanguageSetting (the switch only writes the param).
_sync_language(params)
context = cache.get_settings_context()
settings_with_values = []
@@ -425,7 +504,24 @@ async def get_settings_config_api(request):
section_copy['settings'] = settings_list
settings_with_values.append(section_copy)
response_data = {'settings': settings_with_values}
# Language switcher metadata rides along with the settings (it's settings-
# adjacent and the UI already fetches this). The list comes from the device's
# translation catalog, not a param; the switch itself writes the
# LanguageSetting param via the generic /api/settings/params endpoint.
# Offered only where lang_switch_available() (not comma 3/3x).
# Labels mirror openpilot's raylib device UI (tr("Change Language") /
# tr("Select a language")) and are translated by the same catalog.
languages = ({'available': True,
'current': base_multilang.language,
'list': base_multilang.languages,
'title': base_multilang.tr('Change Language'),
'dialog': base_multilang.tr('Select a language')}
if cache.lang_switch_available() else {'available': False})
# Refresh the web UI's translation map too, so switching language updates
# dashy's own strings (not just the SETTINGS labels) without a reload.
response_data = {'settings': settings_with_values, 'languages': languages,
'i18n': _build_i18n_map()}
cache._settings_cache = response_data
cache._settings_cache_time = now
return web.json_response(response_data)
@@ -492,7 +588,19 @@ async def save_param_api(request):
if 'value' not in data:
return web.json_response({'error': 'value is required in body'}, status=400)
_save_param(params, param_name, data['value'])
try:
_save_param(params, param_name, data['value'])
except ValueError as e:
# malformed JSON / un-coercible INT|FLOAT body — a client error, not a 500
return web.json_response({'error': f'Invalid value for {param_name}: {e}'}, status=400)
# Mirror upstream openpilot's TogglesLayout: a needs_restart param also
# requests an onroad cycle so the change takes effect (openpilot restarts
# when the car is powered on). The web UI blocks these toggles while engaged
# so this can't fire mid-drive.
if setting is not None and setting.get('needs_restart'):
params.put_bool("OnroadCycleRequested", True)
cache.invalidate()
logger.info(f"Param saved: {param_name}={data['value']}")
@@ -510,6 +618,12 @@ def _save_param(params, key, value):
params.put(key, int(value))
elif param_type == 3: # FLOAT
params.put(key, float(value))
elif param_type == 5: # JSON
# Parse an incoming JSON string to a dict/list so Params.put's
# (dict|list, JSON) caster (json.dumps) stores it; put() has no
# (str, JSON) caster and would raise. Malformed JSON raises here and
# is surfaced to the client. Already-parsed bodies pass through.
params.put(key, json.loads(value) if isinstance(value, str) else value)
elif isinstance(value, bool):
params.put_bool(key, value)
else:
@@ -521,12 +635,117 @@ def _save_param(params, key, value):
raise
@api_handler
async def get_accel_eq_config_api(request):
"""Serve the planner's accel-eq contract constants (the single source of
truth in accel_eq.py) so the web model can't drift from the planner.
404 when unavailable — the web UI uses this to gate the whole Accel tab.
"Available" means BOTH: the planner lib imported (constants known) AND the
dp_lon_accel_profiles param is registered on this build (so saves work).
Checking the param registration — not just the import — avoids showing a
tab whose saves would fail on a build where the planner side isn't deployed.
Standalone/dev dashy → 404 → tab hidden, web model keeps built-in defaults."""
if ACCEL_EQ_CONFIG is None:
return web.json_response({'error': 'accel-eq config unavailable'}, status=404)
params = request.app['cache'].params
try:
params.check_key('dp_lon_accel_profiles') # raises if not in the params manifest
except Exception:
return web.json_response({'error': 'accel-eq param unavailable'}, status=404)
return web.json_response(ACCEL_EQ_CONFIG)
@api_handler
async def get_accel_eq_habit_api(request):
"""Serve logged (speed, accel) samples for the Accel-EQ 'habit cloud' overlay.
Reads accel_log.csv from the data dir (where the planner's AccelLogger writes
it) — two columns: speed m/s, accel m/s². Uniform-strided down to ~2000
points so the density is preserved without shipping tens of thousands of
samples. Missing/empty file → {'points': []} (the overlay just doesn't show)."""
import bisect
path = os.path.join(DEFAULT_DIR, 'accel_log.csv')
samples = []
try:
with open(path) as f:
for line in f:
parts = line.split(',')
if len(parts) < 2:
continue
try:
samples.append((float(parts[0]), float(parts[1])))
except ValueError:
continue
except FileNotFoundError:
pass
# Reference grid: sliding windows over speed that hold enough samples. Thin
# windows are SKIPPED (not bailed on), so a sparse very-low-speed slice (the
# log starts at 1 m/s) or a thin high-speed tail doesn't wipe out the whole
# reference — it just isn't drawn there.
ordered = sorted(samples, key=lambda t: t[0])
speeds = [t[0] for t in ordered]
accels = [t[1] for t in ordered]
STEP, HALF, MIN_W = 0.5, 1.5, 60
grid = [] # (speed, sorted accel window)
s = 0.0
while s <= 40.0:
lo = bisect.bisect_left(speeds, s - HALF)
hi = bisect.bisect_right(speeds, s + HALF)
if hi - lo >= MIN_W:
grid.append((s, sorted(accels[lo:hi])))
s += STEP
# Availability probe (?meta=1): sample count + how many reference points we
# could draw, so the UI offers the overlay only when it's actually useful —
# without shipping the dataset.
if request.query.get('meta'):
return web.json_response({'count': len(samples), 'bands': len(grid)})
# Cloud: uniform stride to ~2000 samples (preserves the density distribution).
stride = max(1, len(samples) // 2000)
points = [[round(sp, 2), round(a, 3)] for sp, a in samples[::stride]]
# Envelope: three smooth reference lines for setting a max-accel ceiling —
# usual (p75), brisk (p90) and hardest (p98) of how hard you accelerate at
# each speed. All upper-range: most samples are gentle partial throttle, so
# low percentiles just hug zero and don't inform a ceiling. Moving-average
# smoothed and forced non-increasing (max-accel eases with speed).
def _band(pct):
raw = [(gs, win[min(len(win) - 1, int(pct * len(win)))]) for gs, win in grid]
out, cur = [], float('inf')
for i in range(len(raw)):
a = max(0, i - 2); b = min(len(raw), i + 3) # moving average ±2
avg = sum(v for _, v in raw[a:b]) / (b - a)
cur = min(cur, avg) # non-increasing
out.append([round(raw[i][0], 1), round(cur, 2)])
return out
envelope = {'lower': _band(0.75), 'mid': _band(0.90), 'upper': _band(0.98)}
return web.json_response({'points': points, 'envelope': envelope})
def _get_param_value(params, key):
"""Get a single param value via its declared setting type, or as a
bool for control-only params that have no SETTINGS entry."""
setting = _PARAM_SETTINGS.get(key)
if setting is not None:
return _get_setting_value(params, setting)
if key in _RAW_STRING_PARAMS:
try:
raw = params.get(key)
if raw is None:
return None
# JSON-typed params (e.g. dp_lon_accel_profiles) come back from
# Params.get already json.loads'd into a dict/list — re-serialize so
# the web gets valid JSON, not Python repr (str(dict) → single quotes,
# which JSON.parse can't read → client silently falls back to seed).
if isinstance(raw, (dict, list)):
return json.dumps(raw)
return raw.decode('utf-8', errors='replace') if isinstance(raw, bytes) else str(raw)
except Exception:
return None
if key in _CONTROL_PARAMS:
try:
return params.get_bool(key)
@@ -822,6 +1041,8 @@ def setup_aiohttp_app(host: str, port: int, debug: bool):
app.router.add_get("/api/play", serve_player_api)
app.router.add_get("/api/manifest.m3u8", serve_manifest_api)
app.router.add_get("/api/settings", get_settings_config_api)
app.router.add_get("/api/accel_eq/config", get_accel_eq_config_api)
app.router.add_get("/api/accel_eq/habit", get_accel_eq_habit_api)
app.router.add_get("/api/settings/params/{param_name}", get_param_api)
app.router.add_post("/api/settings/params/{param_name}", save_param_api)
app.router.add_get("/api/models", get_model_list_api)
File diff suppressed because one or more lines are too long
+29 -26
View File
File diff suppressed because one or more lines are too long
@@ -0,0 +1,157 @@
"""
Copyright (c) 2026, Rick Lan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, and/or sublicense,
for non-commercial purposes only, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
- Commercial use (e.g. use in a product, service, or activity intended to
generate revenue) is prohibited without explicit written permission from
the copyright holder.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Acceleration EQ — planner-side reader. Loads the active profile's max-accel
curve from the dp_lon_accel_profiles param (validated, with a stock fallback)
and exposes it to the longitudinal planner. The editor UI lives in dashy.
"""
import math
import os
import numpy as np
from openpilot.common.params import Params
from openpilot.common.swaglog import cloudlog
from opendbc.car.interfaces import ACCEL_MAX
PROFILES_KEY = "dp_lon_accel_profiles"
STOCK_NAME = "Stock" # the protected default — a live mirror of injected stock, never a stored curve
SPEED_CEIL = 60.0
MIN_GAP = 0.5
MIN_PTS = 2
MAX_PTS = 12 # our own sanity bound (np.interp has no limit); must match dashy's MAX_PTS
MAX_ACCEL_CEIL = ACCEL_MAX
def _validate_curve(curve, ceil):
"""Return a sorted, clamped (bp, v) tuple, or None if unusable."""
if not isinstance(curve, dict):
return None
bp, v = curve.get("bp"), curve.get("v")
if not isinstance(bp, list) or not isinstance(v, list):
return None
if len(bp) != len(v) or not (MIN_PTS <= len(bp) <= MAX_PTS):
return None
try:
pairs = sorted(((float(b), float(a)) for b, a in zip(bp, v, strict=True)), key=lambda p: p[0])
except (TypeError, ValueError):
return None
if not all(math.isfinite(b) and math.isfinite(a) for b, a in pairs):
return None
out_bp, out_v = [], []
for b, a in pairs:
b = min(max(b, 0.0), SPEED_CEIL)
if out_bp and b - out_bp[-1] < MIN_GAP:
return None
out_bp.append(b)
out_v.append(min(max(a, 0.0), ceil))
return out_bp, out_v
def _select_active(data, name):
"""The profile with exactly this name, or None (caller falls back to stock).
No first-profile fallback — an unknown name means 'use stock'."""
if not isinstance(data, dict) or not name:
return None
profiles = data.get("profiles")
if not isinstance(profiles, list):
return None
return next((p for p in profiles
if isinstance(p, dict) and p.get("name") == name), None)
def _resolve_active_name(data, personality):
"""Profile name to use: when use_personality is on, the personality-mapped name
(None if unmapped → stock); otherwise the manual 'active' selection (None if
unset → stock). The caller treats None / no match as 'use stock'."""
if not isinstance(data, dict):
return None
if data.get("use_personality"):
pmap = data.get("personality_map")
name = pmap.get(str(personality)) if isinstance(pmap, dict) else None
else:
name = data.get("active")
return name if isinstance(name, str) and name else None
class AccelEq:
def __init__(self, stock_bp, stock_v, params=None):
# Stock fallback is injected by the planner (its A_CRUISE_MAX_* table), so
# there's a single source of truth and accel_eq stays a leaf — it never
# imports the planner (which imports AccelEq → would be circular).
self._stock_bp, self._stock_v = list(stock_bp), list(stock_v)
self._params = params if params is not None else Params()
self._personality = -1 # unknown sentinel → the first maybe_refresh() with a real value (0/1/2) forces a resolve
self._doc = None # cached parsed profiles JSON (re-read only on mtime change)
self._max_bp, self._max_v = list(stock_bp), list(stock_v)
self._reload_doc()
self._last_mtime = self._mtime(PROFILES_KEY)
def _mtime(self, key):
try:
return os.stat(self._params.get_param_path(key)).st_mtime
except OSError:
return None
def maybe_refresh(self, personality):
# The JSON read is the only expensive part, so gate it on the param mtime
# and cache the parsed doc. A personality change (button press) doesn't
# touch the param at all — just re-resolve the active curve from the cache.
mtime = self._mtime(PROFILES_KEY)
if mtime != self._last_mtime:
self._last_mtime = mtime
self._personality = personality
self._reload_doc() # JSON changed → re-read + re-resolve
elif personality != self._personality:
self._personality = personality
self._resolve() # selection changed → re-resolve cache, no I/O
def _reload_doc(self):
# Read + parse + cache the profiles JSON (the expensive step), then resolve.
try:
self._doc = self._params.get(PROFILES_KEY) # parsed dict, or None
except Exception as e: # never let tuning data crash the planner
cloudlog.warning(f"AccelEq: failed to read profiles, using stock: {e}")
self._doc = None
self._resolve()
def _resolve(self):
# Pick the active profile's curve from the cached doc. Pure in-memory — no
# param access, so it's cheap to call on every personality change.
max_bp, max_v = list(self._stock_bp), list(self._stock_v)
try:
data = self._doc
if data:
name = _resolve_active_name(data, self._personality)
# Anything unresolved — unmapped personality, unset/empty active, no
# matching profile, or the Stock baseline itself — falls through to the
# injected stock. Stock is a live mirror of injected stock, so its stored
# curve is ignored (a planner stock change always takes effect).
if name and name != STOCK_NAME:
prof = _select_active(data, name)
if prof is not None:
mc = _validate_curve(prof.get("max"), MAX_ACCEL_CEIL)
if mc is not None:
max_bp, max_v = mc
except Exception as e: # never let tuning data crash the planner
cloudlog.warning(f"AccelEq: failed to resolve profile, using stock: {e}")
self._max_bp, self._max_v = max_bp, max_v
def max_accel(self, v_ego):
return float(np.interp(v_ego, self._max_bp, self._max_v))
@@ -0,0 +1,94 @@
"""
Copyright (c) 2026, Rick Lan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, and/or sublicense,
for non-commercial purposes only, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
- Commercial use (e.g. use in a product, service, or activity intended to
generate revenue) is prohibited without explicit written permission from
the copyright holder.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Param-only settings entry for the Acceleration EQ feature.
No UI fields (section/type/title), so the native dp settings panel skips
these; generate_settings.py still emits them into common/params_keys.h.
The editor UI lives in the dashy web repo.
"""
from cereal import car
from openpilot.common.constants import CV
from openpilot.common.realtime import DT_MDL
from openpilot.common.swaglog import cloudlog
from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState
V_MIN = 1.0 # m/s — exclude creep/stop
TTC_MIN = 0.5 # s — lead must be at least this far in time
LAT_ACCEL_MAX = 1.0 # m/s² — exclude curves
FLUSH_DT = 60.0 # s — append the buffer to disk at most this often
# Accel-log data is observational telemetry, not config, so it lives as a CSV on the
# drive-log partition (where rlogs live) rather than in the params store.
LOG_PATH = "/data/media/0/realdata/accel_log.csv"
def _should_log(long_off, gas, brake, blinker, in_drive, moving, a_ego, lead_ttc, lat_accel):
"""True only for a clean, free, straight-line human-acceleration sample."""
return (long_off and gas and a_ego > 0.0
and not brake and not blinker
and in_drive and moving
and lead_ttc > TTC_MIN and lat_accel < LAT_ACCEL_MAX)
class AccelLogger:
"""Logs the driver's natural acceleration — clean, free, straight-line manual
samples — to a CSV (columns: vEgo m/s, aEgo m/s²). Samples are buffered in RAM
and appended once a minute to spare the flash; up to FLUSH_DT of samples are
lost on an ungraceful shutdown, which is negligible for an aggregate. The gate
makes clean samples rare, so the file grows very slowly (no cap needed).
Fully exception-isolated — it can never perturb the planner."""
def __init__(self, CP, path=None):
self._CP = CP
self._path = path if path is not None else LOG_PATH
self._buf = []
self._frames = 0
self._flush_every = max(1, int(FLUSH_DT / DT_MDL))
def _flush(self):
# Take + clear the buffer first, so RAM stays bounded even if the write
# fails (e.g. path not writable) — those rows are simply dropped.
rows, self._buf = self._buf, []
try:
with open(self._path, "a") as f:
f.writelines(f"{v:.3f},{a:.3f}\n" for v, a in rows)
except Exception as e:
cloudlog.warning(f"AccelLogger: write failed (dropped {len(rows)} rows): {e}")
def update(self, sm):
try:
self._frames += 1
cs = sm['carState']
v_ego = cs.vEgo
long_off = sm['controlsState'].longControlState == LongCtrlState.off
in_drive = cs.gearShifter == car.CarState.GearShifter.drive
moving = (not cs.standstill) and v_ego > V_MIN
blinker = cs.leftBlinker or cs.rightBlinker
lat_accel = abs(v_ego ** 2 * cs.steeringAngleDeg * CV.DEG_TO_RAD
/ (self._CP.steerRatio * self._CP.wheelbase))
lead = sm['radarState'].leadOne
lead_ttc = (lead.dRel / max(v_ego, 0.1)) if lead.status else float('inf')
if _should_log(long_off, cs.gasPressed, cs.brakePressed,
blinker, in_drive, moving, cs.aEgo, lead_ttc, lat_accel):
self._buf.append((v_ego, cs.aEgo))
if self._buf and self._frames % self._flush_every == 0:
self._flush()
except Exception as e:
cloudlog.warning(f"AccelLogger.update failed (ignored): {e}")
@@ -0,0 +1,269 @@
from dragonpilot.selfdrive.controls.lib.accel_eq import _validate_curve, MAX_ACCEL_CEIL, _select_active, MAX_PTS
def test_valid_curve_passes_through_sorted():
bp, v = _validate_curve({"bp": [0, 10, 25, 40], "v": [1.6, 1.2, 0.8, 0.6]}, MAX_ACCEL_CEIL)
assert bp == [0.0, 10.0, 25.0, 40.0]
assert v == [1.6, 1.2, 0.8, 0.6]
def test_unsorted_speeds_are_sorted_together():
bp, v = _validate_curve({"bp": [40, 0, 10], "v": [0.6, 1.6, 1.2]}, MAX_ACCEL_CEIL)
assert bp == [0.0, 10.0, 40.0]
assert v == [1.6, 1.2, 0.6]
def test_value_clamped_to_ceiling():
_, v = _validate_curve({"bp": [0, 20], "v": [99.0, -5.0]}, MAX_ACCEL_CEIL)
assert v == [MAX_ACCEL_CEIL, 0.0]
def test_too_few_points_rejected():
assert _validate_curve({"bp": [0], "v": [1.6]}, MAX_ACCEL_CEIL) is None
def test_too_many_points_rejected():
n = MAX_PTS + 1
assert _validate_curve({"bp": list(range(n)), "v": [1.0] * n}, MAX_ACCEL_CEIL) is None
def test_mismatched_lengths_rejected():
assert _validate_curve({"bp": [0, 10], "v": [1.6]}, MAX_ACCEL_CEIL) is None
def test_duplicate_speeds_rejected():
assert _validate_curve({"bp": [10, 10], "v": [1.0, 0.9]}, MAX_ACCEL_CEIL) is None
def test_non_numeric_rejected():
assert _validate_curve({"bp": [0, "x"], "v": [1.6, 1.2]}, MAX_ACCEL_CEIL) is None
def test_non_finite_rejected():
assert _validate_curve({"bp": [0, float("inf")], "v": [1.6, 1.2]}, MAX_ACCEL_CEIL) is None
def test_none_and_non_dict_rejected():
assert _validate_curve(None, MAX_ACCEL_CEIL) is None
assert _validate_curve([1, 2], MAX_ACCEL_CEIL) is None
DATA = {"profiles": [
{"name": "Eco", "max": {"bp": [0, 20], "v": [1.0, 0.8]}},
{"name": "Sport", "max": {"bp": [0, 20], "v": [2.0, 1.6]}},
]}
def test_select_named_profile():
assert _select_active(DATA, "Sport")["name"] == "Sport"
def test_unknown_name_returns_none():
assert _select_active(DATA, "Nope") is None # no first-profile fallback
def test_empty_name_returns_none():
assert _select_active(DATA, "") is None
def test_no_profiles_returns_none():
assert _select_active({"profiles": []}, "x") is None
assert _select_active({}, "x") is None
assert _select_active(None, "x") is None
def test_unnamed_profiles_ignored():
bad = {"profiles": [{"max": {}}, {"name": 5}]}
assert _select_active(bad, "x") is None
import numpy as np
from openpilot.common.params import Params
from dragonpilot.selfdrive.controls.lib.accel_eq import AccelEq, PROFILES_KEY
# Stock fallback is the planner's A_CRUISE_MAX table, injected into AccelEq.
from openpilot.selfdrive.controls.lib.longitudinal_planner import (
A_CRUISE_MAX_BP as STOCK_MAX_BP, A_CRUISE_MAX_VALS as STOCK_MAX_V,
)
def test_unset_uses_stock():
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, Params())
for v in (0., 5., 10., 25., 40., 55.):
assert c.max_accel(v) == float(np.interp(v, STOCK_MAX_BP, STOCK_MAX_V))
def test_active_profile_drives_curve():
p = Params()
p.put(PROFILES_KEY, {"active": "Sport", "profiles": [
{"name": "Sport", "max": {"bp": [0, 40], "v": [2.0, 1.0]},
"turn": {"bp": [20, 40], "v": [1.7, 3.2]}},
]}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
assert c.max_accel(0.) == 2.0
assert c.max_accel(40.) == 1.0
def test_switching_active_changes_curve_on_refresh():
p = Params()
p.put(PROFILES_KEY, {"active": "Eco", "profiles": [
{"name": "Eco", "max": {"bp": [0, 40], "v": [1.0, 0.5]}},
{"name": "Sport", "max": {"bp": [0, 40], "v": [2.0, 1.0]}},
]}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
assert c.max_accel(0.) == 1.0
p.put(PROFILES_KEY, {"active": "Sport", "profiles": [
{"name": "Eco", "max": {"bp": [0, 40], "v": [1.0, 0.5]}},
{"name": "Sport", "max": {"bp": [0, 40], "v": [2.0, 1.0]}},
]}, block=True)
c.maybe_refresh(1)
assert c.max_accel(0.) == 2.0
def test_no_work_when_unchanged(monkeypatch):
p = Params()
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
c.maybe_refresh(1) # warm up: first call resolves the -1 sentinel to a real personality
calls = []
monkeypatch.setattr(c, "_reload_doc", lambda: calls.append("doc"))
monkeypatch.setattr(c, "_resolve", lambda: calls.append("resolve"))
c.maybe_refresh(1)
c.maybe_refresh(1)
assert calls == [] # mtime + personality unchanged → no read, no resolve
def test_personality_change_resolves_without_reread(monkeypatch):
# A personality change must re-resolve from the cached doc, never re-read the param.
p = Params()
p.put(PROFILES_KEY, {
"use_personality": True,
"personality_map": {"0": "Sport", "1": "Stock", "2": "Eco"},
"profiles": [
{"name": "Stock", "max": {"bp": [0, 40], "v": [1.6, 0.6]}},
{"name": "Sport", "max": {"bp": [0, 40], "v": [2.0, 1.0]}},
{"name": "Eco", "max": {"bp": [0, 40], "v": [1.0, 0.5]}},
],
}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
reads = []
monkeypatch.setattr(c, "_reload_doc", lambda: reads.append(1))
c.maybe_refresh(0) # aggressive → Sport, resolved from cache
assert c.max_accel(0.) == 2.0
assert reads == [] # no JSON re-read on a personality change
def test_malformed_profiles_falls_back_to_stock():
p = Params()
# write raw invalid json bytes directly
p.put(PROFILES_KEY, {"active": "Bad", "profiles": [{"name": "Bad", "max": {"bp": [0], "v": [9]}}]}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
assert c.max_accel(0.) == float(np.interp(0., STOCK_MAX_BP, STOCK_MAX_V))
def test_deleted_after_set_reverts_to_stock():
p = Params()
p.put(PROFILES_KEY, {"active": "S", "profiles": [{"name": "S", "max": {"bp": [0, 40], "v": [2.0, 1.0]}}]}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
assert c.max_accel(0.) == 2.0
p.remove(PROFILES_KEY)
c.maybe_refresh(1)
assert c.max_accel(0.) == float(np.interp(0., STOCK_MAX_BP, STOCK_MAX_V))
def test_invalid_or_empty_doc_falls_back_to_stock_regardless_of_personality():
# A doc that isn't a usable dict (non-dict, empty, or no profiles) → stock,
# for every personality. Mirrors Params.get() returning None on bad/empty JSON.
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, Params())
stock0 = float(np.interp(0., STOCK_MAX_BP, STOCK_MAX_V))
for bad in (None, [1, 2, 3], {}, {"use_personality": True, "personality_map": {"0": "X"}}):
c._doc = bad
for pers in (0, 1, 2):
c._personality = pers
c._resolve()
assert c.max_accel(0.) == stock0
from openpilot.selfdrive.controls.lib.longitudinal_planner import (
get_max_accel, A_CRUISE_MAX_BP, A_CRUISE_MAX_VALS,
)
def test_accelcurves_matches_legacy_get_max_accel_when_unset():
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, Params())
for v in (0., 7., 10., 18., 25., 33., 40., 50.):
assert c.max_accel(v) == float(get_max_accel(v))
assert get_max_accel(v) == float(np.interp(v, A_CRUISE_MAX_BP, A_CRUISE_MAX_VALS))
from dragonpilot.selfdrive.controls.lib.accel_eq import _resolve_active_name
PDATA = {"use_personality": True,
"personality_map": {"0": "Sport", "1": "Stock", "2": "Eco"},
"profiles": [{"name": "Stock"}, {"name": "Sport"}, {"name": "Eco"}]}
def test_personality_maps_to_profile():
assert _resolve_active_name(PDATA, 0) == "Sport"
assert _resolve_active_name(PDATA, 2) == "Eco"
def test_personality_off_uses_active():
d = {"use_personality": False, "active": "Manual", "profiles": []}
assert _resolve_active_name(d, 0) == "Manual"
def test_personality_off_no_active_returns_none():
assert _resolve_active_name({"use_personality": False}, 0) is None # → stock
def test_personality_unmapped_returns_none():
d = {"use_personality": True, "personality_map": {"0": "Sport"}, "active": "Manual"}
assert _resolve_active_name(d, 1) is None # 1 unmapped → stock, not manual
def test_personality_missing_map_returns_none():
assert _resolve_active_name({"use_personality": True}, 0) is None
def test_resolve_handles_non_dict():
assert _resolve_active_name(None, 0) is None
def test_personality_selects_profile_in_accelcurves():
p = Params()
p.put(PROFILES_KEY, {
"use_personality": True,
"personality_map": {"0": "Sport", "1": "Stock", "2": "Eco"},
"profiles": [
{"name": "Stock", "max": {"bp": [0, 40], "v": [1.6, 0.6]}},
{"name": "Sport", "max": {"bp": [0, 40], "v": [2.0, 1.0]}},
{"name": "Eco", "max": {"bp": [0, 40], "v": [1.0, 0.5]}},
],
}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
c.maybe_refresh(0) # aggressive (live personality from the planner)
assert c.max_accel(0.) == 2.0 # Sport
c.maybe_refresh(2) # relaxed
assert c.max_accel(0.) == 1.0 # Eco
def test_personality_off_uses_manual_active_in_accelcurves():
p = Params()
p.put(PROFILES_KEY, {
"active": "Stock",
"use_personality": False,
"personality_map": {"0": "Sport"},
"profiles": [
{"name": "Stock", "max": {"bp": [0, 40], "v": [1.6, 0.6]}},
{"name": "Sport", "max": {"bp": [0, 40], "v": [2.0, 1.0]}},
],
}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
c.maybe_refresh(0) # personality 0 would map to Sport, but use_personality is off
assert c.max_accel(0.) == 1.6 # manual "active": Stock wins → injected stock
def test_active_in_json_drives_curve_without_legacy_key():
p = Params()
p.put(PROFILES_KEY, {
"active": "Sport",
"profiles": [
{"name": "Stock", "max": {"bp": [0, 40], "v": [1.6, 0.6]}},
{"name": "Sport", "max": {"bp": [0, 40], "v": [2.0, 1.0]}},
],
}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
assert c.max_accel(0.) == 2.0
def test_no_active_falls_back_to_stock():
# No "active" and personality off → injected stock, NOT the first profile.
p = Params()
p.put(PROFILES_KEY, {
"profiles": [
{"name": "Sport", "max": {"bp": [0, 40], "v": [2.0, 1.0]}},
{"name": "Eco", "max": {"bp": [0, 40], "v": [1.0, 0.5]}},
],
}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
assert c.max_accel(0.) == float(np.interp(0., STOCK_MAX_BP, STOCK_MAX_V)) # stock, not Sport
assert c.max_accel(0.) != 2.0
def test_stock_profile_ignores_stored_curve():
# A stale/legacy "Stock" with a stored curve must NOT override the injected
# (live) stock table — Stock is a mirror, so a planner stock change wins.
p = Params()
p.put(PROFILES_KEY, {
"active": "Stock",
"profiles": [{"name": "Stock", "max": {"bp": [0, 40], "v": [0.1, 0.1]}}],
}, block=True)
c = AccelEq(STOCK_MAX_BP, STOCK_MAX_V, p)
assert c.max_accel(0.) == float(np.interp(0., STOCK_MAX_BP, STOCK_MAX_V))
assert c.max_accel(0.) != 0.1
@@ -0,0 +1,95 @@
from types import SimpleNamespace
from cereal import car
from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState
from dragonpilot.selfdrive.controls.lib.accel_logger import _should_log, AccelLogger
def _clean(**over):
args = dict(long_off=True, gas=True, brake=False, blinker=False,
in_drive=True, moving=True, a_ego=0.8, lead_ttc=9.9, lat_accel=0.2)
args.update(over)
return _should_log(**args)
def test_clean_sample_logs():
assert _clean() is True
def test_each_condition_blocks():
assert _clean(long_off=False) is False # op long active
assert _clean(gas=False) is False
assert _clean(a_ego=0.0) is False # not accelerating
assert _clean(brake=True) is False
assert _clean(blinker=True) is False
assert _clean(in_drive=False) is False
assert _clean(moving=False) is False
assert _clean(lead_ttc=1.0) is False # lead too close
assert _clean(lat_accel=5.0) is False # in a curve
DRIVE = car.CarState.GearShifter.drive
CP = SimpleNamespace(steerRatio=15.0, wheelbase=2.7)
def _sm(**over):
cs = dict(vEgo=10.0, aEgo=0.8, gasPressed=True, brakePressed=False,
steeringPressed=False, leftBlinker=False, rightBlinker=False,
standstill=False, gearShifter=DRIVE, steeringAngleDeg=0.0)
cs.update(over)
return {
'carState': SimpleNamespace(**cs),
'controlsState': SimpleNamespace(longControlState=LongCtrlState.off),
'radarState': SimpleNamespace(leadOne=SimpleNamespace(status=False, dRel=0.0)),
}
def test_clean_sample_buffers(tmp_path):
log = AccelLogger(CP, path=str(tmp_path / "h.csv"))
log.update(_sm(vEgo=10.0, aEgo=0.8))
assert log._buf == [(10.0, 0.8)]
def test_gate_blocks_dirty_sample(tmp_path):
log = AccelLogger(CP, path=str(tmp_path / "h.csv"))
sm = _sm()
sm['controlsState'] = SimpleNamespace(longControlState=LongCtrlState.pid) # op long active
log.update(sm)
assert log._buf == []
def test_in_curve_sample_rejected_end_to_end(tmp_path):
# large steering -> lateral accel exceeds LAT_ACCEL_MAX -> not buffered
log = AccelLogger(CP, path=str(tmp_path / "h.csv"))
log.update(_sm(vEgo=10.0, aEgo=0.8, steeringAngleDeg=45.0))
assert log._buf == []
def test_flush_appends_and_clears(tmp_path):
p = tmp_path / "h.csv"
log = AccelLogger(CP, path=str(p))
log.update(_sm(vEgo=10.0, aEgo=0.8))
log.update(_sm(vEgo=12.0, aEgo=0.5))
log._flush()
assert log._buf == []
assert p.read_text().splitlines() == ["10.000,0.800", "12.000,0.500"]
# second flush appends (does not truncate)
log.update(_sm(vEgo=5.0, aEgo=1.0))
log._flush()
assert p.read_text().splitlines()[-1] == "5.000,1.000"
def test_auto_flush_on_cadence(tmp_path):
p = tmp_path / "h.csv"
log = AccelLogger(CP, path=str(p))
log._flush_every = 1 # flush every frame
log.update(_sm(vEgo=10.0, aEgo=0.8))
assert p.read_text().splitlines() == ["10.000,0.800"]
assert log._buf == []
def test_flush_failure_drops_rows_no_raise(tmp_path):
# parent dir does not exist -> open() fails -> rows dropped, no raise, RAM bounded
log = AccelLogger(CP, path=str(tmp_path / "missing" / "h.csv"))
log.update(_sm())
log._flush()
assert log._buf == []
def test_update_never_raises(tmp_path):
log = AccelLogger(CP, path=str(tmp_path / "h.csv"))
log.update({}) # missing keys -> swallowed
assert log._buf == []
def test_logger_is_pure_observation(tmp_path):
log = AccelLogger(CP, path=str(tmp_path / "h.csv"))
assert log.update(_sm()) is None
@@ -22,6 +22,24 @@ def update_translations():
ret = os.system(cmd)
assert ret == 0
# Also extract dashy's web UI strings (JavaScript) into the same template.
# dashy is a sibling repo — build_and_deploy.sh copies only the minified dist
# into the tree (where tr() calls are renamed and unscannable), so scan its
# web/src and append the tr()/tr_noop() literals via --join-existing. Override
# the location with DASHY_SRC; skipped quietly if the source isn't present.
dashy_src = os.environ.get("DASHY_SRC") or os.path.join(BASEDIR, "..", "dashy", "web", "src")
dashy_src = os.path.realpath(dashy_src)
if os.path.isdir(dashy_src):
js_files = [os.path.relpath(os.path.join(root, fn), dashy_src)
for root, _, filenames in os.walk(dashy_src)
for fn in filenames if fn.endswith(".js")]
if js_files:
cmd = ("xgettext -L JavaScript --keyword=tr --keyword=tr_noop --from-code=UTF-8 "
"--join-existing "
f"-D {dashy_src} -o {POT_FILE} {' '.join(js_files)}")
ret = os.system(cmd)
assert ret == 0
# Generate/update translation files for each language
for name in multilang.languages.values():
po_file = os.path.join(TRANSLATIONS_DIR, f"dragonpilot_{name}.po")
+4
View File
@@ -80,6 +80,10 @@ _KNOWN_ITEM_KEYS = _UI_REQUIRED_KEYS | {
# text_input_item: text field that POSTs typed value to the named action endpoint.
# action_item: button that POSTs to the named action endpoint with no payload.
"action",
# Setting a needs_restart param also writes OnroadCycleRequested on save
# (dashy), mirroring upstream's TogglesLayout. Behavioral only — ignored by
# generate_settings.py (not a param-storage field).
"needs_restart",
# Param-storage fields (consumed by generate_settings.py, ignored by UI)
"flags", "param_type",
}
@@ -0,0 +1,31 @@
"""
Copyright (c) 2026, Rick Lan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, and/or sublicense,
for non-commercial purposes only, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
- Commercial use (e.g. use in a product, service, or activity intended to
generate revenue) is prohibited without explicit written permission from
the copyright holder.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Param-only settings entry for the Acceleration EQ feature.
No UI fields (section/type/title), so the native dp settings panel skips
these; generate_settings.py still emits them into common/params_keys.h.
The editor UI lives in the dashy web repo.
"""
ITEMS = [
# The whole EQ doc (profiles, curves, personality links, and the manual
# `active` selection) lives in this one JSON param. The planner reads it;
# the dashy web UI writes it.
{"key": "dp_lon_accel_profiles", "flags": "PERSISTENT", "param_type": "JSON"},
# Accel samples are logged to a CSV on the drive-log partition (AccelLogger),
# not a param — see dragonpilot/selfdrive/controls/lib/accel_logger.py.
]
@@ -26,6 +26,7 @@ ITEMS = [
"section": _SEC, "key": "OpenpilotEnabledToggle", "type": "toggle_item",
"title": lambda: tr("Enable openpilot"),
"description": lambda: tr(_TOGGLES_DESC["OpenpilotEnabledToggle"]),
"needs_restart": True,
"condition": _DASHY,
},
{
@@ -55,12 +56,14 @@ ITEMS = [
"section": _SEC, "key": "RecordFront", "type": "toggle_item",
"title": lambda: tr("Record and Upload Driver Camera"),
"description": lambda: tr(_TOGGLES_DESC["RecordFront"]),
"needs_restart": True,
"condition": _DASHY,
},
{
"section": _SEC, "key": "RecordAudio", "type": "toggle_item",
"title": lambda: tr("Record and Upload Microphone Audio"),
"description": lambda: tr(_TOGGLES_DESC["RecordAudio"]),
"needs_restart": True,
"condition": _DASHY,
},
{
@@ -17,6 +17,8 @@ from openpilot.common.swaglog import cloudlog
from dragonpilot.selfdrive.controls.lib.acm import ACM
from dragonpilot.selfdrive.controls.lib.aem import AEM
from dragonpilot.selfdrive.controls.lib.apm import APM
from dragonpilot.selfdrive.controls.lib.accel_eq import AccelEq
from dragonpilot.selfdrive.controls.lib.accel_logger import AccelLogger
A_CRUISE_MAX_VALS = [1.6, 1.2, 0.8, 0.6]
A_CRUISE_MAX_BP = [0., 10.0, 25., 40.]
@@ -75,6 +77,8 @@ class LongitudinalPlanner:
self.acm = ACM()
self.aem = AEM()
self.apm = APM()
self.accel_eq = AccelEq(A_CRUISE_MAX_BP, A_CRUISE_MAX_VALS)
self.accel_logger = AccelLogger(CP)
@staticmethod
def parse_model(model_msg):
@@ -118,7 +122,9 @@ class LongitudinalPlanner:
# No change cost when user is controlling the speed, or when standstill
prev_accel_constraint = not (reset_state or sm['carState'].standstill)
accel_clip = [ACCEL_MIN, get_max_accel(v_ego)]
self.accel_eq.maybe_refresh(sm['selfdriveState'].personality.raw)
self.accel_logger.update(sm)
accel_clip = [ACCEL_MIN, self.accel_eq.max_accel(v_ego)]
steer_angle_without_offset = sm['carState'].steeringAngleDeg - sm['liveParameters'].angleOffsetDeg
accel_clip = limit_accel_in_turns(v_ego, steer_angle_without_offset, accel_clip, self.CP)