Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0fcbb1ab26 | ||
|
|
900d44806c | ||
|
|
c229b730c6 | ||
|
|
d01028b12b | ||
|
|
7d23a874e0 | ||
|
|
2ea989e5a3 | ||
|
|
658b161730 | ||
|
|
1c37ea029e | ||
|
|
de54c1ff40 | ||
|
|
f9c2152c9d | ||
|
|
7c1391dcf4 | ||
|
|
9952c4507f | ||
|
|
6e59fef093 | ||
|
|
71200709ab | ||
|
|
ecb42ee8d7 | ||
|
|
a6eb06618f | ||
|
|
2b1422352c | ||
|
|
f988478336 | ||
|
|
bc928defdb | ||
|
|
097740f348 | ||
|
|
e380efa98c | ||
|
|
f5d2472184 | ||
|
|
5eeda440be | ||
|
|
90718df8ce | ||
|
|
29d09661a4 | ||
|
|
fb1fae4f6e | ||
|
|
b3b37e80e4 | ||
|
|
20649df8a5 | ||
|
|
89fcf5b8dc | ||
|
|
50cc615d80 | ||
|
|
6cf46401b0 | ||
|
|
0598c5f8e1 | ||
|
|
3de1860494 | ||
|
|
105fc3b982 | ||
|
|
398a74c34d | ||
|
|
d3a03359f2 | ||
|
|
29050c06c9 | ||
|
|
1215e82dc0 | ||
|
|
79c03e9dd6 | ||
|
|
6c6bed1f14 | ||
|
|
74808332be | ||
|
|
008b1c11b5 | ||
|
|
77a374f7a4 | ||
|
|
c7430c7106 | ||
|
|
da38eccb72 | ||
|
|
383bfb9566 | ||
|
|
004a327afc | ||
|
|
237149e87a | ||
|
|
e763999e85 | ||
|
|
04ac6e3097 | ||
|
|
31cba53798 | ||
|
|
e5bc77ec15 | ||
|
|
4071a420c7 | ||
|
|
4491a02ef5 | ||
|
|
a3ae9c9ddf | ||
|
|
9c67ce6abb | ||
|
|
fd17b9d03e | ||
|
|
ca9d5b8eda | ||
|
|
bac9445026 |
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"servers": {
|
||||
"elmer-server": {
|
||||
"type": "stdio",
|
||||
"command": "python3",
|
||||
"args": [
|
||||
"/home/naeel/elmer/.vscode/mcp_server.py"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""MCP сервер для Elmer — БД, логи, ssh."""
|
||||
|
||||
import json, subprocess, sys
|
||||
|
||||
def handle(req):
|
||||
method = req.get("method", "")
|
||||
params = req.get("params", {})
|
||||
|
||||
if method == "list_tools":
|
||||
return {
|
||||
"tools": [
|
||||
{"name": "query_db", "description": "SQL-запрос к elmer.db", "inputSchema": {"type": "object", "properties": {"sql": {"type": "string"}}}},
|
||||
{"name": "server_logs", "description": "Логи сервера (последние N строк)", "inputSchema": {"type": "object", "properties": {"lines": {"type": "number", "default": 30}}}},
|
||||
{"name": "ssh", "description": "Выполнить bash-команду на ВМ", "inputSchema": {"type": "object", "properties": {"cmd": {"type": "string"}}}},
|
||||
]
|
||||
}
|
||||
|
||||
if method == "call_tool":
|
||||
name = params.get("name", "")
|
||||
args = params.get("arguments", {})
|
||||
|
||||
if name == "query_db":
|
||||
ssh(f"sqlite3 /opt/elmer/elmer.db \"{args['sql']}\"")
|
||||
elif name == "server_logs":
|
||||
ssh(f"sudo journalctl -u elmer --no-pager -n {args.get('lines', 30)}")
|
||||
elif name == "ssh":
|
||||
ssh(args["cmd"])
|
||||
else: return {"error": f"unknown tool: {name}"}
|
||||
|
||||
return {"result": "ok"}
|
||||
|
||||
def ssh(cmd):
|
||||
r = subprocess.run(["ssh", "-i", "/home/naeel/.ssh/naeel_vm_id_ed25519", "naeel@5.172.178.213", cmd], capture_output=True, text=True)
|
||||
return {"stdout": r.stdout, "stderr": r.stderr}
|
||||
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if line:
|
||||
resp = handle(json.loads(line))
|
||||
print(json.dumps(resp), flush=True)
|
||||
+72
-1
@@ -1,7 +1,7 @@
|
||||
# elmAI — Changelog / Полное описание проекта
|
||||
|
||||
> Файл для нового агента: прочитай — и ты в курсе всего.
|
||||
> Актуально: v0.77.0-dev, 7 июня 2026
|
||||
> Актуально: v0.95.0-dev, 10 июня 2026
|
||||
|
||||
---
|
||||
|
||||
@@ -132,6 +132,14 @@
|
||||
|
||||
### История версий (сервер)
|
||||
|
||||
#### v0.93.0-dev (10 июня 2026)
|
||||
- **Speed-test ELM327:** при первом подключении нового ELM — замер скорости ответа на 3 PID (RPM, MAF, STFT) × 3 раза каждый
|
||||
- **Адаптивный интервал:** динамический тест использует `max(250, avg_response × 3 × 1.5)` вместо жёстких 250ms
|
||||
- **Профиль устройства:** колонка `response_time_ms` в `device_profiles`, API `PUT /api/v1/elm/profile/<mac>`
|
||||
- **Fix:** `threading.Lock()` в `Database` — 0 ошибок при 20 конкурентных записях (было 8/20)
|
||||
- **UI:** прогресс speed-теста показывается пользователю
|
||||
- Деплой v0.93.0-dev на obdai.ru
|
||||
|
||||
#### v0.48.0 (7 июня 2026)
|
||||
- **Пробинг ELM327:** трехуровневый каскад (L0/L1/L2)
|
||||
- **Рефакторинг `obd/`:** разделение на независимые сервисы
|
||||
@@ -265,3 +273,66 @@ scp app/build/outputs/apk/debug/app-debug.apk obdai.ru:/opt/elmer/web/static/app
|
||||
| `fat-client` | Старая fat-client архитектура (устарела) |
|
||||
| `androbd-proto` | Прототип AndrOBD стейт-машины (устарела) |
|
||||
| `elm-layer-v2` | Старый ELM-слой (устарела) |
|
||||
|
||||
---
|
||||
|
||||
## 9. Динамический тест — START/STOP (v0.93+, 10.06.2026)
|
||||
|
||||
### Цель
|
||||
Выявить **потерю мощности, подсос воздуха, забитый фильтр, проблемы смеси** — ловля STFT/LTFT на сбросе газа.
|
||||
|
||||
### 5 быстрых PID (планировалось)
|
||||
1. **RPM** (010C)
|
||||
2. **MAF** (0110)
|
||||
3. **STFT** (0106)
|
||||
4. **LTFT** (0107)
|
||||
5. **TPS** (0111)
|
||||
|
||||
→ После тестов #43-#45 выяснилось: ELM327 v1.5 не успевает 5 PID за 250ms (данные склеиваются).
|
||||
→ После тестов #47-#48 (v0.93.0-dev): даже 3 PID × 250ms — 94% ошибок, ELM перестаёт отвечать после ~15 сэмплов.
|
||||
→ **Решение (текущее, v0.93.0): Speed-test при первом подключении ELM + адаптивный интервал.**
|
||||
|
||||
### Текущая стратегия (v0.93+)
|
||||
|
||||
#### Этап 0 — Speed-test (только при первом подключении нового ELM)
|
||||
- После инициализации ELM: замерить время ответа на 010C, 0110, 0106 — каждый 3 раза
|
||||
- Показать пользователю: `"⏱ Тест скорости: RPM 82ms MAF 91ms STFT 82ms"`
|
||||
- Сохранить `response_time_ms` в профиль устройства (по BT MAC)
|
||||
- Интервал = `max(250, avg_response × 3 × 1.5)`
|
||||
- При повторных запусках — использовать сохранённое значение
|
||||
|
||||
#### Этап 1 — Статика (перед СТАРТ)
|
||||
- Снять все доступные PID по одному разу
|
||||
- Определить какие PID отвечают, какие нет (7F 01 12)
|
||||
- **Запомнить** неподдерживаемые — больше не опрашивать
|
||||
- Время: ~3-4 секунды
|
||||
|
||||
#### Этап 2 — Динамика (250ms)
|
||||
- **3 PID**: RPM (010C), MAF (0110), STFT (0106)
|
||||
- LTFT, TPS, MAP, Load, coolant, IAT — один раз в статике
|
||||
|
||||
#### Этап 3 — Контроль качества
|
||||
- После СТОП проверить количество сэмплов и % ошибок
|
||||
- Если < 6-8 сэмплов или > 30% errors — сообщить водителю:
|
||||
> «Слишком быстро. Нажмите СТАРТ, плавно наберите ~3000 об/мин, **сбросьте газ, подождите 3-4 секунды**, нажмите СТОП.»
|
||||
|
||||
### Процедура для водителя
|
||||
1. Дождаться ДИАГНОСТИКА → зелёный
|
||||
2. Нажать СТАРТ
|
||||
3. Плавно газ до ~3000 об/мин
|
||||
4. **Резко сбросить газ**
|
||||
5. **Подождать 3-4 секунды** (без нажатий) — ЭБУ корректирует смесь
|
||||
6. СТОП
|
||||
7. ➤ (Send) — отправка на сервер
|
||||
|
||||
### Зачем ждать 3-4 секунды после сброса
|
||||
- MAF падает → STFT резко уходит в минус/плюс
|
||||
- ЭБУ пытается стабилизировать смесь
|
||||
- LTFT начинает подстраиваться
|
||||
- Именно эти 3-4 секунды — самое ценное для анализа
|
||||
|
||||
### Планы
|
||||
- Скорость — потом через GPS (не через OBD)
|
||||
- ~~Адаптивный интервал если ELM быстрее (v2.x)~~ ✅ Сделано в v0.93.0
|
||||
- Логирование в историю каждого теста
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
@@ -21,6 +22,7 @@ class Database:
|
||||
self.conn.row_factory = sqlite3.Row
|
||||
self.conn.execute("PRAGMA journal_mode=WAL")
|
||||
self.conn.execute("PRAGMA busy_timeout=30000")
|
||||
self._lock = threading.Lock()
|
||||
self._init_schema()
|
||||
|
||||
def __enter__(self):
|
||||
@@ -112,6 +114,7 @@ class Database:
|
||||
elm_desc TEXT,
|
||||
protocol TEXT,
|
||||
voltage TEXT,
|
||||
response_time_ms INTEGER DEFAULT 250,
|
||||
supported TEXT,
|
||||
unsupported TEXT,
|
||||
errors TEXT,
|
||||
@@ -127,6 +130,7 @@ class Database:
|
||||
|
||||
# Миграции: добавляем колонки, которых нет в старых БД
|
||||
migrations = [
|
||||
"ALTER TABLE device_profiles ADD COLUMN response_time_ms INTEGER DEFAULT 250",
|
||||
"ALTER TABLE sessions ADD COLUMN device_uuid TEXT",
|
||||
"ALTER TABLE sessions ADD COLUMN phone_lang TEXT",
|
||||
"ALTER TABLE sessions ADD COLUMN phone_tz TEXT",
|
||||
@@ -175,65 +179,65 @@ class Database:
|
||||
|
||||
Если request_id передан и уже существует — silently return (идемпотентность).
|
||||
"""
|
||||
ci = client_info
|
||||
with self._lock:
|
||||
ci = client_info
|
||||
|
||||
# Подсчёт DTC/PID из ответов
|
||||
dtc_count = 0
|
||||
pid_count = 0
|
||||
for r in responses:
|
||||
dec = (r.get("decoded") or "").lower()
|
||||
if dec.startswith("dtc"):
|
||||
dtc_count += 1
|
||||
elif ":" in dec and not dec.startswith(("vin", "dtc", "elm", "protocol")):
|
||||
pid_count += 1
|
||||
# Подсчёт DTC/PID из ответов
|
||||
dtc_count = 0
|
||||
pid_count = 0
|
||||
for r in responses:
|
||||
dec = (r.get("decoded") or "").lower()
|
||||
if dec.startswith("dtc"):
|
||||
dtc_count += 1
|
||||
elif ":" in dec and not dec.startswith(("vin", "dtc", "elm", "protocol")):
|
||||
pid_count += 1
|
||||
|
||||
# VIN из ответов
|
||||
vin = None
|
||||
for r in responses:
|
||||
dec = (r.get("decoded") or "")
|
||||
if dec.startswith("VIN:"):
|
||||
vin = dec[4:].strip()
|
||||
if len(vin) != 17:
|
||||
vin = None
|
||||
break
|
||||
# VIN из ответов
|
||||
vin = None
|
||||
for r in responses:
|
||||
dec = (r.get("decoded") or "")
|
||||
if dec.startswith("VIN:"):
|
||||
vin = dec[4:].strip()
|
||||
if len(vin) != 17:
|
||||
vin = None
|
||||
break
|
||||
|
||||
resp_json_str = json.dumps(response_json, ensure_ascii=False) if response_json else None
|
||||
resp_json_str = json.dumps(response_json, ensure_ascii=False) if response_json else None
|
||||
|
||||
self.conn.execute("""
|
||||
INSERT OR IGNORE INTO sessions (
|
||||
client_ip, real_ip, user_agent, content_length,
|
||||
phone_model, phone_maker, android_version, android_sdk,
|
||||
app_version, android_id, device_uuid, phone_lang, phone_tz, phone_display,
|
||||
elm_mac, elm_bt_name, obd_protocol,
|
||||
self.conn.execute("""
|
||||
INSERT OR IGNORE INTO sessions (
|
||||
client_ip, real_ip, user_agent, content_length,
|
||||
phone_model, phone_maker, android_version, android_sdk,
|
||||
app_version, android_id, device_uuid, phone_lang, phone_tz, phone_display,
|
||||
elm_mac, elm_bt_name, obd_protocol,
|
||||
vin, dtc_count, pid_count,
|
||||
duration_ms, response_count, error_count,
|
||||
retry_count, timeout_count, script_mode,
|
||||
transport, mock_mode, car_info,
|
||||
diagnosis_text, diagnosis_len, llm_model,
|
||||
llm_duration_ms, llm_success,
|
||||
raw_responses, request_id, response_json
|
||||
) VALUES (?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?, ?,?,?,?, ?,?,?,?,?)
|
||||
""", (
|
||||
ci.get("client_ip"), ci.get("real_ip"), ci.get("user_agent"),
|
||||
ci.get("content_length"),
|
||||
ci.get("phone_model"), ci.get("phone_maker"), ci.get("android_version"),
|
||||
ci.get("android_sdk"), ci.get("app_version"), ci.get("android_id"),
|
||||
ci.get("device_uuid"),
|
||||
ci.get("phone_lang"), ci.get("phone_tz"), ci.get("phone_display"),
|
||||
ci.get("elm_mac"), ci.get("elm_bt_name"), ci.get("obd_protocol"),
|
||||
vin, dtc_count, pid_count,
|
||||
duration_ms, response_count, error_count,
|
||||
retry_count, timeout_count, script_mode,
|
||||
transport, mock_mode, car_info,
|
||||
diagnosis_text, diagnosis_len, llm_model,
|
||||
llm_duration_ms, llm_success,
|
||||
raw_responses, request_id, response_json
|
||||
) VALUES (?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?, ?,?,?,?, ?,?,?,?,?)
|
||||
|
||||
""", (
|
||||
ci.get("client_ip"), ci.get("real_ip"), ci.get("user_agent"),
|
||||
ci.get("content_length"),
|
||||
ci.get("phone_model"), ci.get("phone_maker"), ci.get("android_version"),
|
||||
ci.get("android_sdk"), ci.get("app_version"), ci.get("android_id"),
|
||||
ci.get("device_uuid"),
|
||||
ci.get("phone_lang"), ci.get("phone_tz"), ci.get("phone_display"),
|
||||
ci.get("elm_mac"), ci.get("elm_bt_name"), ci.get("obd_protocol"),
|
||||
vin, dtc_count, pid_count,
|
||||
ci.get("duration_ms"), len(responses), ci.get("error_count", 0),
|
||||
ci.get("retry_count", 0), ci.get("timeout_count", 0),
|
||||
ci.get("script_mode"), ci.get("transport"), ci.get("mock_mode", 0),
|
||||
ci.get("car_info", ""),
|
||||
diagnosis, len(diagnosis), llm_model,
|
||||
llm_duration_ms, 1 if llm_success else 0,
|
||||
json.dumps(responses, ensure_ascii=False) if responses else None,
|
||||
request_id if request_id else None,
|
||||
resp_json_str,
|
||||
))
|
||||
self.conn.commit()
|
||||
ci.get("duration_ms"), len(responses), ci.get("error_count", 0),
|
||||
ci.get("retry_count", 0), ci.get("timeout_count", 0),
|
||||
ci.get("script_mode"), ci.get("transport"), ci.get("mock_mode", 0),
|
||||
ci.get("car_info", ""),
|
||||
diagnosis, len(diagnosis), llm_model,
|
||||
llm_duration_ms, 1 if llm_success else 0,
|
||||
json.dumps(responses, ensure_ascii=False) if responses else None,
|
||||
request_id if request_id else None,
|
||||
resp_json_str,
|
||||
))
|
||||
self.conn.commit()
|
||||
|
||||
def get_recent_sessions(self, limit: int = 50) -> list[dict]:
|
||||
"""Последние N сессий."""
|
||||
@@ -244,27 +248,28 @@ class Database:
|
||||
|
||||
def save_dtc_scan(self, client_info: dict, dtc_codes: list[str]):
|
||||
"""Сохраняет быстрый скан кодов ошибок."""
|
||||
self.conn.execute("""
|
||||
INSERT INTO sessions (
|
||||
client_ip, real_ip, user_agent,
|
||||
phone_model, phone_maker, android_version, android_sdk,
|
||||
app_version, android_id, device_uuid,
|
||||
elm_mac, elm_bt_name,
|
||||
dtc_count, response_count,
|
||||
script_mode, transport,
|
||||
raw_responses
|
||||
) VALUES (?,?,?, ?,?,?,?, ?,?,?, ?,?, ?,?, ?,?,?)
|
||||
""", (
|
||||
client_info.get("client_ip"), client_info.get("real_ip"), client_info.get("user_agent"),
|
||||
client_info.get("phone_model"), client_info.get("phone_maker"), client_info.get("android_version"),
|
||||
client_info.get("android_sdk"), client_info.get("app_version"), client_info.get("android_id"),
|
||||
client_info.get("device_uuid"),
|
||||
client_info.get("elm_mac"), client_info.get("elm_bt_name"),
|
||||
len(dtc_codes), 0,
|
||||
"dtc_scan", client_info.get("transport", "bt"),
|
||||
json.dumps([{"decoded": f"DTC stored: {c}"} for c in dtc_codes], ensure_ascii=False)
|
||||
))
|
||||
self.conn.commit()
|
||||
with self._lock:
|
||||
self.conn.execute("""
|
||||
INSERT INTO sessions (
|
||||
client_ip, real_ip, user_agent,
|
||||
phone_model, phone_maker, android_version, android_sdk,
|
||||
app_version, android_id, device_uuid,
|
||||
elm_mac, elm_bt_name,
|
||||
dtc_count, response_count,
|
||||
script_mode, transport,
|
||||
raw_responses
|
||||
) VALUES (?,?,?, ?,?,?,?, ?,?,?, ?,?, ?,?, ?,?,?)
|
||||
""", (
|
||||
client_info.get("client_ip"), client_info.get("real_ip"), client_info.get("user_agent"),
|
||||
client_info.get("phone_model"), client_info.get("phone_maker"), client_info.get("android_version"),
|
||||
client_info.get("android_sdk"), client_info.get("app_version"), client_info.get("android_id"),
|
||||
client_info.get("device_uuid"),
|
||||
client_info.get("elm_mac"), client_info.get("elm_bt_name"),
|
||||
len(dtc_codes), 0,
|
||||
"dtc_scan", client_info.get("transport", "bt"),
|
||||
json.dumps([{"decoded": f"DTC stored: {c}"} for c in dtc_codes], ensure_ascii=False)
|
||||
))
|
||||
self.conn.commit()
|
||||
|
||||
# ── device_profiles ──────────────────────────────────
|
||||
|
||||
@@ -283,35 +288,39 @@ class Database:
|
||||
def save_device_profile(self, mac: str, profile: dict):
|
||||
"""Сохраняет или обновляет профиль устройства.
|
||||
|
||||
profile — результат obd.probe.probe().
|
||||
profile — результат obd.probe.probe() + response_time_ms.
|
||||
"""
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
self.conn.execute("""
|
||||
INSERT INTO device_profiles
|
||||
(mac, level, elm_version, elm_desc, protocol, voltage,
|
||||
supported, unsupported, errors, first_seen, last_seen)
|
||||
VALUES (?,?,?,?,?,?, ?,?,?, ?,?)
|
||||
ON CONFLICT(mac) DO UPDATE SET
|
||||
level = excluded.level,
|
||||
elm_version = excluded.elm_version,
|
||||
elm_desc = excluded.elm_desc,
|
||||
protocol = excluded.protocol,
|
||||
voltage = excluded.voltage,
|
||||
supported = excluded.supported,
|
||||
unsupported = excluded.unsupported,
|
||||
errors = excluded.errors,
|
||||
last_seen = excluded.last_seen
|
||||
""", (
|
||||
mac,
|
||||
profile.get("level", -1),
|
||||
profile.get("elm_version"),
|
||||
profile.get("elm_desc"),
|
||||
profile.get("protocol"),
|
||||
profile.get("voltage"),
|
||||
json.dumps(profile.get("supported", []), ensure_ascii=False),
|
||||
json.dumps(profile.get("unsupported", []), ensure_ascii=False),
|
||||
json.dumps(profile.get("errors", []), ensure_ascii=False),
|
||||
now, now,
|
||||
))
|
||||
self.conn.commit()
|
||||
with self._lock:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
self.conn.execute("""
|
||||
INSERT INTO device_profiles
|
||||
(mac, level, elm_version, elm_desc, protocol, voltage,
|
||||
response_time_ms, supported, unsupported, errors,
|
||||
first_seen, last_seen)
|
||||
VALUES (?,?,?,?,?,?, ?,?,?,?, ?,?)
|
||||
ON CONFLICT(mac) DO UPDATE SET
|
||||
level = excluded.level,
|
||||
elm_version = excluded.elm_version,
|
||||
elm_desc = excluded.elm_desc,
|
||||
protocol = excluded.protocol,
|
||||
voltage = excluded.voltage,
|
||||
response_time_ms = excluded.response_time_ms,
|
||||
supported = excluded.supported,
|
||||
unsupported = excluded.unsupported,
|
||||
errors = excluded.errors,
|
||||
last_seen = excluded.last_seen
|
||||
""", (
|
||||
mac,
|
||||
profile.get("level", -1),
|
||||
profile.get("elm_version"),
|
||||
profile.get("elm_desc"),
|
||||
profile.get("protocol"),
|
||||
profile.get("voltage"),
|
||||
profile.get("response_time_ms", 250),
|
||||
json.dumps(profile.get("supported", []), ensure_ascii=False),
|
||||
json.dumps(profile.get("unsupported", []), ensure_ascii=False),
|
||||
json.dumps(profile.get("errors", []), ensure_ascii=False),
|
||||
now, now,
|
||||
))
|
||||
self.conn.commit()
|
||||
|
||||
|
||||
+1
-4
@@ -28,14 +28,11 @@ def register(app):
|
||||
|
||||
@app.route("/api/v1/ping-llm", methods=["GET"])
|
||||
def ping_llm():
|
||||
"""Проверка LLM с адаптивным кэшем. # API key check
|
||||
"""Проверка LLM с адаптивным кэшем (успех=60с, ошибка=7с)."""
|
||||
cfg = load()
|
||||
required = cfg.get("api", {}).get("key", "")
|
||||
if required and request.headers.get("X-Api-Key", "") != required:
|
||||
return jsonify({"ok": False, "error": "unauthorized"}), 401
|
||||
- Успех → кэш 60с
|
||||
- Ошибка → кэш 7с (LLM мог уже ожить)
|
||||
"""
|
||||
global _ping_llm_cache
|
||||
now = time.time()
|
||||
if _ping_llm_cache:
|
||||
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
"""
|
||||
api/raw_elm.py — Сырое взаимодействие с ELM327 (локальное + удалённое через Android).
|
||||
|
||||
ЛОКАЛЬНЫЙ РЕЖИМ (ELM327 подключён к серверу напрямую):
|
||||
POST /api/v1/elm/raw — отправить команду, получить сырой ответ
|
||||
POST /api/v1/elm/raw/batch — несколько команд
|
||||
POST /api/v1/elm/raw/drain — очистить буфер
|
||||
GET /api/v1/elm/raw/available — байт в буфере
|
||||
GET /api/v1/elm/raw/log — история команд
|
||||
GET /api/v1/elm/raw/mode — режим (normal/raw)
|
||||
|
||||
УДАЛЁННЫЙ РЕЖИМ (Android-ретранслятор):
|
||||
POST /api/v1/elm/raw/hello — Android: «я готов»
|
||||
POST /api/v1/elm/raw/cmd — Copilot: поставить команду в очередь
|
||||
GET /api/v1/elm/raw/cmd — Android: забрать команду
|
||||
POST /api/v1/elm/raw/response — Android: отправить ответ
|
||||
GET /api/v1/elm/raw/response — Copilot: прочитать ответ
|
||||
GET /api/v1/elm/raw/status — Copilot: статус устройства
|
||||
"""
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from flask import jsonify, request, Blueprint
|
||||
|
||||
logger = logging.getLogger("elmer.raw_api")
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# Глобальное состояние
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
_raw_mode = False
|
||||
_raw_elm = None # локальный RawELM
|
||||
|
||||
# Очередь команд (удалённый режим)
|
||||
_lock = threading.Lock()
|
||||
_pending_cmd: dict | None = None # команда, которую ждёт Android
|
||||
_pending_seq: int = 0 # номер последней команды
|
||||
_last_response: dict | None = None # последний ответ от ELM327
|
||||
_device_ready: bool = False # Android подключён и готов
|
||||
_device_info: dict = {} # информация об устройстве (из hello)
|
||||
_history: list[dict] = [] # история команд через Android
|
||||
|
||||
|
||||
def is_raw_mode() -> bool:
|
||||
return _raw_mode
|
||||
|
||||
def set_raw_mode(on: bool):
|
||||
global _raw_mode
|
||||
_raw_mode = on
|
||||
logger.info(f"RawELM mode: {'ON' if on else 'OFF'}")
|
||||
|
||||
def set_raw_elm(instance):
|
||||
global _raw_elm
|
||||
_raw_elm = instance
|
||||
|
||||
|
||||
bp = Blueprint("raw_elm", __name__)
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# ЛОКАЛЬНЫЙ РЕЖИМ — ELM327 подключён к серверу напрямую
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
@bp.route("/api/v1/elm/raw", methods=["POST"])
|
||||
def raw_command():
|
||||
if not _raw_elm:
|
||||
return jsonify({"error": "no local ELM connection"}), 503
|
||||
data = request.get_json(silent=True)
|
||||
if not data or "cmd" not in data:
|
||||
return jsonify({"error": "missing 'cmd'"}), 400
|
||||
cmd = data["cmd"].strip()
|
||||
if not cmd:
|
||||
return jsonify({"error": "empty cmd"}), 400
|
||||
timeout = data.get("timeout_ms")
|
||||
drain_first = data.get("drain_first", False)
|
||||
if drain_first:
|
||||
_raw_elm.drain()
|
||||
result = _raw_elm.send(cmd, timeout=timeout)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/batch", methods=["POST"])
|
||||
def raw_batch():
|
||||
if not _raw_elm:
|
||||
return jsonify({"error": "no local ELM connection"}), 503
|
||||
data = request.get_json(silent=True)
|
||||
if not data or "cmds" not in data:
|
||||
return jsonify({"error": "missing 'cmds'"}), 400
|
||||
cmds = data["cmds"]
|
||||
if len(cmds) > 100:
|
||||
return jsonify({"error": "too many commands (max 100)"}), 400
|
||||
timeout = data.get("timeout_ms")
|
||||
drain_between = data.get("drain_between", False)
|
||||
t0 = time.time()
|
||||
results = []
|
||||
for cmd in cmds:
|
||||
if drain_between:
|
||||
_raw_elm.drain()
|
||||
results.append(_raw_elm.send(cmd, timeout=timeout))
|
||||
total_elapsed = int((time.time() - t0) * 1000)
|
||||
return jsonify({"results": results, "total_elapsed_ms": total_elapsed})
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/drain", methods=["POST"])
|
||||
def raw_drain():
|
||||
if not _raw_elm:
|
||||
return jsonify({"error": "no local ELM connection"}), 503
|
||||
return jsonify(_raw_elm.drain())
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/available", methods=["GET"])
|
||||
def raw_available():
|
||||
if not _raw_elm:
|
||||
return jsonify({"error": "no local ELM connection"}), 503
|
||||
return jsonify({"available": _raw_elm.available()})
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/log", methods=["GET"])
|
||||
def raw_log():
|
||||
if not _raw_elm:
|
||||
return jsonify({"log": _history, "count": len(_history)})
|
||||
return jsonify({"log": _raw_elm.log, "count": len(_raw_elm.log)})
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/mode", methods=["GET", "POST"])
|
||||
def raw_mode_control():
|
||||
global _raw_mode
|
||||
if request.method == "POST":
|
||||
data = request.get_json(silent=True) or {}
|
||||
on = data.get("raw_mode", False)
|
||||
set_raw_mode(on)
|
||||
return jsonify({"raw_mode": _raw_mode, "has_local_elm": _raw_elm is not None,
|
||||
"device_ready": _device_ready})
|
||||
return jsonify({"raw_mode": _raw_mode, "has_local_elm": _raw_elm is not None,
|
||||
"device_ready": _device_ready})
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
# УДАЛЁННЫЙ РЕЖИМ — Android-ретранслятор
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
@bp.route("/api/v1/elm/raw/hello", methods=["POST"])
|
||||
def raw_hello():
|
||||
"""Android сообщает: «я подключился к ELM327, готов принимать команды».
|
||||
|
||||
Body: {
|
||||
"device_id": "android-xyz",
|
||||
"elm_version": "ELM327 v1.5",
|
||||
"protocol": "A4",
|
||||
"voltage": "12.3V"
|
||||
}
|
||||
"""
|
||||
global _device_ready, _device_info, _pending_cmd, _pending_seq, _last_response
|
||||
data = request.get_json(silent=True) or {}
|
||||
with _lock:
|
||||
_device_ready = True
|
||||
_device_info = {
|
||||
"device_id": data.get("device_id", "unknown"),
|
||||
"elm_version": data.get("elm_version", "?"),
|
||||
"protocol": data.get("protocol", "?"),
|
||||
"voltage": data.get("voltage", "?"),
|
||||
"connected_at": time.time(),
|
||||
}
|
||||
_pending_cmd = None
|
||||
_pending_seq = 0
|
||||
_last_response = None
|
||||
logger.info(f"RawELM: device ready — {_device_info['device_id']} "
|
||||
f"({_device_info['elm_version']}, proto {_device_info['protocol']})")
|
||||
return jsonify({"ok": True, "seq": 0})
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/cmd", methods=["POST"])
|
||||
def raw_enqueue_cmd():
|
||||
"""Copilot: поставить команду в очередь для Android.
|
||||
|
||||
Body: {
|
||||
"cmd": "0105",
|
||||
"timeout_ms": 500,
|
||||
"drain_first": false
|
||||
}
|
||||
"""
|
||||
global _pending_cmd, _pending_seq
|
||||
data = request.get_json(silent=True)
|
||||
if not data or "cmd" not in data:
|
||||
return jsonify({"error": "missing 'cmd'"}), 400
|
||||
|
||||
cmd = data["cmd"].strip()
|
||||
if not cmd:
|
||||
return jsonify({"error": "empty cmd"}), 400
|
||||
|
||||
with _lock:
|
||||
_pending_seq += 1
|
||||
_pending_cmd = {
|
||||
"cmd": cmd,
|
||||
"timeout_ms": data.get("timeout_ms", 500),
|
||||
"drain_first": data.get("drain_first", False),
|
||||
"seq": _pending_seq,
|
||||
}
|
||||
logger.info(f"RawELM: enqueued #{_pending_seq} → {cmd}")
|
||||
return jsonify({"ok": True, "seq": _pending_seq, "cmd": cmd})
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/cmd", methods=["GET"])
|
||||
def raw_dequeue_cmd():
|
||||
"""Android: забрать команду из очереди.
|
||||
|
||||
Returns:
|
||||
200 {"cmd": "0105", "seq": 1, ...} — есть команда
|
||||
204 — нет команды, полли дальше
|
||||
"""
|
||||
global _pending_cmd
|
||||
device_id = request.args.get("device_id", "")
|
||||
|
||||
with _lock:
|
||||
if not _device_ready:
|
||||
return jsonify({"error": "device not ready"}), 503
|
||||
if _pending_cmd is None:
|
||||
return "", 204 # No Content — полли дальше
|
||||
cmd = _pending_cmd
|
||||
_pending_cmd = None # забрали
|
||||
|
||||
logger.info(f"RawELM: dequeued #{cmd['seq']} → {cmd['cmd']} (device={device_id})")
|
||||
return jsonify(cmd)
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/response", methods=["POST"])
|
||||
def raw_post_response():
|
||||
"""Android: отправить ответ ELM327 на сервер.
|
||||
|
||||
Body: {
|
||||
"device_id": "android-xyz",
|
||||
"seq": 1,
|
||||
"cmd": "0105",
|
||||
"raw": "41 05 5C",
|
||||
"prompt": true,
|
||||
"elapsed_ms": 48,
|
||||
"bytes": 8,
|
||||
"error": null
|
||||
}
|
||||
"""
|
||||
global _last_response, _history
|
||||
data = request.get_json(silent=True)
|
||||
if not data:
|
||||
return jsonify({"error": "empty body"}), 400
|
||||
|
||||
with _lock:
|
||||
_last_response = {
|
||||
"seq": data.get("seq", 0),
|
||||
"cmd": data.get("cmd", ""),
|
||||
"raw": data.get("raw", ""),
|
||||
"prompt": data.get("prompt", False),
|
||||
"elapsed_ms": data.get("elapsed_ms", 0),
|
||||
"bytes": data.get("bytes", 0),
|
||||
"error": data.get("error"),
|
||||
"received_at": time.time(),
|
||||
}
|
||||
_history.append(dict(_last_response))
|
||||
if len(_history) > 1000:
|
||||
_history = _history[-500:]
|
||||
|
||||
logger.info(f"RawELM: response #{_last_response['seq']} ← {_last_response['raw'][:80]}")
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/response", methods=["GET"])
|
||||
def raw_get_response():
|
||||
"""Copilot: прочитать последний ответ от ELM327.
|
||||
|
||||
Query: ?wait=30 — ждать до 30 сек пока появится новый ответ
|
||||
"""
|
||||
global _last_response, _pending_cmd
|
||||
wait_s = int(request.args.get("wait", 0))
|
||||
seq = int(request.args.get("seq", 0))
|
||||
|
||||
if wait_s > 0:
|
||||
# Ждём пока появится ответ на команду с seq > указанного
|
||||
dl = time.time() + wait_s
|
||||
while time.time() < dl:
|
||||
with _lock:
|
||||
if _last_response and _last_response["seq"] > seq:
|
||||
return jsonify(_last_response)
|
||||
if _pending_cmd is None and _last_response:
|
||||
# команд в очереди нет, ответ уже есть
|
||||
return jsonify(_last_response)
|
||||
time.sleep(0.5)
|
||||
|
||||
with _lock:
|
||||
if _last_response is None:
|
||||
return jsonify({"error": "no response yet", "seq": 0})
|
||||
return jsonify(_last_response)
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/status", methods=["GET"])
|
||||
def raw_status():
|
||||
"""Copilot: статус Android-устройства."""
|
||||
with _lock:
|
||||
return jsonify({
|
||||
"device_ready": _device_ready,
|
||||
"device_info": _device_info,
|
||||
"pending_cmd": bool(_pending_cmd),
|
||||
"pending_seq": _pending_seq,
|
||||
"last_response_seq": _last_response["seq"] if _last_response else 0,
|
||||
"history_count": len(_history),
|
||||
})
|
||||
|
||||
|
||||
@bp.route("/api/v1/elm/raw/history", methods=["GET"])
|
||||
def raw_history():
|
||||
"""Copilot: история всех команд через Android."""
|
||||
n = int(request.args.get("n", 50))
|
||||
with _lock:
|
||||
return jsonify({"history": _history[-n:], "total": len(_history)})
|
||||
|
||||
+74
-1
@@ -16,7 +16,7 @@ from flask import jsonify, request
|
||||
from api.config import load
|
||||
from api.db import Database
|
||||
from api.parser import format_no_llm, parse_batch
|
||||
from api.scripts import build_default_script, build_full_script, build_script_for_level, build_dynamic_script
|
||||
from api.scripts import build_default_script, build_full_script, build_script_for_level, build_dynamic_script, build_test_script
|
||||
from brain.client import Diagnoser, LLMError
|
||||
from brain.prompts import SYSTEM_PROMPT, DYNAMIC_PROMPT
|
||||
|
||||
@@ -93,6 +93,12 @@ def register(app):
|
||||
script = build_default_script()
|
||||
elif mode == "dynamic":
|
||||
script = build_dynamic_script()
|
||||
elif mode == "test":
|
||||
wait = int(request.args.get("wait", 2000))
|
||||
pid_str = request.args.get("pids", "")
|
||||
pids = pid_str.split(",") if pid_str else None
|
||||
repeat = int(request.args.get("repeat", 8))
|
||||
script = build_test_script(wait_ms=wait, pids=pids, repeat=repeat)
|
||||
elif mode == "full":
|
||||
script = build_full_script()
|
||||
else:
|
||||
@@ -241,6 +247,24 @@ def register(app):
|
||||
return jsonify({"answer": answer})
|
||||
|
||||
|
||||
@app.route("/api/v1/sessions", methods=["GET"])
|
||||
def get_sessions():
|
||||
"""История сессий для мобильного приложения."""
|
||||
if not _check_api_key():
|
||||
return _auth_error()
|
||||
with Database() as db:
|
||||
rows = db.conn.execute(
|
||||
"SELECT id, vin, car_info, created_at, diagnosis_text as diagnosis FROM sessions ORDER BY id DESC LIMIT 50"
|
||||
).fetchall()
|
||||
return jsonify([{
|
||||
"id": r["id"],
|
||||
"title": (r["vin"] or r["car_info"] or "Диагностика"),
|
||||
"created_at": r["created_at"],
|
||||
"uploaded": 1,
|
||||
"diagnosis": r["diagnosis"] or ""
|
||||
} for r in rows])
|
||||
|
||||
|
||||
@app.route("/api/v1/elm/probe", methods=["POST"])
|
||||
def probe_elm():
|
||||
"""Пробинг ELM327: определение уровня устройства.
|
||||
@@ -298,6 +322,55 @@ def register(app):
|
||||
return jsonify(p)
|
||||
|
||||
|
||||
@app.route("/api/v1/elm/profile/<mac>", methods=["PUT"])
|
||||
def update_elm_profile(mac: str):
|
||||
"""Обновляет поля профиля (response_time_ms и т.д.). Если профиля нет — создаёт."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
with Database() as db:
|
||||
p = db.get_device_profile(mac)
|
||||
if p is None:
|
||||
p = {"mac": mac, "level": 0, "supported": [], "unsupported": [], "errors": []}
|
||||
p.update(data)
|
||||
_save_profile(mac, p)
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@app.route("/api/v1/test/next", methods=["POST"])
|
||||
def test_next():
|
||||
"""Авто-подбор параметров теста. Принимает результаты, возвращает следующий скрипт или done."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
results = data.get("results", [])
|
||||
run = data.get("run", 0)
|
||||
|
||||
# Анализ результатов
|
||||
total = len(results)
|
||||
if total == 0:
|
||||
return jsonify({"done": True, "message": "Нет данных", "script": None})
|
||||
|
||||
ok_count = sum(1 for r in results if r.get("raw", "").startswith("41"))
|
||||
err_pct = (total - ok_count) * 100 // total if total > 0 else 100
|
||||
wait_ms = int(request.args.get("wait", data.get("wait_ms", 2000)))
|
||||
|
||||
max_runs = 6
|
||||
if err_pct < 20 or run >= max_runs:
|
||||
return jsonify({
|
||||
"done": True,
|
||||
"message": f"✅ Стабильно: {ok_count}/{total} ({err_pct}% ошибок) на wait={wait_ms}ms",
|
||||
"script": None,
|
||||
"final_wait_ms": wait_ms,
|
||||
})
|
||||
|
||||
# Увеличиваем паузу
|
||||
new_wait = wait_ms + 500
|
||||
return jsonify({
|
||||
"done": False,
|
||||
"message": f"⚠️ {err_pct}% ошибок — увеличиваю паузу до {new_wait}ms",
|
||||
"run": run + 1,
|
||||
"wait_ms": new_wait,
|
||||
"script": build_test_script(wait_ms=new_wait, pids=["010C", "0106"], repeat=6),
|
||||
})
|
||||
|
||||
|
||||
def _save_profile(mac: str, profile: dict):
|
||||
"""Сохраняет профиль в БД (best-effort)."""
|
||||
try:
|
||||
|
||||
@@ -131,3 +131,42 @@ def build_dynamic_script() -> dict:
|
||||
{"id": "pid_1F", "cmd": "011F", "desc": "Время работы"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def build_test_script(wait_ms: int = 1500, pids: list[str] | None = None, repeat: int = 8) -> dict:
|
||||
"""Тестовый скрипт для отладки таймингов ELM327.
|
||||
|
||||
Сервер управляет таймингами — можно менять wait_ms/pids/repeat без передеплоя APK.
|
||||
|
||||
Args:
|
||||
wait_ms: пауза ПЕРЕД каждой OBD-командой (ms)
|
||||
pids: список PID для опроса (по умолчанию 010C,0110,0106)
|
||||
repeat: сколько раз повторить цикл
|
||||
"""
|
||||
if pids is None:
|
||||
pids = ["010C", "0106"] # RPM + STFT — минимум для проверки связи
|
||||
|
||||
pid_names = {"010C": "RPM", "0110": "MAF", "0106": "STFT", "0105": "ОЖ",
|
||||
"0104": "Нагрузка", "0107": "LTFT", "0111": "Дроссель",
|
||||
"010D": "Скорость", "010B": "MAP", "010F": "IAT"}
|
||||
|
||||
steps = []
|
||||
# Статика — один проход по всем PID для калибровки
|
||||
for pid in pids:
|
||||
name = pid_names.get(pid, pid)
|
||||
steps.append({"id": f"static_{pid}", "cmd": pid, "desc": f"{name} (статик)", "wait": 0})
|
||||
|
||||
# Динамика — repeat циклов
|
||||
for cycle in range(repeat):
|
||||
for pid in pids:
|
||||
name = pid_names.get(pid, pid)
|
||||
steps.append({"id": f"dyn{cycle}_{pid}", "cmd": pid, "desc": f"{name}", "wait": wait_ms})
|
||||
|
||||
return {
|
||||
"version": 1,
|
||||
"mode": "test",
|
||||
"title": f"Тест: {len(pids)} PID × {repeat}, пауза {wait_ms}ms",
|
||||
"wait_ms": wait_ms,
|
||||
"repeat": repeat,
|
||||
"steps": steps,
|
||||
}
|
||||
|
||||
+75
-49
@@ -1,65 +1,91 @@
|
||||
# Отчёт об аудите (07.06.2026)
|
||||
# Отчёт об аудите безопасности и багах (07.06.2026)
|
||||
|
||||
## Найдено
|
||||
## 🔴 КРИТИЧЕСКИЕ (7)
|
||||
|
||||
### 🔴 Критичные
|
||||
### 1. Жестко заданный API ключ в конфигурации
|
||||
- **Файл:** [config.yaml](config.yaml#L5)
|
||||
- **Описание:** \`api_key: "sk-78ec529c1eba4ba69995091046c9fa33"\` — настоящий ключ DeepSeek находится непосредственно в репозитории.
|
||||
- **Влияние:** Экспозиция платного LLM, финансовый ущерб, возможность несанкционированного использования лимитов.
|
||||
|
||||
1. **Краш при отсутствии Bluetooth**
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/ui/MainActivity.kt](android/app/src/main/java/ru/elmer/client/ui/MainActivity.kt)
|
||||
- **Строки:** 155, 230, 310
|
||||
- **Описание:** Используется оператор `!!` для `btAdapter`. На устройствах без Bluetooth (или в эмуляторе) приложение упадёт при попытке проверить прибор или запустить сканирование.
|
||||
- **Как исправить:** Добавить проверку `if (btAdapter == null)` перед использованием и выводить сообщение об ошибке.
|
||||
### 2. check_same_thread=False в SQLite
|
||||
- **Файл:** [api/db.py](api/db.py#L20)
|
||||
- **Описание:** Использование \`check_same_thread=False\` без механизмов синхронизации в многопоточном Flask-приложении.
|
||||
- **Влияние:** Состояние гонки (Race conditions), повреждение базы данных при одновременной записи.
|
||||
|
||||
2. **Отсутствие аутентификации на сервере**
|
||||
- **Файл:** [api/routes.py](api/routes.py)
|
||||
- **Описание:** Эндпоинты `/api/v1/session/upload`, `/api/v1/chat` и `/api/v1/ping-llm` принимают запросы без проверки API-ключа. Клиент передаёт `X-Api-Key`, но сервер его игнорирует. Любой может отправлять запросы и тратить токены LLM.
|
||||
- **Как исправить:** Добавить декоратор `@api_key_required` или проверку заголовка в `before_request`.
|
||||
### 3. /api/v1/ping-llm без аутентификации тратит токены
|
||||
- **Файлы:** [api/ping.py](api/ping.py#L40-45), [web/script_endpoint.py](web/script_endpoint.py#L215-219)
|
||||
- **Описание:** Эндпоинт доступен без заголовка \`X-Api-Key\` и выполняет реальный запрос к LLM.
|
||||
- **Влияние:** Возможность DoS-атаки на кошелек API через бесконечные пинги.
|
||||
|
||||
3. **Состязание потоков (Race Condition) в ScriptRunnerService**
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/script/ScriptRunnerService.kt](android/app/src/main/java/ru/elmer/client/script/ScriptRunnerService.kt)
|
||||
- **Описание:** `onStartCommand` не проверяет, запущен ли уже процесс. Если дважды вызвать `startForegroundService` (нажав кнопку несколько раз), создадутся два конкурирующих потока `ScriptRunner`, которые будут одновременно работать с одним и тем же Bluetooth-сокетом.
|
||||
- **Как исправить:** В `startRun` проверять флаг `running` и игнорировать повторные запуски.
|
||||
### 4. Краш при отсутствии Bluetooth (Android)
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/ui/MainActivity.kt](android/app/src/main/java/ru/elmer/client/ui/MainActivity.kt)
|
||||
- **Описание:** Используется оператор \`!!\` для \`btAdapter\`. На устройствах без Bluetooth приложение упадёт.
|
||||
- **Влияние:** Нестабильность приложения на эмуляторах и старых устройствах.
|
||||
|
||||
4. **Логическая ошибка в выборе Bluetooth-устройства**
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/ui/MainActivity.kt](android/app/src/main/java/ru/elmer/client/ui/MainActivity.kt#L457)
|
||||
- **Описание:** Функция `findElmDevice()` при наличии двух и более устройств показывает диалог, но возвращает `null` немедленно. Стейт-машина (`checkElm`, `scanDtc`) видит `null` и прерывает работу с ошибкой «ELM не найден».
|
||||
- **Как исправить:** Перестроить логику: диалог выбора должен вызываться отдельно, сохранять `elmDevice`, и только потом запускать операции.
|
||||
### 5. Отсутствие аутентификации на критичных эндпоинтах
|
||||
- **Файл:** [api/routes.py](api/routes.py#L245), [api/routes.py](api/routes.py#L292)
|
||||
- **Описание:** Эндпоинты \`POST /api/v1/elm/probe\` и \`GET /api/v1/elm/profile/<mac>\` не защищены API-ключом.
|
||||
- **Влияние:** Идентификация структуры OBD-профилей любых пользователей.
|
||||
|
||||
### 🟡 Средние
|
||||
### 6. Дублирование API с разной логикой
|
||||
- **Файлы:** [web/script_endpoint.py](web/script_endpoint.py) vs [api/routes.py](api/routes.py)
|
||||
- **Описание:** Маршрут \`/api/v1/session/upload\` реализован дважды. В \`web/\` версии отсутствует проверка идемпотентности (\`request_id\`).
|
||||
- **Влияние:** Неконсистентное поведение, дублирование LLM-запросов при ретраях из мобильного приложения.
|
||||
|
||||
5. **Утечка памяти в ElmChecker**
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/elm/ElmChecker.kt](android/app/src/main/java/ru/elmer/client/elm/ElmChecker.kt)
|
||||
- **Описание:** Список `logLines` является членом класса. В `MainActivity` экземпляр `elmChecker` переиспользуется. Приложение копит логи всех операций в памяти до своей гибели.
|
||||
- **Как исправить:** Очищать `logLines` в начале каждой операции или переносить лог в локальную переменную метода `run()`.
|
||||
### 7. Состязание потоков в ScriptRunnerService (Android)
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/script/ScriptRunnerService.kt](android/app/src/main/java/ru/elmer/client/script/ScriptRunnerService.kt)
|
||||
- **Описание:** Повторный запуск сервиса создает новый поток \`ScriptRunner\`, конкурирующий за Bluetooth-сокет.
|
||||
|
||||
6. **Утечка курсоров в БД**
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/db/SessionDb.kt](android/app/src/main/java/ru/elmer/client/db/SessionDb.kt)
|
||||
- **Описание:** Методы `getResponses`, `getSessions`, `getPendingSessions` вызывают `cursor.close()` в конце цикла, но не в `finally`. При ошибке чтения курсор останется открытым.
|
||||
- **Как исправить:** Использовать конструкцию `.use { ... }` (в Kotlin для `Cursor` доступно начиная с определенных версий) или `try { ... } finally { cursor.close() }`.
|
||||
---
|
||||
|
||||
7. **Не включены Foreign Keys**
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/db/SessionDb.kt](android/app/src/main/java/ru/elmer/client/db/SessionDb.kt)
|
||||
- **Описание:** Несмотря на наличие `REFERENCES sessions(id)`, SQLite в Android по умолчанию не проверяет целостность связей.
|
||||
- **Как исправить:** Добавить `db.setForeignKeyConstraintsEnabled(true)` в `onConfigure`.
|
||||
## 🟡 ВАЖНЫЕ (10)
|
||||
|
||||
8. **Слепой выбор устройства в сервисе**
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/script/ScriptRunnerService.kt](android/app/src/main/java/ru/elmer/client/script/ScriptRunnerService.kt#L143)
|
||||
- **Описание:** Сервис берёт `bonded[0]` — первое попавшееся сопряжённое устройство. Это могут быть наушники или магнитола.
|
||||
- **Как исправить:** Передавать MAC-адрес выбранного ELM через `Intent`.
|
||||
### 8. Database.close() не гарантирован в web/
|
||||
- **Файл:** [web/script_endpoint.py](web/script_endpoint.py#L117-120)
|
||||
- **Описание:** Соединение с БД открывается, но не закрывается в блоке \`finally\`.
|
||||
- **Влияние:** Утечка дескрипторов файлов и соединений SQLite.
|
||||
|
||||
9. **Отсутствие лимита на размер запроса**
|
||||
- **Файл:** [api/routes.py](api/routes.py)
|
||||
- **Описание:** Сервер принимает список `responses` любого размера. Злоумышленник может отправить миллион строк, вызвав OOM или переполнение диска логами.
|
||||
- **Как исправить:** Проверять `len(responses)` перед обработкой.
|
||||
### 9. Отсутствие checkpoint для WAL в SQLite
|
||||
- **Файл:** [api/db.py](api/db.py#L22)
|
||||
- **Описание:** Режим WAL включен, но \`wal_checkpoint\` никогда не вызывается явно. Журналы могут расти бесконечно.
|
||||
|
||||
### 🟢 Косметика
|
||||
### 10. Утечка курсоров в БД (Android)
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/db/SessionDb.kt](android/app/src/main/java/ru/elmer/client/db/SessionDb.kt)
|
||||
- **Описание:** Курсоры закрываются только в конце успешных циклов, а не в \`finally\`.
|
||||
|
||||
10. **Неиспользуемые переменные**
|
||||
- В `ElmProtocol.kt` константа `INIT_TIMEOUT` и другие не используются.
|
||||
- В `MainActivity.kt` список `chatHistory` хранится в памяти, но не восстанавливается после `onSaveInstanceState`.
|
||||
### 11. Не включены Foreign Keys (Android)
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/db/SessionDb.kt](android/app/src/main/java/ru/elmer/client/db/SessionDb.kt)
|
||||
- **Описание:** SQLite игнорирует \`REFERENCES\` без явной команды \`PRAGMA foreign_keys = ON\`.
|
||||
|
||||
11. **Устаревший API**
|
||||
- `BluetoothAdapter.getDefaultAdapter()` помечен как Deprecated. В современных Android рекомендуется использовать `BluetoothManager`.
|
||||
### 12. Раскрытие sensitive info в ошибках
|
||||
- **Файлы:** [web/script_endpoint.py](web/script_endpoint.py#L127), [api/ping.py](api/ping.py#L48)
|
||||
- **Описание:** \`str(e)\` пробрасывается клиенту, может содержать детали API или токены.
|
||||
|
||||
12. **Бесполезный пинг LLM**
|
||||
- Эндпоинт `/api/v1/ping-llm` делает реальный `diagnose`, что стоит денег (токенов). Кэш есть, но при перезапуске сервера или по таймауту он всё равно будет жечь токены на "пустые" проверки.
|
||||
### 13. Нет лимита на размер payload
|
||||
- **Описание:** Сервер принимает JSON любого объема, что ведет к OOM (Out Of Memory).
|
||||
|
||||
### 14. Нет rate-limiting
|
||||
- **Описание:** Отсутствует защита от перебора ключей и спама запросами.
|
||||
|
||||
### 15. Отсутствие CORS ограничений
|
||||
- **Файл:** [web/app.py](web/app.py#L48)
|
||||
- **Описание:** Flask слушает на \`0.0.0.0\`, разрешая запросы с любых источников.
|
||||
|
||||
### 16. Уязвимость потокобезопасности AndrOBD
|
||||
- **Файл:** [obd/protocol.py](obd/protocol.py#L114-121)
|
||||
- **Описание:** Метод \`send()\` не синхронизирован, состояние протокола может быть повреждено при параллельном доступе.
|
||||
|
||||
### 17. Слепой выбор Bluetooth-устройства в сервисе (Android)
|
||||
- **Файл:** [android/app/src/main/java/ru/elmer/client/script/ScriptRunnerService.kt](android/app/src/main/java/ru/elmer/client/script/ScriptRunnerService.kt#L143)
|
||||
- **Описание:** Берется первое сопряженное устройство (\`bonded[0]\`), что часто ошибочно.
|
||||
|
||||
---
|
||||
|
||||
## 📋 ЗАМЕЧАНИЯ ПО АРХИТЕКТУРЕ
|
||||
- **Dynamic Imports:** В \`web/script_endpoint.py\` импорты используют \`elmer.*\`, что может конфликтовать с установленными пакетами.
|
||||
- **Git Hygiene:** Файл \`config.yaml\` содержит секреты и должен быть добавлен в \`.gitignore\` с предоставлением \`config.yaml.example\`.
|
||||
- **Логирование:** Недостаточно информации для трассировки багов пользователя (отсутствуют IP и User-Agent в логах сессий).
|
||||
|
||||
---
|
||||
*Дата аудита: 07.06.2026*
|
||||
*Инструмент: GitHub Copilot (Gemini 3 Flash)*
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# Анализ: ELM327 динамический тест
|
||||
|
||||
## 1. exec() — retry с повторной write(cmd) — ГЛАВНЫЙ БАГ
|
||||
|
||||
При таймауте ELM уже отправил запрос в CAN-шину и ждёт ответа от ЭБУ. write(cmd) снова вызывает drainInput() — сбрасывает буфер с ответом, которого мы ждём — и шлёт команду повторно. ELM получает 010C пока обрабатывает предыдущий 010C → BUFFER FULL / зависание. 10 retry = 10 одновременных CAN-запросов. Статика не задевает этот путь, потому что там таймауты не случаются (пауза между командами — секунды).
|
||||
|
||||
## 2. Почему v1.9.0 (без drainInput) стало хуже
|
||||
|
||||
drainInput() в write() — единственный механизм синхронизации запрос/ответ. Без него:
|
||||
|
||||
- Ответ на команду N читается как ответ на команду N+1
|
||||
- read() видит > из старого ответа — возвращает мусор, считает успехом
|
||||
- К 3-му PID цикла батча сдвиг накопился: ответы не совпадают с командами
|
||||
- BT-буфер на стороне ELM забивается необработанными данными → ELM перестаёт отвечать
|
||||
|
||||
В v1.3.0 drainInput() маскировал проблему retry: хотя бы буфер чистился перед каждой командой.
|
||||
|
||||
## 3. ATWS — нужен ли, сколько ждать
|
||||
|
||||
Нужен: сбрасывает SEARCHING..., очищает внутренние ошибки CAN-протокола ELM.
|
||||
|
||||
Проблемы текущего использования:
|
||||
- Пауза 800 мс — мало. CAN-шина после warm start поднимается 700–1000 мс, плюс ATSP0 negotiate. Нужно 1200–1500 мс.
|
||||
- После ATWS ELM сбрасывает настройки в дефолт: ATE1 (эхо ON), ATL1 (LF ON), ATS1 (пробелы ON). Код не восстанавливает ATE0/ATL0/ATS0 → read() начинает видеть эхо команды и переносы строк → парсинг ломается.
|
||||
|
||||
## 4. sleep(350) между PID — правильно?
|
||||
|
||||
Для ELM327 v1.5 — приемлемо. Адаптер не успевает переключаться быстрее 100–200 мс между разными PID (CAN frame turnaround). Но 350 мс не решает проблему, потому что рассинхрон возникает раньше — внутри retry в exec(). Пауза между командами маскирует, но не лечит.
|
||||
|
||||
## 5. Почему статика работает, динамика нет
|
||||
|
||||
Статика: пауза между командами — секунды (UI-обработка). ELM успевает ответить. Retry не срабатывает. Накопления сдвига нет.
|
||||
|
||||
Динамика: пауза 350–500 мс. При первом таймауте retry запускает цепочку дублей. Синхронизация батча ломается. Следующий батч начинается на сломанном состоянии.
|
||||
|
||||
## Итог: приоритет причин
|
||||
|
||||
1. exec() повторяет write(cmd) при таймауте — нельзя дублировать OBD-команды в CAN (первична)
|
||||
2. Убрали drainInput() в write() — потеряна синхронизация запрос/ответ
|
||||
3. После ATWS не восстанавливают ATE0/ATL0/ATS0 — парсинг ответов ломается
|
||||
@@ -0,0 +1,43 @@
|
||||
# Анализ причин отказа ELM327 v1.5 при динамическом опросе
|
||||
|
||||
Анализ кода `ElmProtocol.kt`, `DynamicCollector.kt` и `ElmChecker.kt` выявил ряд критических проблем, которые в совокупности приводят к "зависанию" адаптера ELM327 (особенно дешевых клонов v1.5) при переходе к быстрому циклу опроса.
|
||||
|
||||
## Ответы на вопросы
|
||||
|
||||
### 1. Почему ELM327 v1.5 замолкает после первых 2 ответов?
|
||||
Основная причина — **десинхронизация и переполнение буфера**.
|
||||
* **ATWS прямо перед циклом:** Команда `ATWS` (Warm Start) сбрасывает микроконтроллер. Ему требуется время на инициализацию (обычно 500-1000 мс). Код в `MainActivity` ждет всего 300 мс. Первые команды `010C` прилетают, когда ELM еще "просыпается" или находится в неопределенном состоянии.
|
||||
* **Эффект домино в `exec()`:** Если первый PID в цикле (`010C`) не успел ответить вовремя, `exec` возвращает пустую строку, но ELM продолжает обработку. Следующий вызов `sendCommand` через `write()` делает `drainInput()`, удаляя запоздавший ответ, и посылает новую команду. Для клона v1.5 типична ситуация, когда он "захлебывается", если получает новую команду, не закончив передачу предыдущего ответа или символа `>`.
|
||||
|
||||
### 2. Может ли `drainInput()` в `write()` съедать ответ?
|
||||
**Да, и это главная проблема надежности.**
|
||||
Если ELM327 ответил на 50 мс позже таймаута, данные уже лежат в буфере Bluetooth-сокета. Вызов `write()` для следующей команды в цикле безусловно их очищает. В итоге `read()` следующей команды видит пустоту, провоцируя новые таймауты и ретраи. Происходит рассинхрон: приложение ждет ответ на команду B, а ELM (если не завис) шлет ответ на команду A.
|
||||
|
||||
### 3. Критична ли последовательность: static -> speed-test -> ATWS -> dynamic?
|
||||
Последовательность перегружена сбросами.
|
||||
* `ATWS` сбрасывает настройки `ATAT1`, `ATSP`, `ATL0` и т.д., которые были установлены в `init()`.
|
||||
* После `ATWS` протокол может вернуться к `AUTO` (`ATSP0`), что заставляет ELM тратить время на "SEARCHING..." при первом же запросе `010C`. Это гарантированный таймаут в динамическом тесте.
|
||||
|
||||
### 4. Нужно ли переподключать ELM вместо ATWS?
|
||||
Переподключать Bluetooth-сокет не обязательно, но **вместо `ATWS` лучше вызвать серию настроечных команд**, гарантирующих состояние:
|
||||
1. `ATE0` (эхо выкл)
|
||||
2. `ATL0` (переносы строк выкл)
|
||||
3. `ATS0` (пробелы выкл) — крайне важно для скорости и предотвращения переполнения буфера.
|
||||
4. `ATSP X` (принудительная установка протокола, найденного в `checkDevice`), чтобы исключить стадию поиска.
|
||||
|
||||
### 5. Как правильно реализовать динамический опрос для v1.5?
|
||||
Для минимизации ошибок на медленных адаптерах:
|
||||
1. **Убрать `Thread.sleep(350)` внутри цикла `for (step in steps)`.** Пауза должна быть только между *пакетами* (батчами) PID, если нужно ограничить частоту. Внутри батча команды должны идти максимально плотно: послал -> дождался `>` -> сразу следующий.
|
||||
2. **Увеличить таймаут для v1.5.** 500 мс — это предел для v1.5. Первичный запрос (особенно после сброса) может занимать до 1500 мс.
|
||||
3. **Оптимизировать `read()`:** v1.5 очень чувствителен к таймингам. Текущий `Thread.sleep(1)` в `read()` — это хорошо, но логика `drainInput` должна быть перемещена: чистить буфер нужно только один раз *перед стартом всего динамического теста*, а не перед каждой командой.
|
||||
|
||||
## Рекомендации по исправлению
|
||||
|
||||
1. **В `ElmProtocol.kt`:**
|
||||
* Сделать `drainInput()` опциональным параметром в `write()` или убрать его из `sendCommand` по умолчанию.
|
||||
* В `handle()` при получении `NODATA` или `ERROR` не делать `ATWS` мгновенно, так как это убивает сессию опроса.
|
||||
2. **В `DynamicCollector.kt`:**
|
||||
* Удалить `Thread.sleep(350)` в цикле `for`. Вместо этого полагаться на таймауты `ElmProtocol`.
|
||||
3. **В `MainActivity.kt`:**
|
||||
* Убрать `ATWS` перед стартом. Если нужен сброс — использовать `ATZ` и ждать 2 секунды, после чего заново прогнать весь `init()`.
|
||||
* Перед запуском `DynamicCollector` зафиксировать протокол: `elmProto.sendCommand("ATSP" + currentProtocol)`.
|
||||
@@ -0,0 +1,277 @@
|
||||
# Запрос к Claude Sonnet — ТОЛЬКО АНАЛИЗ
|
||||
|
||||
## ⛔ ЗАПРЕЩЕНО МЕНЯТЬ КОД ⛔
|
||||
## ⛔ НЕ ДЕЛАТЬ КОММИТЫ ⛔
|
||||
## ⛔ НЕ ПРАВИТЬ ФАЙЛЫ ⛔
|
||||
## ⛔ ТОЛЬКО АНАЛИЗ — вывод в файл `doc/claude-analysis-elm-v2.md` ⛔
|
||||
|
||||
Ты — эксперт по ELM327 и OBD2. Тебе дан код Android-приложения (Kotlin). НАЙДИ БАГИ, ОБЪЯСНИ, ДАЙ РЕКОМЕНДАЦИИ. Код не менять.
|
||||
|
||||
---
|
||||
|
||||
## Проблема
|
||||
|
||||
Динамический тест: опрос 3 PID (010C RPM, 0110 MAF, 0106 STFT) в цикле. ELM327 v1.5 замолкает.
|
||||
|
||||
### Реальные данные с машины
|
||||
|
||||
**v1.3.0-dev** (drainInput в каждой write, ATWS+300ms):
|
||||
```
|
||||
0106: 1/18 ok 010C: 1/18 ok 0110: 0/18 ok
|
||||
Первые 2 ответа — данные, дальше 16 пустых.
|
||||
```
|
||||
|
||||
**v1.9.0-dev** (drainInput отключён, без ATWS):
|
||||
```
|
||||
0106: 0/15 ok 010C: 0/15 ok 0110: 0/15 ok ← СТАЛО ХУЖЕ
|
||||
ВСЕ 15 пустые.
|
||||
```
|
||||
|
||||
**Статическая диагностика** — одиночные PID — работает идеально.
|
||||
|
||||
---
|
||||
|
||||
## Код
|
||||
|
||||
Все файлы в `android/app/src/main/java/ru/elmer/client/`.
|
||||
|
||||
### 1. ElmProtocol.kt (elm/ElmProtocol.kt) — Стейт-машина AndrOBD
|
||||
|
||||
```kotlin
|
||||
package ru.elmer.client.elm
|
||||
|
||||
import android.util.Log
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
class ElmProtocol(
|
||||
private val input: InputStream,
|
||||
private val output: OutputStream
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "ElmProto"
|
||||
private const val POLL_DELAY = 1L
|
||||
private const val INIT_TIMEOUT = 10000L
|
||||
private const val DEF_TIMEOUT = 500L
|
||||
private const val TIMEOUT_MIN = 50L
|
||||
private const val TIMEOUT_MAX = 2000L
|
||||
private const val TIMEOUT_STEP = 20L
|
||||
private const val TIMEOUT_RES = 4
|
||||
private const val MAX_RETRIES = 10
|
||||
}
|
||||
|
||||
private enum class State { UNDEFINED, INITIALIZING, READY, BUSY, ERROR, DISCONNECTED }
|
||||
private var state = State.UNDEFINED
|
||||
private var timeoutMs = DEF_TIMEOUT
|
||||
private var learnedMin = TIMEOUT_MIN
|
||||
|
||||
fun init() {
|
||||
state = State.INITIALIZING
|
||||
write("ATSP0"); tryRead(4000); drainInput()
|
||||
write("ATAT1"); tryRead(2000); drainInput()
|
||||
updateAtst()
|
||||
write("ATS0"); tryRead(2000); drainInput()
|
||||
write("ATL0"); tryRead(2000); drainInput()
|
||||
write("ATE0"); tryRead(2000); drainInput()
|
||||
state = State.READY
|
||||
}
|
||||
|
||||
fun sendCommand(cmd: String): String {
|
||||
if (state == State.ERROR || state == State.DISCONNECTED) recover()
|
||||
state = State.BUSY
|
||||
val result = exec(cmd, timeoutMs)
|
||||
if (state == State.BUSY) state = State.READY
|
||||
return result
|
||||
}
|
||||
|
||||
private fun exec(cmd: String, timeout: Long): String {
|
||||
write(cmd)
|
||||
var t = timeout
|
||||
for (i in 0 until MAX_RETRIES) {
|
||||
try {
|
||||
return handle(read(t))
|
||||
} catch (_: TimeoutException) {
|
||||
if (state == State.INITIALIZING) t += 1000
|
||||
else { increaseTimeout(); t = timeoutMs }
|
||||
}
|
||||
}
|
||||
state = State.ERROR
|
||||
return ""
|
||||
}
|
||||
|
||||
private fun handle(raw: String): String {
|
||||
val u = raw.uppercase().trim()
|
||||
when {
|
||||
u.startsWith("SEARCHING") -> {}
|
||||
u.startsWith("OK") -> decreaseTimeout()
|
||||
u.startsWith("NODATA") || u.startsWith("NO DATA") -> { increaseTimeout(); updateAtst() }
|
||||
isBusError(u) -> {
|
||||
state = State.DISCONNECTED; resetTimeout(); updateAtst()
|
||||
write("ATPC"); tryRead(3000); write("ATSP0"); tryRead(3000)
|
||||
}
|
||||
u.startsWith("ERROR") && !u.startsWith("DATA ERROR") -> { state = State.ERROR; write("ATWS"); tryRead(3000) }
|
||||
isDataError(u) -> { state = State.ERROR; write("ATWS"); tryRead(3000) }
|
||||
else -> decreaseTimeout()
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
private fun recover() {
|
||||
state = State.INITIALIZING
|
||||
write("ATWS"); tryRead(2000); drainInput()
|
||||
write("ATSP0"); tryRead(2000); drainInput()
|
||||
write("ATE0"); tryRead(2000); drainInput()
|
||||
state = State.READY
|
||||
}
|
||||
|
||||
private fun write(cmd: String) {
|
||||
drainInput()
|
||||
output.write((cmd + "\r").toByteArray())
|
||||
output.flush()
|
||||
}
|
||||
|
||||
private fun drainInput() {
|
||||
while (input.available() > 0) input.read()
|
||||
}
|
||||
|
||||
@Throws(TimeoutException::class)
|
||||
private fun read(timeout: Long): String {
|
||||
val dl = System.currentTimeMillis() + timeout
|
||||
val sb = StringBuilder()
|
||||
val lines = mutableListOf<String>()
|
||||
var gotPrompt = false
|
||||
while (System.currentTimeMillis() < dl) {
|
||||
if (input.available() > 0) {
|
||||
val b = input.read()
|
||||
if (b == -1) break
|
||||
when (b) {
|
||||
62 -> { push(sb, lines); gotPrompt = true; break }
|
||||
13 -> push(sb, lines)
|
||||
10, 32 -> {}
|
||||
else -> sb.append(b.toChar())
|
||||
}
|
||||
} else { Thread.sleep(POLL_DELAY) }
|
||||
}
|
||||
push(sb, lines)
|
||||
if (!gotPrompt) throw TimeoutException("timeout ${timeout}ms")
|
||||
return lines.joinToString("\n")
|
||||
}
|
||||
|
||||
private fun tryRead(timeout: Long) { try { read(timeout) } catch (_: TimeoutException) {} }
|
||||
private fun push(sb: StringBuilder, lines: MutableList<String>) {
|
||||
if (sb.isNotEmpty()) { lines.add(sb.toString()); sb.clear() }
|
||||
}
|
||||
private fun increaseTimeout() { if (timeoutMs + TIMEOUT_STEP < TIMEOUT_MAX) timeoutMs += TIMEOUT_STEP }
|
||||
private fun decreaseTimeout() { if (timeoutMs - TIMEOUT_STEP >= learnedMin) timeoutMs -= TIMEOUT_STEP }
|
||||
private fun resetTimeout() { timeoutMs = DEF_TIMEOUT }
|
||||
fun resetAdaptiveTiming() { timeoutMs = DEF_TIMEOUT }
|
||||
private fun updateAtst() {
|
||||
val v = (timeoutMs / TIMEOUT_RES).toInt().coerceAtLeast(1)
|
||||
write("ATST${v.toString(16).uppercase().padStart(2, '0')}")
|
||||
tryRead(2000); drainInput()
|
||||
}
|
||||
private fun isBusError(s: String) = listOf("UNABLE","BUS BUSY","BUS ERROR","CAN ERROR","BUS INIT","STOPPED").any { s.startsWith(it) }
|
||||
private fun isDataError(s: String) = listOf("DATA ERROR","BUFFER FULL","RX ERROR").any { s.startsWith(it) }
|
||||
}
|
||||
|
||||
class TimeoutException(message: String) : Exception(message)
|
||||
```
|
||||
|
||||
### 2. DynamicCollector.kt (script/DynamicCollector.kt)
|
||||
|
||||
```kotlin
|
||||
package ru.elmer.client.script
|
||||
|
||||
import ru.elmer.client.elm.ElmProtocol
|
||||
import ru.elmer.client.elm.ObdDecoder
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
class DynamicCollector(
|
||||
private val elm: ElmProtocol,
|
||||
private val steps: List<ElmStep>,
|
||||
private val intervalMs: Long,
|
||||
private val onSample: (sampleIndex: Int) -> Unit,
|
||||
private val onLog: (msg: String) -> Unit
|
||||
) {
|
||||
data class ElmStep(val id: String, val cmd: String, val desc: String)
|
||||
private val running = AtomicBoolean(false)
|
||||
private val samples = mutableListOf<List<SampleResponse>>()
|
||||
private var threadRef: Thread? = null
|
||||
|
||||
data class SampleResponse(val stepId: String, val cmd: String, val raw: String, val decoded: String, val ts: Long = 0)
|
||||
|
||||
fun start() {
|
||||
running.set(true)
|
||||
val startTs = System.currentTimeMillis()
|
||||
threadRef = thread(name = "DynamicCollector", isDaemon = true) {
|
||||
var idx = 0
|
||||
while (running.get()) {
|
||||
val t0 = System.currentTimeMillis()
|
||||
val batch = mutableListOf<SampleResponse>()
|
||||
for (step in steps) {
|
||||
if (!running.get()) break
|
||||
try {
|
||||
val raw = elm.sendCommand(step.cmd)
|
||||
val dec = ObdDecoder.decode(step.cmd, raw)
|
||||
batch.add(SampleResponse(step.id, step.cmd, raw, dec, System.currentTimeMillis() - startTs))
|
||||
} catch (e: Exception) {
|
||||
batch.add(SampleResponse(step.id, step.cmd, "(err)", e.message ?: "error", System.currentTimeMillis() - startTs))
|
||||
}
|
||||
Thread.sleep(350)
|
||||
}
|
||||
if (batch.isNotEmpty()) { synchronized(samples) { samples.add(batch) }; onSample(idx); idx++ }
|
||||
val elapsed = System.currentTimeMillis() - t0
|
||||
val sleep = intervalMs - elapsed
|
||||
if (sleep > 0 && running.get()) Thread.sleep(sleep)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop(): List<List<SampleResponse>> {
|
||||
running.set(false)
|
||||
try { threadRef?.join(3000) } catch (_: Exception) {}
|
||||
return synchronized(samples) { samples.toList() }
|
||||
}
|
||||
|
||||
fun isRunning(): Boolean = running.get()
|
||||
}
|
||||
```
|
||||
|
||||
### 3. MainActivity.kt — startDynamicRecording() (фрагмент)
|
||||
|
||||
```kotlin
|
||||
// v1.10.0-dev — текущая версия
|
||||
private fun startDynamicRecording() {
|
||||
thread(name = "DynamicTest", isDaemon = true) {
|
||||
checker.ensureConnected()
|
||||
val elmProto = checker.getElm()!!
|
||||
|
||||
// Статика — 9 PID по одному (работает)
|
||||
for ((pid, desc) in staticCmds) {
|
||||
elmProto.sendCommand("01$pid")
|
||||
}
|
||||
|
||||
// Подготовка к динамике
|
||||
try { elmProto.sendCommand("ATWS") } catch (_: Exception) {}
|
||||
Thread.sleep(800)
|
||||
|
||||
// Динамика: 3 PID, интервал 500ms
|
||||
val dynSteps = listOf("010C" to "RPM", "0110" to "MAF", "0106" to "STFT")
|
||||
.map { ElmStep(it.second, it.first, it.second) }
|
||||
DynamicCollector(elmProto, dynSteps, 500L, ...).start()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Вопросы
|
||||
|
||||
1. **exec()** делает retry с ПОВТОРНОЙ ОТПРАВКОЙ команды — не забивает ли это ELM327?
|
||||
2. **drainInput()** в write() — почему без него (v1.9.0) стало ХУЖЕ?
|
||||
3. **ATWS** — нужен ли? Сколько ждать?
|
||||
4. **sleep(350)** между PID — правильно или избыточно?
|
||||
5. Почему статика работает а динамика нет?
|
||||
|
||||
## ⛔ НАПОМИНАНИЕ: НЕ МЕНЯТЬ КОД, НЕ КОММИТИТЬ. ТОЛЬКО АНАЛИЗ В ФАЙЛ doc/claude-analysis-elm-v2.md ⛔
|
||||
@@ -0,0 +1,499 @@
|
||||
# Запрос анализа ELM327-кода — для Claude Sonnet
|
||||
|
||||
## Контекст
|
||||
|
||||
Android-приложение для OBD2-диагностики автомобиля через ELM327 Bluetooth-адаптер.
|
||||
Стек: Kotlin, minSdk 24, OkHttp 4.12.
|
||||
|
||||
**Проблема:** динамический тест (START/STOP) — опрос 3 PID (RPM, MAF, STFT) в реальном времени —
|
||||
даёт 94-100% пустых ответов. ELM327 v1.5 просто перестаёт отвечать.
|
||||
|
||||
Статическая диагностика (одиночные PID) работает нормально.
|
||||
|
||||
## Важно
|
||||
|
||||
АНАЛИЗИРУЙ ТОЛЬКО ELM-код. Не трогай UI, сервер, БД.
|
||||
Нужен анализ того, почему ELM327 замолкает при динамическом опросе.
|
||||
|
||||
## Файлы
|
||||
|
||||
Ниже полный код всех файлов, связанных с ELM327.
|
||||
|
||||
---
|
||||
|
||||
### 1. ElmProtocol.kt — стейт-машина AndrOBD (1:1 копия ElmProt.java)
|
||||
|
||||
```kotlin
|
||||
package ru.elmer.client.elm
|
||||
|
||||
import android.util.Log
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
class ElmProtocol(
|
||||
private val input: InputStream,
|
||||
private val output: OutputStream
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "ElmProto"
|
||||
private const val POLL_DELAY = 1L
|
||||
private const val INIT_TIMEOUT = 10000L
|
||||
private const val DEF_TIMEOUT = 500L
|
||||
private const val TIMEOUT_MIN = 50L
|
||||
private const val TIMEOUT_MAX = 2000L
|
||||
private const val TIMEOUT_STEP = 20L
|
||||
private const val TIMEOUT_RES = 4
|
||||
private const val MAX_RETRIES = 10
|
||||
}
|
||||
|
||||
private enum class State { UNDEFINED, INITIALIZING, READY, BUSY, ERROR, DISCONNECTED }
|
||||
private var state = State.UNDEFINED
|
||||
private var timeoutMs = DEF_TIMEOUT
|
||||
private var learnedMin = TIMEOUT_MIN
|
||||
|
||||
fun init() {
|
||||
Log.i(TAG, "init start")
|
||||
state = State.INITIALIZING
|
||||
write("ATSP0"); tryRead(4000); drainInput()
|
||||
write("ATAT1"); tryRead(2000); drainInput()
|
||||
updateAtst()
|
||||
write("ATS0"); tryRead(2000); drainInput()
|
||||
write("ATL0"); tryRead(2000); drainInput()
|
||||
write("ATE0"); tryRead(2000); drainInput()
|
||||
state = State.READY
|
||||
Log.i(TAG, "ready")
|
||||
}
|
||||
|
||||
fun sendCommand(cmd: String): String {
|
||||
if (state == State.ERROR || state == State.DISCONNECTED) recover()
|
||||
state = State.BUSY
|
||||
val result = exec(cmd, timeoutMs)
|
||||
if (state == State.BUSY) state = State.READY
|
||||
return result
|
||||
}
|
||||
|
||||
private fun exec(cmd: String, timeout: Long): String {
|
||||
write(cmd)
|
||||
var t = timeout
|
||||
for (i in 0 until MAX_RETRIES) {
|
||||
try {
|
||||
return handle(read(t))
|
||||
} catch (_: TimeoutException) {
|
||||
if (state == State.INITIALIZING) t += 1000
|
||||
else { increaseTimeout(); t = timeoutMs }
|
||||
}
|
||||
}
|
||||
Log.e(TAG, "no response for $cmd")
|
||||
state = State.ERROR
|
||||
return ""
|
||||
}
|
||||
|
||||
private fun handle(raw: String): String {
|
||||
val u = raw.uppercase().trim()
|
||||
when {
|
||||
u.startsWith("SEARCHING") -> {}
|
||||
u.startsWith("OK") -> decreaseTimeout()
|
||||
u.startsWith("NODATA") || u.startsWith("NO DATA") -> {
|
||||
increaseTimeout(); updateAtst()
|
||||
}
|
||||
isBusError(u) -> {
|
||||
Log.w(TAG, "BUS ERROR: ${raw.take(60)}")
|
||||
state = State.DISCONNECTED
|
||||
resetTimeout(); updateAtst()
|
||||
write("ATPC"); tryRead(3000)
|
||||
write("ATSP0"); tryRead(3000)
|
||||
}
|
||||
u.startsWith("ERROR") && !u.startsWith("DATA ERROR") -> {
|
||||
Log.w(TAG, "ERROR — warm start")
|
||||
state = State.ERROR
|
||||
write("ATWS"); tryRead(3000)
|
||||
}
|
||||
isDataError(u) -> {
|
||||
Log.w(TAG, "data error — warm start")
|
||||
state = State.ERROR
|
||||
write("ATWS"); tryRead(3000)
|
||||
}
|
||||
else -> decreaseTimeout()
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
private fun recover() {
|
||||
Log.i(TAG, "recovering...")
|
||||
state = State.INITIALIZING
|
||||
write("ATWS"); tryRead(2000); drainInput()
|
||||
write("ATSP0"); tryRead(2000); drainInput()
|
||||
write("ATE0"); tryRead(2000); drainInput()
|
||||
state = State.READY
|
||||
}
|
||||
|
||||
private fun write(cmd: String) {
|
||||
drainInput()
|
||||
output.write((cmd + "\r").toByteArray())
|
||||
output.flush()
|
||||
Log.d(TAG, "→ $cmd")
|
||||
}
|
||||
|
||||
private fun drainInput() {
|
||||
while (input.available() > 0) input.read()
|
||||
}
|
||||
|
||||
@Throws(TimeoutException::class)
|
||||
private fun read(timeout: Long): String {
|
||||
val dl = System.currentTimeMillis() + timeout
|
||||
val sb = StringBuilder()
|
||||
val lines = mutableListOf<String>()
|
||||
var gotPrompt = false
|
||||
while (System.currentTimeMillis() < dl) {
|
||||
if (input.available() > 0) {
|
||||
val b = input.read()
|
||||
if (b == -1) break
|
||||
when (b) {
|
||||
62 -> { push(sb, lines); gotPrompt = true; break } // '>'
|
||||
13 -> push(sb, lines) // CR
|
||||
10, 32 -> {} // LF, space
|
||||
else -> sb.append(b.toChar())
|
||||
}
|
||||
} else {
|
||||
Thread.sleep(POLL_DELAY)
|
||||
}
|
||||
}
|
||||
push(sb, lines)
|
||||
if (!gotPrompt) throw TimeoutException("timeout ${timeout}ms")
|
||||
return lines.joinToString("\n")
|
||||
}
|
||||
|
||||
private fun tryRead(timeout: Long) {
|
||||
try { read(timeout) } catch (_: TimeoutException) {}
|
||||
}
|
||||
|
||||
private fun push(sb: StringBuilder, lines: MutableList<String>) {
|
||||
if (sb.isNotEmpty()) { lines.add(sb.toString()); sb.clear() }
|
||||
}
|
||||
|
||||
private fun increaseTimeout() {
|
||||
if (timeoutMs + TIMEOUT_STEP < TIMEOUT_MAX) timeoutMs += TIMEOUT_STEP
|
||||
}
|
||||
|
||||
private fun decreaseTimeout() {
|
||||
if (timeoutMs - TIMEOUT_STEP >= learnedMin) timeoutMs -= TIMEOUT_STEP
|
||||
}
|
||||
|
||||
private fun resetTimeout() { timeoutMs = DEF_TIMEOUT }
|
||||
|
||||
fun resetAdaptiveTiming() { timeoutMs = DEF_TIMEOUT }
|
||||
|
||||
private fun updateAtst() {
|
||||
val v = (timeoutMs / TIMEOUT_RES).toInt().coerceAtLeast(1)
|
||||
write("ATST${v.toString(16).uppercase().padStart(2, '0')}")
|
||||
tryRead(2000)
|
||||
drainInput()
|
||||
}
|
||||
|
||||
private fun isBusError(s: String): Boolean {
|
||||
return listOf("UNABLE", "BUS BUSY", "BUS ERROR", "CAN ERROR",
|
||||
"BUS INIT", "STOPPED").any { s.startsWith(it) }
|
||||
}
|
||||
|
||||
private fun isDataError(s: String): Boolean {
|
||||
return listOf("DATA ERROR", "BUFFER FULL", "RX ERROR").any { s.startsWith(it) }
|
||||
}
|
||||
}
|
||||
|
||||
class TimeoutException(message: String) : Exception(message)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. DynamicCollector.kt — сборщик для динамического теста
|
||||
|
||||
```kotlin
|
||||
package ru.elmer.client.script
|
||||
|
||||
import ru.elmer.client.elm.ElmProtocol
|
||||
import ru.elmer.client.elm.ObdDecoder
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
class DynamicCollector(
|
||||
private val elm: ElmProtocol,
|
||||
private val steps: List<ElmStep>,
|
||||
private val intervalMs: Long,
|
||||
private val onSample: (sampleIndex: Int) -> Unit,
|
||||
private val onLog: (msg: String) -> Unit
|
||||
) {
|
||||
data class ElmStep(val id: String, val cmd: String, val desc: String)
|
||||
private val running = AtomicBoolean(false)
|
||||
private val samples = mutableListOf<List<SampleResponse>>()
|
||||
private var threadRef: Thread? = null
|
||||
|
||||
data class SampleResponse(
|
||||
val stepId: String, val cmd: String, val raw: String,
|
||||
val decoded: String, val ts: Long = 0
|
||||
)
|
||||
|
||||
fun start() {
|
||||
running.set(true)
|
||||
val startTs = System.currentTimeMillis()
|
||||
threadRef = thread(name = "DynamicCollector", isDaemon = true) {
|
||||
var idx = 0
|
||||
while (running.get()) {
|
||||
val t0 = System.currentTimeMillis()
|
||||
val batch = mutableListOf<SampleResponse>()
|
||||
for (step in steps) {
|
||||
if (!running.get()) break
|
||||
try {
|
||||
val raw = elm.sendCommand(step.cmd)
|
||||
val dec = ObdDecoder.decode(step.cmd, raw)
|
||||
batch.add(SampleResponse(step.id, step.cmd, raw, dec, System.currentTimeMillis() - startTs))
|
||||
} catch (e: Exception) {
|
||||
batch.add(SampleResponse(step.id, step.cmd, "(err)", e.message ?: "error", System.currentTimeMillis() - startTs))
|
||||
}
|
||||
Thread.sleep(350)
|
||||
}
|
||||
if (batch.isNotEmpty()) {
|
||||
synchronized(samples) { samples.add(batch) }
|
||||
onSample(idx); idx++
|
||||
}
|
||||
val elapsed = System.currentTimeMillis() - t0
|
||||
val sleep = intervalMs - elapsed
|
||||
if (sleep > 0 && running.get()) Thread.sleep(sleep)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop(): List<List<SampleResponse>> {
|
||||
running.set(false)
|
||||
try { threadRef?.join(3000) } catch (_: Exception) {}
|
||||
return synchronized(samples) { samples.toList() }
|
||||
}
|
||||
|
||||
fun isRunning(): Boolean = running.get()
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. ElmChecker.kt — проверка устройства + speed-test
|
||||
|
||||
```kotlin
|
||||
package ru.elmer.client.elm
|
||||
|
||||
import android.bluetooth.BluetoothAdapter
|
||||
import android.bluetooth.BluetoothDevice
|
||||
import android.bluetooth.BluetoothSocket
|
||||
import android.util.Log
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
|
||||
class ElmChecker(
|
||||
private val device: BluetoothDevice,
|
||||
private val adapter: BluetoothAdapter
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "ElmChecker"
|
||||
private val SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
|
||||
}
|
||||
|
||||
data class DeviceInfo(
|
||||
val version: String, val deviceId: String, val protocol: String,
|
||||
val voltage: String, val hasAdaptive: Boolean
|
||||
)
|
||||
data class EcuData(val supportsObd: Boolean, val pidMask: String, val vin: String?)
|
||||
data class Result(val good: Boolean, val device: DeviceInfo, val ecu: EcuData, val log: String)
|
||||
|
||||
private val logLines = mutableListOf<String>()
|
||||
fun getLog(): String = logLines.joinToString("\n")
|
||||
private var socket: BluetoothSocket? = null
|
||||
private var elm: ElmProtocol? = null
|
||||
|
||||
fun checkDevice(): DeviceInfo? {
|
||||
if (!connectAndInit()) return null
|
||||
val ati = send("ATI"); val version = parseVersion(ati)
|
||||
val isV2 = version.contains("v2", ignoreCase = true)
|
||||
val deviceId = if (isV2) cleanAt2(send("AT@2")) else "—"
|
||||
val dp = send("ATDP"); val protocol = if (dp.length > 3 && dp != "OK") dp.take(60) else dp
|
||||
val rv = send("ATRV"); val voltage = if (rv.contains("V", ignoreCase = true) || rv.matches(Regex("[0-9.]+"))) rv else "—"
|
||||
val hasAdaptive = if (isV2) send("ATAT1") == "OK" else false
|
||||
return DeviceInfo(version, deviceId, protocol, voltage, hasAdaptive)
|
||||
}
|
||||
|
||||
fun checkEcu(): EcuData {
|
||||
val pid0100 = send("0100"); val supportsObd = pid0100.startsWith("41")
|
||||
val pidMask = if (supportsObd) pid0100.take(60) else "—"
|
||||
val vinRaw = send("0902"); val vin = parseVin(vinRaw)
|
||||
return EcuData(supportsObd, pidMask, vin)
|
||||
}
|
||||
|
||||
fun scanDtc(): List<String>? {
|
||||
if (!connectAndInit()) { disconnect(); return null }
|
||||
val codes = mutableListOf<String>()
|
||||
codes.addAll(parseDtcCodes(send("03")))
|
||||
codes.addAll(parseDtcCodes(send("07")))
|
||||
return codes.distinct()
|
||||
}
|
||||
|
||||
fun ensureConnected(): Boolean = connectAndInit()
|
||||
fun isConnected(): Boolean = socket?.isConnected == true && elm != null
|
||||
fun getElm(): ElmProtocol? = elm
|
||||
|
||||
fun quickCheck(): Int? {
|
||||
val e = elm ?: return null
|
||||
return try {
|
||||
val t0 = System.currentTimeMillis()
|
||||
val raw = e.sendCommand("010C"); val dt = System.currentTimeMillis() - t0
|
||||
if (raw.isBlank() || raw == "(err)") null else dt.toInt()
|
||||
} catch (_: Exception) { null }
|
||||
}
|
||||
|
||||
data class SpeedTestResult(val perPidAvg: List<Int>, val batchTime: Int, val reliable: Boolean, val message: String)
|
||||
|
||||
fun measureResponseTime(onProgress: (String) -> Unit): SpeedTestResult {
|
||||
val testPids = listOf("010C" to "RPM", "0110" to "MAF", "0106" to "STFT")
|
||||
val perPidAvg = mutableListOf<Int>()
|
||||
var hadErrors = false; var reliable = true
|
||||
val reasons = mutableListOf<String>()
|
||||
val e = elm ?: return SpeedTestResult(listOf(250,250,250), 750, false, "❌ ELM не инициализирован")
|
||||
try { e.sendCommand("010C") } catch (_: Exception) {}
|
||||
onProgress("\n⏱ Тест скорости ELM...")
|
||||
for ((pi, pair) in testPids.withIndex()) {
|
||||
val (cmd, name) = pair; val allTimes = mutableListOf<Long>()
|
||||
val count = if (pi == 0) 4 else 3
|
||||
for (i in 0 until count) {
|
||||
val t0 = System.currentTimeMillis()
|
||||
val raw = try { e.sendCommand(cmd) } catch (_: Exception) { "(err)" }
|
||||
val dt = System.currentTimeMillis() - t0; allTimes.add(dt)
|
||||
if (raw == "(err)" || raw.isBlank()) hadErrors = true
|
||||
}
|
||||
val times = if (pi == 0) allTimes.takeLast(2).toMutableList() else allTimes
|
||||
val avg = times.average().toInt(); perPidAvg.add(avg)
|
||||
onProgress("\n $name: ${times.joinToString("ms, ")}ms (среднее ${avg}ms)")
|
||||
for (t in times) {
|
||||
if (t > 0 && avg > 0 && kotlin.math.abs(t - avg).toFloat() / avg > 0.5f) {
|
||||
if (reliable) reliable = false
|
||||
reasons.add("${name} нестабилен: ${t}ms vs среднее ${avg}ms")
|
||||
}
|
||||
}
|
||||
}
|
||||
val batchTime = perPidAvg.sum()
|
||||
val message = if (reliable) "✅ Скорость стабильна: ${perPidAvg.joinToString("+")}=${batchTime}ms"
|
||||
else "⚠️ ${reasons.joinToString("; ")}. Проверьте контакт ELM в OBD-разъёме."
|
||||
onProgress("\n$message")
|
||||
return SpeedTestResult(perPidAvg, batchTime, reliable, message)
|
||||
}
|
||||
|
||||
fun close() { try { socket?.close() } catch (_: Exception) {}; socket = null; elm = null }
|
||||
|
||||
// ... (private connect, send, parseVin, parseDtcCodes, parseVersion, failResult опущены для краткости)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Проблема
|
||||
|
||||
При динамическом тесте:
|
||||
|
||||
```
|
||||
Сессия #54 (v1.3.0-dev): 55 ответов
|
||||
0106 (STFT): 1 ok / 18 попыток → 94% ошибок
|
||||
010C (RPM): 1 ok / 18 попыток → 94% ошибок
|
||||
0110 (MAF): 0 ok / 18 попыток → 100% ошибок
|
||||
|
||||
Первые 2 ответа — нормальные (410680, 41110E), затем 17 пустых.
|
||||
```
|
||||
|
||||
**Поток вызовов перед динамическим тестом:**
|
||||
1. `ElmProtocol.init()` — 5 AT-команд (ATSP0, ATAT1, ATS0, ATL0, ATE0)
|
||||
2. `ElmChecker.checkDevice()` — 5-6 AT-команд (ATI, AT@2, ATDP, ATRV, ATAT1)
|
||||
3. `ElmChecker.checkEcu()` — 2 OBD-команды (0100, 0902)
|
||||
4. В MainActivity: статический проброс 9 PID (0104-011F)
|
||||
5. Speed-test: 1 warmup + 4 RPM + 3 MAF + 3 STFT = 11 OBD-команд
|
||||
6. `ATWS` — сброс ELM
|
||||
7. DynamicCollector: 3 PID в цикле каждые 500ms
|
||||
|
||||
**Ключевое:** `sendCommand()` → `exec()` при таймауте делает RETRY:
|
||||
- `write(cmd)` — посылает команду
|
||||
- `read(timeout)` — ждёт ответ
|
||||
- таймаут → `increaseTimeout()` → `write(cmd)` ОПЯТЬ
|
||||
- до 10 retry на одну команду
|
||||
|
||||
## Вопросы
|
||||
|
||||
1. Почему ELM327 v1.5 замолкает после первых 2 ответов в DynamicCollector?
|
||||
2. Может ли `drainInput()` в `write()` съедать ответ от предыдущей команды?
|
||||
3. Критична ли последовательность: static probe → speed-test → ATWS → dynamic collect?
|
||||
4. Нужно ли переподключать ELM перед динамическим тестом вместо ATWS?
|
||||
5. Как правильно реализовать динамический опрос с учётом медленного ELM327 v1.5 (min ответ 350ms)?
|
||||
|
||||
Ответ сохрани в файл `doc/claude-analysis-elm.md`
|
||||
|
||||
---
|
||||
|
||||
### 4. MainActivity.kt — фрагменты (checkElm, checkEcu, startDynamicRecording)
|
||||
|
||||
```kotlin
|
||||
// Вызывается при клике на светофор ELM
|
||||
private fun checkElm() {
|
||||
// ... поиск Bluetooth-устройства ...
|
||||
elmDevice = dev
|
||||
try {
|
||||
val checker = ElmChecker(dev, btAdapter!!)
|
||||
val r = checker.checkDevice() // AT-команды, инициализация
|
||||
if (r != null) {
|
||||
elmChecker = checker
|
||||
setIndicator(indElm, "🟢")
|
||||
checkEcu() // ← синхронно на главном потоке!
|
||||
// Speed-test в фоновом потоке
|
||||
thread(name = "SpeedTest", isDaemon = true) {
|
||||
val client = ServerClient(...)
|
||||
val saved = client.getProfileResponseTime(elmMac)
|
||||
if (saved != null && saved > 0) {
|
||||
val quick = checker.quickCheck() // 010C × 1
|
||||
// сверка с профилем...
|
||||
return@thread
|
||||
}
|
||||
val result = checker.measureResponseTime { msg -> debugLog(msg) }
|
||||
if (result.reliable) client.saveProfile(elmMac, result.batchTime)
|
||||
}
|
||||
}
|
||||
} catch ...
|
||||
}
|
||||
|
||||
private fun checkEcu() {
|
||||
val checker = elmChecker ?: return
|
||||
try {
|
||||
val raw = checker.getElm()?.sendCommand("03") ?: "" // ← синхронно!
|
||||
val ok = raw.startsWith("43")
|
||||
setIndicator(indEcu, if (ok) "🟢" else "🔴")
|
||||
} catch ...
|
||||
}
|
||||
|
||||
// Вызывается при нажатии СТАРТ
|
||||
private fun startDynamicRecording() {
|
||||
thread(name = "DynamicTest", isDaemon = true) {
|
||||
val checker = elmChecker
|
||||
if (!checker.ensureConnected()) { /* retry */ }
|
||||
val elmProto = checker.getElm()!!
|
||||
|
||||
// ── Статика: пробуем 9 PID ──
|
||||
for ((pid, desc) in staticCmds) {
|
||||
val raw = elmProto.sendCommand("01$pid")
|
||||
// ...
|
||||
}
|
||||
|
||||
// ── ATWS: сброс ELM ──
|
||||
try { elmProto.sendCommand("ATWS") } catch (_: Exception) {}
|
||||
Thread.sleep(300)
|
||||
|
||||
// ── Динамика: 3 PID, интервал 500ms ──
|
||||
val dynSteps = listOf("010C" to "RPM", "0110" to "MAF", "0106" to "STFT")
|
||||
.map { ElmStep(it.second, it.first, it.second) }
|
||||
val collector = DynamicCollector(elmProto, dynSteps, 500L, ...)
|
||||
collector.start()
|
||||
while (state == State.START && collector.isRunning()) Thread.sleep(200)
|
||||
val samples = collector.stop()
|
||||
// ... контроль качества, слияние со статикой ...
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,209 @@
|
||||
# Анализ динамического сбоя ELM327
|
||||
|
||||
Дата: 2026-06-14
|
||||
|
||||
## Контекст
|
||||
|
||||
Проверено:
|
||||
|
||||
- статическая диагностика работает стабильно;
|
||||
- чтение VIN работает;
|
||||
- чтение DTC работает;
|
||||
- последовательное чтение нескольких PID в статическом режиме работает;
|
||||
- ELM327 выдерживает не менее 9 PID подряд в статике;
|
||||
- увеличение пауз до 4000 мс не устраняет проблему;
|
||||
- автоподбор таймингов не устраняет проблему;
|
||||
- сбой проявляется только в динамическом сборе данных через ScriptEngine.
|
||||
|
||||
Это сильно сужает пространство причин. Проблема почти наверняка не в "скорости ELM вообще", не в "ECU не успевает" и не в банальном "надо ещё увеличить задержку".
|
||||
|
||||
## Что объясняет факты лучше всего
|
||||
|
||||
### 1. Несовпадение между тем, как ElmChecker и ScriptEngine общаются с ELM
|
||||
|
||||
Вероятность: высокая.
|
||||
|
||||
Смысл гипотезы: статический путь и динамический путь используют не одинаковую коммуникационную последовательность. Ломается не ELM как таковой, а конкретный сценарий: кто пишет, кто читает, когда читают, что считается окончанием ответа, как очищается буфер, как меняются состояния.
|
||||
|
||||
Что подтверждает:
|
||||
|
||||
- статический путь работает полностью;
|
||||
- динамический ломается только в ScriptEngine;
|
||||
- один и тот же адаптер выдерживает длинную серию PID в статике;
|
||||
- в проектных заметках уже зафиксировано, что проблема может быть именно в различии между ElmChecker и ScriptEngine, а не в тайминге как таковом.
|
||||
|
||||
Что противоречит:
|
||||
|
||||
- если в удачном и неудачном сценарии полностью совпадают AT-команды, порядок команд, чтение и ожидание конца ответа.
|
||||
|
||||
Быстрый эксперимент:
|
||||
|
||||
- снять полный лог команд и сырых ответов для успешного статического пути и для динамического пути;
|
||||
- сравнить именно последовательность TX/RX, а не распарсенные значения;
|
||||
- проверить, расходится ли сценарий уже до первого PID.
|
||||
|
||||
### 2. InputStream не дочитывается до символа ">", и следующий запрос попадает в хвост прошлого ответа
|
||||
|
||||
Вероятность: высокая.
|
||||
|
||||
Смысл гипотезы: динамический читатель завершает чтение раньше, чем ELM реально закончил ответ. В буфере остаётся промпт `>` или другой хвост, и следующий запрос читает не чистый ответ, а остаток прошлого цикла.
|
||||
|
||||
Что подтверждает:
|
||||
|
||||
- это прямо совпадает с типовым режимом отказа ELM327;
|
||||
- в проектных заметках символ `>` отдельно выделен как конец ответа;
|
||||
- в обсуждениях проекта уже встречалась версия, что ответы смешиваются и хвост остаётся в буфере;
|
||||
- статика может это маскировать, потому что между командами там больше естественных пауз.
|
||||
|
||||
Что противоречит:
|
||||
|
||||
- если сырые логи показывают, что каждый ответ полностью доходит до `>` и следующий запрос стартует только после этого;
|
||||
- если после сбоя буфер точно пуст.
|
||||
|
||||
Быстрый эксперимент:
|
||||
|
||||
- включить сырой дамп RX/TX без парсинга;
|
||||
- для первого сбойного цикла проверить, присутствует ли `>` в сыром потоке полностью;
|
||||
- перед следующим запросом проверить, не остаётся ли в InputStream ничего, кроме уже считанного ответа.
|
||||
|
||||
### 3. Остатки данных в буфере ломают синхронизацию между командами
|
||||
|
||||
Вероятность: высокая.
|
||||
|
||||
Смысл гипотезы: чтение и запись идут корректно по отдельности, но между ними нет надёжной очистки буфера. В результате следующий запрос потребляет не только свежий ответ, но и мусор: эхо, переносы строк, старые байты, задержавшийся ответ предыдущего PID.
|
||||
|
||||
Что подтверждает:
|
||||
|
||||
- проектные заметки отдельно говорят, что drainInput раньше был механизмом синхронизации запрос/ответ;
|
||||
- после отключения drainInput в одной из версий стало хуже;
|
||||
- описан эффект сдвига: ответ на команду N прочитан как ответ на N+1;
|
||||
- статический сценарий выдерживает это лучше из-за более редкой частоты обращений.
|
||||
|
||||
Что противоречит:
|
||||
|
||||
- если перед каждым запросом в динамическом цикле буфер гарантированно очищается и при этом проблема остаётся;
|
||||
- если в логах нет признаков мусора, эха или сдвига границ ответов.
|
||||
|
||||
Быстрый эксперимент:
|
||||
|
||||
- один раз до старта динамики и один раз перед вторым запросом вывести количество доступных байт в InputStream и содержимое остатка;
|
||||
- сравнить результат между успешным статическим и неудачным динамическим прогоном;
|
||||
- проверить, есть ли хвосты после первого ответа.
|
||||
|
||||
### 4. ScriptEngine выполняет не тот же state machine, что ElmChecker
|
||||
|
||||
Вероятность: средняя.
|
||||
|
||||
Смысл гипотезы: проблема не в самом Bluetooth и не в самом ELM, а в том, что динамический движок переходит между состояниями раньше или иначе, чем ElmChecker. Например, команда считается завершённой по временному признаку, а не по фактическому окончанию ответа.
|
||||
|
||||
Что подтверждает:
|
||||
|
||||
- пользователь отдельно выделил риск state machine;
|
||||
- динамический режим содержит свои шаги, цикл и внутренние переходы;
|
||||
- статический путь короче и проще, поэтому ошибки state machine там могут не проявляться;
|
||||
- уже были замечания, что в таких сценариях рассинхрон появляется раньше, чем кажется.
|
||||
|
||||
Что противоречит:
|
||||
|
||||
- если логически и по времени state transitions происходят только после полного ответа ELM;
|
||||
- если обе машины выполняют одинаковый сценарий завершения команды.
|
||||
|
||||
Быстрый эксперимент:
|
||||
|
||||
- на одном прогоне логировать каждое состояние до и после отправки команды;
|
||||
- отметить момент, когда реально получен `>`;
|
||||
- проверить, не уходит ли ScriptEngine в следующий шаг до фактического конца ответа.
|
||||
|
||||
### 5. Доступ к одному сокету или одному InputStream идёт из двух потоков
|
||||
|
||||
Вероятность: средняя.
|
||||
|
||||
Смысл гипотезы: чтение или запись в динамике пересекаются с другим потоком, который тоже читает или пишет тот же канал. Для ELM это критично: поток байтов становится недетерминированным, и команда может лишиться части ответа.
|
||||
|
||||
Что подтверждает:
|
||||
|
||||
- пользователь отдельно попросил проверить конкурентный доступ к сокету;
|
||||
- динамический режим по определению более многопоточен: цикл, сбор данных, UI, возможные фоновые операции;
|
||||
- статический путь может не задевать гонку из-за более редкой частоты и меньшего числа активных операций.
|
||||
|
||||
Что противоречит:
|
||||
|
||||
- если трасса покажет строго одного читателя и одного писателя на весь жизненный цикл соединения;
|
||||
- если динамика воспроизводится даже в полностью однопоточном прогоне.
|
||||
|
||||
Быстрый эксперимент:
|
||||
|
||||
- вывести thread id для каждого read и write;
|
||||
- проверить, нет ли второго consumer на InputStream;
|
||||
- сравнить идентичность владельца сокета в статике и динамике.
|
||||
|
||||
### 6. Неправильная последовательность команд, а не неправильная пауза
|
||||
|
||||
Вероятность: средняя-низкая.
|
||||
|
||||
Смысл гипотезы: дело не в длительности ожидания как таковой, а в том, что динамический сценарий отправляет команды в другом порядке или с другим набором служебных AT-команд, чем успешный статический сценарий. Тогда ELM оказывается в другом режиме, и дальнейшая обработка ломается.
|
||||
|
||||
Что подтверждает:
|
||||
|
||||
- в проекте есть отдельные сценарии для статической диагностики, тестового скрипта и динамики;
|
||||
- серверный build_test_script и build_dynamic_script действительно строят разные последовательности;
|
||||
- в заметках по ELM отдельно обсуждаются последствия ATWS, ATE0/ATL0/ATS0 и различий в инит-последовательности.
|
||||
|
||||
Что противоречит:
|
||||
|
||||
- если сравнение трасс покажет полностью одинаковый init и только разный темп;
|
||||
- если тот же набор команд в статике и динамике повторяет поломку только из-за способа выполнения, а не порядка.
|
||||
|
||||
Быстрый эксперимент:
|
||||
|
||||
- распечатать полный список команд, которые реально уходят в ELM в обоих режимах;
|
||||
- сравнить not only PID, но и все AT-команды, входы в state machine и возможные reset-команды;
|
||||
- проверить, совпадает ли стартовая инициализация побайтно.
|
||||
|
||||
## Что менее вероятно
|
||||
|
||||
### Adaptive timing как первопричина
|
||||
|
||||
Вероятность: низкая.
|
||||
|
||||
Почему низкая:
|
||||
|
||||
- уже проверяли увеличение пауз до 4000 мс;
|
||||
- уже проверяли автоподбор;
|
||||
- одиночные запросы и статический набор PID работают.
|
||||
|
||||
Вывод: adaptive timing может усиливать или маскировать проблему, но не выглядит корнем сбоя.
|
||||
|
||||
### Просто "мало ждать"
|
||||
|
||||
Вероятность: низкая.
|
||||
|
||||
Почему низкая:
|
||||
|
||||
- паузы уже увеличивали;
|
||||
- первый запрос проходит, второй ломается;
|
||||
- для обычного ELM327 это больше похоже на ошибку синхронизации, чем на нехватку миллисекунд.
|
||||
|
||||
## Итоговая интерпретация
|
||||
|
||||
Новое мнение хорошо согласуется с уже собранными фактами. Оно сдвигает фокус с "таймингов вообще" на более узкий класс проблем:
|
||||
|
||||
- границы ответа ELM, особенно символ `>`;
|
||||
- остатки в InputStream;
|
||||
- различие между ElmChecker и ScriptEngine;
|
||||
- state machine, которая может идти вперёд раньше времени;
|
||||
- возможная конкуренция за сокет или поток чтения.
|
||||
|
||||
Главный вывод: если статический путь стабилен, а динамический ломается даже при больших паузах, то первичная причина почти наверняка находится не в задержках, а в чтении потока, границах ответа и разнице в сценарии исполнения.
|
||||
|
||||
## Порядок расследования
|
||||
|
||||
1. Снять сырой RX/TX лог без парсинга для статического и динамического режима.
|
||||
2. Проверить, доходит ли каждый ответ до `>` и не остаются ли байты в буфере перед следующим запросом.
|
||||
3. Сопоставить полную последовательность команд ElmChecker и ScriptEngine.
|
||||
4. Подтвердить или опровергнуть второй consumer на сокете/InputStream.
|
||||
5. Проверить, не идёт ли state machine вперёд до фактического завершения ответа.
|
||||
|
||||
## Краткий вывод
|
||||
|
||||
Наиболее правдоподобно, что проблема не в скорости ELM, а в том, как динамический сценарий читает и синхронизирует поток ответов. Внутри этого класса причин самые сильные кандидаты: неполное дочитывание до `>`, остатки в InputStream, и различие между ElmChecker и ScriptEngine.
|
||||
@@ -0,0 +1,293 @@
|
||||
# План: тонкий Android-ретранслятор ELM327
|
||||
|
||||
Дата: 2026-06-14
|
||||
|
||||
## Цель
|
||||
|
||||
Отдельное Android-приложение — тупой ретранслятор команд между сервером и ELM327.
|
||||
Пользователь устанавливает один раз. Вся логика (какие команды слать, как анализировать
|
||||
ответы) — на сервере. Приложение только:
|
||||
|
||||
1. Коннектится к ELM327 по Bluetooth
|
||||
2. Сообщает серверу «готов»
|
||||
3. Поллит сервер на наличие команды
|
||||
4. Отправляет команду в ELM327
|
||||
5. Возвращает сырой ответ на сервер
|
||||
6. Повторяет с пункта 3
|
||||
|
||||
## Почему отдельное приложение
|
||||
|
||||
- Ноль риска сломать существующий `ru.elmer.client`
|
||||
- Независимый пакет `ru.elmer.raw`
|
||||
- Свой APK, свой URL на сервере (`/elm-raw.apk`)
|
||||
- Можно удалить/переустановить независимо от основного
|
||||
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Сервер (elmer/python) │
|
||||
│ │
|
||||
│ POST /api/v1/elm/raw/cmd ← я ставлю команду │
|
||||
│ GET /api/v1/elm/raw/cmd ← приложение поллит │
|
||||
│ POST /api/v1/elm/raw/response ← приложение шлёт │
|
||||
│ GET /api/v1/elm/raw/response ← я читаю ответ │
|
||||
│ /elm-raw.apk ← раздача APK │
|
||||
└──────────────┬──────────────────────────────────┘
|
||||
│ HTTP (OkHttp)
|
||||
┌──────────────▼──────────────────────────────────┐
|
||||
│ Android-приложение (ru.elmer.raw) │
|
||||
│ │
|
||||
│ RawRelayService (foreground) │
|
||||
│ ├─ Bluetooth → ELM327 │
|
||||
│ ├─ ElmProtocol (AndrOBD, проверенный) │
|
||||
│ ├─ Polling: GET /cmd каждые 500ms │
|
||||
│ └─ POST /response с сырым ответом │
|
||||
│ │
|
||||
│ MainActivity (минимальный UI) │
|
||||
│ ├─ Статус: сервер / ELM / ECU │
|
||||
│ ├─ Лог последних команд │
|
||||
│ └─ Кнопка «Стоп» │
|
||||
└──────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Компоненты Android-приложения
|
||||
|
||||
### 1. Пакет: `ru.elmer.raw`
|
||||
|
||||
Новый пакет, не пересекается с `ru.elmer.client`.
|
||||
|
||||
### 2. Файлы (5 штук)
|
||||
|
||||
| Файл | Размер | Назначение |
|
||||
|------|--------|-----------|
|
||||
| `MainActivity.kt` | ~100 строк | UI: статус, лог, кнопка стоп |
|
||||
| `RawRelayService.kt` | ~150 строк | Foreground-сервис: BT+поллинг+команды |
|
||||
| `ElmProtocol.kt` | копия | Точная копия из `ru.elmer.client.elm` |
|
||||
| `ServerClient.kt` | ~80 строк | Урезанный HTTP-клиент (только cmd/response) |
|
||||
| `AndroidManifest.xml` | ~40 строк | Свой манифест для `ru.elmer.raw` |
|
||||
|
||||
**Почему копия ElmProtocol.kt, а не общий модуль:**
|
||||
- Не трогаем существующий код вообще
|
||||
- AndrOBD-логика отлажена годами, меняться не будет
|
||||
- Две копии живут независимо, никаких конфликтов
|
||||
|
||||
### 3. ElmProtocol.kt — как есть
|
||||
|
||||
Используем **без изменений** проверенную стейт-машину:
|
||||
- `init()`: ATSP0 → ATAT1 → ATS0 → ATL0 → ATE0
|
||||
- `sendCommand(cmd)`: отправить → прочитать до `>` → вернуть сырой ответ
|
||||
- Обработка ошибок: BUS ERROR, CAN ERROR, BUFFER FULL, ретраи, восстановление
|
||||
- Адаптивные тайминги
|
||||
|
||||
Единственное что добавим — вызов `sendCommand()` оборачиваем в `try/catch`,
|
||||
результат всегда возвращается на сервер (даже если ошибка).
|
||||
|
||||
### 4. Протокол обмена с сервером
|
||||
|
||||
#### Приложение → Сервер: «я готов»
|
||||
```
|
||||
POST /api/v1/elm/raw/hello
|
||||
{
|
||||
"device_id": "android-xyz",
|
||||
"elm_version": "ELM327 v1.5",
|
||||
"protocol": "A4",
|
||||
"voltage": "12.3V"
|
||||
}
|
||||
```
|
||||
|
||||
#### Сервер → Приложение: команда
|
||||
```
|
||||
GET /api/v1/elm/raw/cmd?device_id=android-xyz
|
||||
Ответ 200:
|
||||
{
|
||||
"cmd": "0105",
|
||||
"timeout_ms": 500,
|
||||
"drain_first": false,
|
||||
"seq": 1
|
||||
}
|
||||
Ответ 204: (нет команды — полли дальше)
|
||||
```
|
||||
|
||||
#### Приложение → Сервер: ответ
|
||||
```
|
||||
POST /api/v1/elm/raw/response
|
||||
{
|
||||
"device_id": "android-xyz",
|
||||
"seq": 1,
|
||||
"cmd": "0105",
|
||||
"raw": "41 05 5C",
|
||||
"prompt": true,
|
||||
"elapsed_ms": 48,
|
||||
"bytes": 8,
|
||||
"error": null
|
||||
}
|
||||
```
|
||||
|
||||
#### Сервер → Приложение: подтверждение
|
||||
```
|
||||
200 {"ok": true}
|
||||
```
|
||||
|
||||
### 5. RawRelayService — жизненный цикл
|
||||
|
||||
```
|
||||
onStartCommand(Intent: serverUrl)
|
||||
↓
|
||||
1. Подключить Bluetooth к ELM327 (UUID SPP 00001101-0000-1000-8000-00805F9B34FB)
|
||||
↓
|
||||
2. ElmProtocol.init() — базовая инициализация
|
||||
↓
|
||||
3. POST /hello — сообщить серверу «готов»
|
||||
↓
|
||||
4. Цикл (в фоновом потоке):
|
||||
GET /cmd — ждать команду (500ms поллинг)
|
||||
если 204 → sleep 500ms → снова GET /cmd
|
||||
если 200 →
|
||||
drain? → ElmProtocol.sendCommand("ATPC") → read/discard
|
||||
ElmProtocol.sendCommand(cmd)
|
||||
POST /response — отправить сырой ответ
|
||||
→ снова GET /cmd
|
||||
↓
|
||||
5. onDestroy(): закрыть BT, stopForeground, остановить поток
|
||||
```
|
||||
|
||||
### 6. MainActivity — UI
|
||||
|
||||
```
|
||||
┌──────────────────────────────┐
|
||||
│ ELM327 Raw Relay │
|
||||
│ │
|
||||
│ Сервер: ✅ obdai.ru │
|
||||
│ ELM: 🔵 подключён │
|
||||
│ ECU: ✅ отвечает │
|
||||
│ │
|
||||
│ Последняя команда: │
|
||||
│ → 0105 │
|
||||
│ ← 41 05 5C (48ms, 8 байт) │
|
||||
│ │
|
||||
│ Лог: 12 команд, 0 ошибок │
|
||||
│ │
|
||||
│ [ СТОП ] │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
Минимальный UI:
|
||||
- Три индикатора статуса (сервер, ELM, ECU)
|
||||
- Последняя команда и ответ
|
||||
- Счётчик команд/ошибок
|
||||
- Кнопка «Стоп»
|
||||
|
||||
## Изменения на серверной стороне (elmer/python)
|
||||
|
||||
### 1. Очередь команд — `api/raw_elm.py`
|
||||
|
||||
Добавить эндпоинты (дополнить существующий `api/raw_elm.py`):
|
||||
|
||||
```
|
||||
POST /api/v1/elm/raw/cmd — я ставлю команду в очередь
|
||||
GET /api/v1/elm/raw/cmd — приложение забирает команду
|
||||
POST /api/v1/elm/raw/response — приложение шлёт ответ
|
||||
GET /api/v1/elm/raw/response — я читаю последний ответ
|
||||
POST /api/v1/elm/raw/hello — приложение регистрируется
|
||||
GET /api/v1/elm/raw/status — статус: готово/ждёт/ошибка
|
||||
```
|
||||
|
||||
### 2. Хранение очереди
|
||||
|
||||
В памяти (глобальная переменная), не в БД:
|
||||
- `_pending_cmd: dict | None` — команда, которую ждёт приложение
|
||||
- `_last_response: dict | None` — последний ответ от ELM327
|
||||
- `_device_ready: bool` — готово ли приложение
|
||||
- `_device_info: dict` — информация об устройстве
|
||||
|
||||
Зачем в памяти: одна сессия отладки, один поток команд. Не нужна персистентность.
|
||||
|
||||
### 3. Раздача APK — `web/app.py`
|
||||
|
||||
```python
|
||||
@app.route("/elm-raw.apk")
|
||||
def download_raw_apk():
|
||||
return send_from_directory("static", "elm-raw.apk", ...)
|
||||
```
|
||||
|
||||
В `templates/index.html` — ссылка «Скачать ELM Raw Relay».
|
||||
|
||||
### 4. Интерактивная консоль — `tools/elm_relay.py`
|
||||
|
||||
Скрипт для меня (Copilot):
|
||||
- Читает статус устройства
|
||||
- Ставит команду в очередь
|
||||
- Ждёт ответ
|
||||
- Показывает сырой ответ
|
||||
- Анализирует, ставит следующую команду
|
||||
- История всех команд сохраняется
|
||||
|
||||
## Сборка и деплой
|
||||
|
||||
### Сборка APK
|
||||
|
||||
```bash
|
||||
cd android
|
||||
./gradlew :app:assembleDebug
|
||||
# APK: android/app/build/outputs/apk/debug/app-debug.apk
|
||||
```
|
||||
|
||||
Но нам нужен **отдельный** APK для `ru.elmer.raw`. Два варианта:
|
||||
|
||||
**Вариант A: Product Flavor** (в одном проекте)
|
||||
- В `app/build.gradle.kts` добавить `flavorDimensions` + два flavor: `client` и `raw`
|
||||
- Разные `applicationId`, разные `AndroidManifest.xml`
|
||||
- Общий код в `main/`, специфичный — в `client/` и `raw/`
|
||||
- Минус: трогаем `build.gradle.kts` основного приложения
|
||||
|
||||
**Вариант B: Новый модуль** (рекомендую)
|
||||
- Новый Gradle-модуль `android/raw/`
|
||||
- Свой `build.gradle.kts`, свой манифест, свой пакет
|
||||
- Не трогаем вообще ничего в `android/app/`
|
||||
- `settings.gradle.kts` — добавить `include(":raw")`
|
||||
- Минус: ElmProtocol.kt — физическая копия файла
|
||||
|
||||
### Я за Вариант B: новый модуль `:raw`
|
||||
|
||||
```
|
||||
android/
|
||||
├── app/ ← существующее, НЕ ТРОГАЕМ
|
||||
├── raw/ ← НОВЫЙ модуль
|
||||
│ ├── build.gradle.kts
|
||||
│ └── src/main/
|
||||
│ ├── AndroidManifest.xml
|
||||
│ └── java/ru/elmer/raw/
|
||||
│ ├── MainActivity.kt
|
||||
│ ├── RawRelayService.kt
|
||||
│ ├── ElmProtocol.kt ← копия из :app
|
||||
│ └── ServerClient.kt
|
||||
├── settings.gradle.kts ← + include(":raw")
|
||||
└── build.gradle.kts ← не трогаем
|
||||
```
|
||||
|
||||
### Деплой
|
||||
|
||||
```bash
|
||||
cd android
|
||||
./gradlew :raw:assembleDebug
|
||||
cp raw/build/outputs/apk/debug/raw-debug.apk ../web/static/elm-raw.apk
|
||||
# Задеплоить на сервер через deploy.sh
|
||||
```
|
||||
|
||||
## Порядок работ
|
||||
|
||||
1. **Сервер**: дополнить `api/raw_elm.py` эндпоинтами очереди
|
||||
2. **Сервер**: добавить `web/app.py` — раздача `/elm-raw.apk`
|
||||
3. **Сервер**: `tools/elm_relay.py` — консоль для меня
|
||||
4. **Android**: модуль `:raw` — 5 файлов (.kt + манифест + build.gradle)
|
||||
5. **Сборка**: проверить что оба APK собираются
|
||||
6. **Тест**: поставить APK на телефон, проверить связь с сервером
|
||||
|
||||
## Что НЕ делаем
|
||||
|
||||
- Не трогаем `ru.elmer.client` — ни строчки
|
||||
- Не меняем `app/build.gradle.kts`
|
||||
- Не меняем существующий `AndroidManifest.xml`
|
||||
- Не изобретаем новый ELM327-протокол — используем AndrOBD как есть
|
||||
- Не пишем сложный UI — только статус и лог
|
||||
@@ -0,0 +1,207 @@
|
||||
# 2026-06-10 — Speed-test ELM327, адаптивный интервал, валидация, деплой v0.94.0-dev
|
||||
|
||||
## Проблема
|
||||
|
||||
Динамический тест (START/STOP) использует жёстко заданный интервал 250мс для опроса 3 PID (RPM, MAF, STFT). Реальные тесты на машине показали:
|
||||
|
||||
- **Session #47** (3 PID × 250ms): 94% ошибок — ELM327 v1.5 не успевает
|
||||
- **Session #48** (3 PID × 250ms): первые 15 сэмплов ок, потом все пустые — буфер ELM переполняется
|
||||
- **Session #45** (5 PID × 500ms, старый): после ~20 сэмплов тоже падает
|
||||
|
||||
**Корень:** 3 команды занимают ~240-300ms на ELM327 v1.5. При интервале 250ms пауза между батчами ≈ 0ms. Буфер UART переполняется, ELM перестаёт отвечать.
|
||||
|
||||
Также: в `api/db.py` не было защиты `threading.Lock` — 20 конкурентных записей в БД давали 8 ошибок.
|
||||
|
||||
---
|
||||
|
||||
## Решения
|
||||
|
||||
### 1. Threading lock в Database
|
||||
|
||||
`api/db.py` — добавлен `threading.Lock()`, обёрнуты все write-методы (`save_session`, `save_dtc_scan`, `save_device_profile`).
|
||||
|
||||
Было: `self.conn.execute()` + `self.conn.commit()` без блокировки → 8/20 ошибок при конкурентном доступе.
|
||||
Стало: `with self._lock:` → 0 ошибок.
|
||||
|
||||
Коммит: `fix: threading lock in Database for concurrent writes`
|
||||
|
||||
### 2. Speed-test ELM327 — адаптивный интервал
|
||||
|
||||
#### Концепция
|
||||
|
||||
При первом подключении нового ELM327 (уникальный BT MAC) — замерить скорость ответа на разных PID, сохранить в профиль. При последующих запусках использовать сохранённое значение для расчёта интервала.
|
||||
|
||||
#### Сервер — `api/db.py`
|
||||
|
||||
Добавлена колонка `response_time_ms INTEGER DEFAULT 250` в таблицу `device_profiles`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE device_profiles (
|
||||
mac TEXT PRIMARY KEY,
|
||||
level INTEGER NOT NULL,
|
||||
elm_version TEXT,
|
||||
elm_desc TEXT,
|
||||
protocol TEXT,
|
||||
voltage TEXT,
|
||||
response_time_ms INTEGER DEFAULT 250, -- <-- NEW
|
||||
supported TEXT,
|
||||
unsupported TEXT,
|
||||
errors TEXT,
|
||||
first_seen TEXT,
|
||||
last_seen TEXT
|
||||
);
|
||||
```
|
||||
|
||||
Миграция для старых БД:
|
||||
```sql
|
||||
ALTER TABLE device_profiles ADD COLUMN response_time_ms INTEGER DEFAULT 250;
|
||||
```
|
||||
|
||||
`save_device_profile()` обновлена: принимает и сохраняет `response_time_ms`.
|
||||
|
||||
#### Сервер — `api/routes.py`
|
||||
|
||||
Добавлен эндпоинт:
|
||||
```
|
||||
PUT /api/v1/elm/profile/<mac>
|
||||
Body: {"response_time_ms": 180}
|
||||
```
|
||||
|
||||
Позволяет Android-клиенту обновить скорость ELM в профиле.
|
||||
|
||||
#### Android — `ElmChecker.kt`
|
||||
|
||||
Добавлен метод `measureResponseTime(elm: ElmProtocol, log: (String) -> Unit): Int`:
|
||||
|
||||
```
|
||||
Алгоритм:
|
||||
1. Выбрать 3 PID: 010C (RPM), 0110 (MAF), 0106 (STFT)
|
||||
2. Каждый PID послать 3 раза
|
||||
3. Замерить round-trip время для каждого
|
||||
4. Усреднить
|
||||
5. Вернуть среднее в миллисекундах
|
||||
6. Логировать в UI: "⏱ Тест скорости: 010C — 82ms, 89ms, 78ms"
|
||||
```
|
||||
|
||||
Вызывается после connectAndInit(), перед стартом динамического теста.
|
||||
|
||||
#### Android — `MainActivity.kt` — `startDynamicRecording()`
|
||||
|
||||
В流程 добавлен speed-test между статическим пробросом PID и динамическим сбором:
|
||||
|
||||
```
|
||||
1. Статика: пробуем 9 PID, log в UI
|
||||
2. Speed-test: 3 PID × 3 раза, замер времени
|
||||
→ "⏱ Тест скорости ELM..."
|
||||
→ " RPM: 82ms 89ms 78ms (среднее 83ms)"
|
||||
→ " MAF: 95ms 91ms 88ms (среднее 91ms)"
|
||||
→ " STFT: 79ms 82ms 85ms (среднее 82ms)"
|
||||
→ " Среднее по всем: 85ms"
|
||||
3. Расчёт интервала: max(250, avg_response_time × 3 × 1.5)
|
||||
→ "📡 Интервал опроса: 383ms (запас 50%)"
|
||||
4. Сохранение response_time_ms на сервер
|
||||
5. Запуск DynamicCollector с вычисленным интервалом
|
||||
```
|
||||
|
||||
Формула интервала:
|
||||
```
|
||||
interval = max(250, avg_response_time × num_pids × 1.5)
|
||||
```
|
||||
|
||||
Где:
|
||||
- `avg_response_time` — среднее время ответа ELM на одну команду (ms)
|
||||
- `num_pids` — количество PID в динамическом тесте (3)
|
||||
- `1.5` — запас 50% на вариативность
|
||||
- `250` — минимальный интервал (для быстрых ELM327 v2.x)
|
||||
|
||||
Если профиль уже существует (повторный запуск) — speed-test пропускается, интервал берётся из профиля. По кнопке «принудительно» можно перезамерить.
|
||||
|
||||
---
|
||||
|
||||
## Итог тестов
|
||||
|
||||
После фикса threading lock:
|
||||
```
|
||||
134 ✅ / 0 ❌ — все тесты проходят
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Файлы
|
||||
|
||||
| Файл | Что изменено |
|
||||
|------|-------------|
|
||||
| `api/db.py` | threading lock, response_time_ms колонка, миграция |
|
||||
| `api/routes.py` | PUT /api/v1/elm/profile/<mac> |
|
||||
| `android/.../ElmChecker.kt` | measureResponseTime() |
|
||||
| `android/.../MainActivity.kt` | speed-test перед динамикой, адаптивный интервал |
|
||||
| `android/.../ServerClient.kt` | saveProfile() — отправка response_time_ms |
|
||||
| `android/.../DynamicCollector.kt` | intervalMs параметр (уже есть) |
|
||||
| `android/app/build.gradle.kts` | versionName = "0.93.0-dev" |
|
||||
| `web/templates/index.html` | v0.93.0-dev |
|
||||
|
||||
---
|
||||
|
||||
## 3. Валидация speed-test (v0.94.0-dev)
|
||||
|
||||
### Проблема
|
||||
Если ELM327 плохо вставлен в OBD-разъём (контакт болтается), замеры скорости — мусор: часть команд падает с `(err)`, время прыгает от 10ms до 900ms. Сохранять такой профиль нельзя.
|
||||
|
||||
### Решение
|
||||
`ElmChecker.kt` — `measureResponseTime()` возвращает `SpeedTestResult`:
|
||||
|
||||
```kotlin
|
||||
data class SpeedTestResult(
|
||||
val perPidAvg: List<Int>,
|
||||
val batchTime: Int,
|
||||
val reliable: Boolean,
|
||||
val message: String
|
||||
)
|
||||
```
|
||||
|
||||
**Критерии отбраковки (reliable=false):**
|
||||
1. Любой замер отклоняется от среднего по своему PID >50%
|
||||
2. Любая команда вернула `(err)` или пустой ответ
|
||||
3. Все замеры <20ms (ELM не отвечает, мусор)
|
||||
|
||||
При `reliable=false` — профиль **не сохраняется**, интервал 250ms по умолчанию.
|
||||
|
||||
### Quick-check при каждом connect
|
||||
`ElmChecker.kt` — добавлен `quickCheck(): Int?`:
|
||||
|
||||
```
|
||||
При каждом клике на светофор ELM:
|
||||
1. Загрузить профиль с сервера
|
||||
2. Послать 010C (RPM), замерить время
|
||||
3. Сравнить с профилем:
|
||||
- расхождение <50% → "✅ ELM стабилен: ~85ms (профиль 256ms)"
|
||||
- расхождение >50% → "⚠️ Скорость ELM изменилась: было 256ms, сейчас ~510ms"
|
||||
4. Если профиля нет → полный speed-test (3 PID × 3 раза)
|
||||
```
|
||||
|
||||
### Принудительный перетест
|
||||
Клик на 🔵 ELM → переинициализация → quick-check. Если нужно полностью перемерить — очистить `response_time_ms` в `device_profiles` на сервере.
|
||||
|
||||
---
|
||||
|
||||
## Итоговая логика
|
||||
|
||||
| Ситуация | При connect | При СТАРТ |
|
||||
|----------|------------|-----------|
|
||||
| Новый ELM (нет профиля) | Полный speed-test 3 PID × 3 → сохранить | Интервал из профиля |
|
||||
| Знакомый ELM, контакт ок | Quick-check: "стабилен" | Интервал из профиля |
|
||||
| Знакомый ELM, контакт плохой | Quick-check: "изменилась" | Интервал 250ms (дефолт) |
|
||||
| После переподключения | Quick-check → сверка | Интервал из профиля если ок |
|
||||
|
||||
## Файлы (v0.94.0-dev)
|
||||
|
||||
| Файл | Что изменено |
|
||||
|------|-------------|
|
||||
| `android/.../ElmChecker.kt` | `SpeedTestResult`, `quickCheck()`, валидация |
|
||||
| `android/.../MainActivity.kt` | Speed-test при инициализации, quick-check |
|
||||
| `android/.../ServerClient.kt` | `getProfileResponseTime()`, `saveProfile()` |
|
||||
| `api/db.py` | `response_time_ms` колонка, threading lock |
|
||||
| `api/routes.py` | `PUT /api/v1/elm/profile/<mac>` |
|
||||
| `android/app/build.gradle.kts` | versionName = "0.94.0-dev" |
|
||||
| `web/templates/index.html` | v0.94.0-dev |
|
||||
| `doc/history/2026-06-10.md` | Этот файл |
|
||||
@@ -0,0 +1,396 @@
|
||||
# Automotive Sensing and Actuators
|
||||
|
||||
> Источник: [MPScholar — Monolithic Power Systems](https://www.monolithicpower.com/en/learning/mpscholar/automotive-electronics/automotive-sensing-and-actuators)
|
||||
> Дата сохранения: 2026-06-10
|
||||
|
||||
---
|
||||
|
||||
## Содержание
|
||||
|
||||
1. [Introduction to Automotive Sensors and Actuators](#1-introduction-to-automotive-sensors-and-actuators)
|
||||
2. [Types and Functions of Sensors in Automotive Systems](#2-types-and-functions-of-sensors-in-automotive-systems)
|
||||
3. [Types and Functions of Actuators in Automotive Systems](#3-types-and-functions-of-actuators-in-automotive-systems)
|
||||
4. [Power Management for Sensors and Actuators](#4-power-management-for-sensors-and-actuators)
|
||||
5. [Integration and Interfacing of Sensors and Actuators](#5-integration-and-interfacing-of-sensors-and-actuators)
|
||||
|
||||
---
|
||||
|
||||
## 1. Introduction to Automotive Sensors and Actuators
|
||||
|
||||
### The Role of Sensors and Actuators in Modern Vehicles
|
||||
|
||||
A new era of unheard-of performance, safety, and control in automobiles has begun with the introduction of sensors and actuators in automotive engineering. The future of mobility can be understood by comprehending the complex functions that these devices play, especially at a time when we are on the verge of a revolution in transportation.
|
||||
|
||||
#### Overview of Vehicle Automation and Control
|
||||
|
||||
The 21st-century automobile is changing from a mechanical device to an extremely complex electrical system on wheels. This change has been made possible in large part by the growing integration of actuators and sensors, which work together to enhance vehicle functioning.
|
||||
|
||||
- **Role of Sensors:** In essence, sensors are the eyes and ears of a vehicle. They keep an eye on a number of variables, including proximity, temperature, acceleration, and speed. Numerous control systems rely on this data to provide them with real-time information about the vehicle and its surroundings.
|
||||
|
||||
- **Role of Actuators:** If sensors are the information gatherers, actuators are the doers. Actuators receive signals and respond with specified actions, including changing the air-fuel ratio in the engine, tightening up the suspension, or even applying the brakes. They convert electrical information into mechanical action, directly influencing and controlling a variety of vehicle components.
|
||||
|
||||
#### Improving Safety, Efficiency, and Performance
|
||||
|
||||
The ultimate goal of sensor and actuator integration is to improve driving in three critical areas: performance, efficiency, and safety.
|
||||
|
||||
- **Safety Enhancements:** In order to provide power to advanced driver-assistance systems (ADAS), sensors such as radar, lidar, and cameras collaborate with one another. Meticulous sensor input and actuator reaction enable features like automated emergency braking, adaptive cruise control, and lane-keeping assistance. Through anticipatory threat detection and proactive measures, these technologies significantly lower accident rates and save lives.
|
||||
|
||||
- **Efficiency Optimization:** In today's automotive world, fuel economy and pollution management are critical. Onboard computers can modify combustion settings due to sensors that track pollutants and engine data. Actuators then put these adjustments into practice, maximizing fuel efficiency and lowering dangerous emissions. In a similar vein, sensors aid in the best possible battery utilization in electric cars, guaranteeing optimal range and longevity.
|
||||
|
||||
- **Performance Upgrades:** Today's drivers need a car that is strong, nimble, and responsive. Sensors evaluate performance metrics like grip, acceleration, and aerodynamic drag through continuous feedback loops. Actuators then modify components such as the suspension, engine, and gearbox to improve the vehicle's performance and provide for a thrilling ride.
|
||||
|
||||
To sum up, the integration of actuators and sensors in contemporary automobiles has completely reshaped the concepts of automotive engineering. These elements will become even more crucial as we approach the future of autonomous driving and smart transportation, spurring innovation and setting new standards for performance, safety, and efficiency.
|
||||
|
||||
### Basic Principles of Sensing and Actuation
|
||||
|
||||
The two main pillars that support the current vehicle control system are actuation and sensing. The sophisticated and sensitive behavior of today's cars, which allows them to easily interact with constantly changing environments, depends on both of these components.
|
||||
|
||||
#### Sensing as Information Gathering
|
||||
|
||||
In the context of automobiles, sensing can be conceptualized as the means by which the vehicle perceives its internal states and external environment. Similar to how our senses of sight, touch, and hearing feed us vital information about the world around us, automobile sensors pick up on particular factors that affect how well vehicles operate.
|
||||
|
||||
- **Types of Sensors:** Sensors vary widely based on their functional requirement. Common varieties include position sensors (for crankshaft or throttle position), temperature sensors (for engine and interior conditions), pressure sensors (in tire monitoring systems or fuel lines), and more sophisticated devices (such as cameras and radars for ADAS functions).
|
||||
|
||||
- **Data Acquisition:** Every sensor operates on the principle of converting a physical quantity into an electrical signal. Electronic control units (ECUs) interpret and analyze these electrical impulses, making real-time analysis possible. For this reason, this conversion is essential.
|
||||
|
||||
- **Feedback Mechanism:** Continuous data collection guarantees that a feedback loop is maintained at all times, which in turn supplies the control systems of the vehicle with the most recent information. This ongoing cycle enables the behavior of the vehicle to be improved and adjusted.
|
||||
|
||||
#### Actuation as Control Execution
|
||||
|
||||
Actuation takes over to make the required adjustments after the sensors have collected the crucial data. Actuators essentially function as the vehicle's "muscles," translating the electrical impulses that are processed back into motion.
|
||||
|
||||
- **Types of Actuators:** Actuators in vehicles are diverse, including components like fuel injectors (which control fuel delivery), electric motors (steering, braking, or throttle control), and solenoids (for valve operation or gear shifts).
|
||||
|
||||
- **Signal Interpretation:** The ECUs of the car send signals to the actuators, which decipher the sensor data. These signals specify the precise action that the actuator must do in order to accomplish the intended result.
|
||||
|
||||
- **Responsive and Adaptive Actions:** Vehicles that use actuators can be made to be both responsive and adaptable. When an obstruction is detected, responsive actions take rapid action, such as automated braking. Adaptive actions, like adaptive cruise control, which modifies vehicle speed based on traffic circumstances, change over time based on continuous sensor data.
|
||||
|
||||
In conclusion, the modern vehicle's intelligence is defined by the combination of sensing and actuation. Actuators implement the necessary modifications to maximize safety, performance, and efficiency, while sensors offer a thorough understanding of the surroundings and the condition of the vehicle.
|
||||
|
||||
### Historical Development of Automotive Sensors and Actuators
|
||||
|
||||
When one looks at the realm of sensing and actuation, the evolution of the automobile is a fascinating tapestry of engineering achievements and discoveries.
|
||||
|
||||
#### Evolution of Sensing Technologies in Vehicles
|
||||
|
||||
The early autos' basic mechanical and electro-mechanical systems are where sensing in cars first appeared.
|
||||
|
||||
- **Mechanical Era:** The nascent stages of automotive development predominantly employed mechanical systems. An example of an early speedometer was a cable-driven device that sent speed through a rotating cable and was directly attached to the gearbox.
|
||||
|
||||
- **Electro-Mechanical Onset:** Transitioning into the 20th century, electro-mechanical components began surfacing. For instance, bimetallic strips and Bourdon tubes were utilized in temperature and oil pressure gauges, respectively.
|
||||
|
||||
- **Electronic Revolution:** Thanks to developments in semiconductor technologies, electronic sensing saw a boom after the 1970s. The advent of sensors such as oxygen sensors, manifold absolute pressure sensors, and throttle position sensors during this era laid the foundation for advanced engine management and electronic fuel injection systems.
|
||||
|
||||
- **Advent of ADAS and Connectivity:** Advanced driver-assistance systems (ADAS) were introduced in the late 20th and early 21st centuries. Advances in autonomous driving, collision avoidance, and lane departure warning systems were made possible by technological innovations, including radar, LIDAR, and cameras.
|
||||
|
||||
#### Trends and Future Directions
|
||||
|
||||
The scope of sensing and actuation in the automobile industry is expanding in step with the constant advancement of technology.
|
||||
|
||||
- **Miniaturization and Integration:** Miniaturization is a trend in modern sensors, making them smaller without compromising on functionality. Integrated sensor systems are increasingly widely used; they combine several sensing functions into a single unit.
|
||||
|
||||
- **Self-Diagnostics and Predictive Maintenance:** The upcoming generation of sensors and actuators are not only operational devices but also self-aware. They are able to keep an eye on their performance, anticipate malfunctions, and notify the driver or the car's central system of possible problems.
|
||||
|
||||
- **Holistic Vehicle Sensing:** An automobile that senses its environment holistically is the automotive industry's vision of the future. To ensure peak performance, safety, and comfort, a confluence of internal and external sensors must cooperate.
|
||||
|
||||
- **Actuators in Electric and Autonomous Vehicles:** With electric cars (EVs) gaining pace, specialized actuators customized for EVs are on the horizon. Actuators will also become increasingly important as autonomous driving technologies advance, guaranteeing precise, split-second responses to sensor input.
|
||||
|
||||
- **Material Innovations:** Actuators can now respond faster, with greater precision, and for longer periods of time thanks to new materials including shape-memory alloys and piezoelectric compounds.
|
||||
|
||||
---
|
||||
|
||||
## 2. Types and Functions of Sensors in Automotive Systems
|
||||
|
||||
### Classification of Automotive Sensors
|
||||
|
||||
Automotive sensors are essential to the smooth operation of modern automobiles. These sensors provide information about numerous vehicle parameters to the Electronic Control Unit (ECU) so that safety, efficiency, and performance are maximized. They do this by translating physical quantities into electrical impulses. These sensors can be categorized along two main lines: first, by the physical characteristics they measure, and second, by the underlying technology they use.
|
||||
|
||||
#### Classification Based on Physical Properties
|
||||
|
||||
- **Pressure Sensors:** These devices identify and gauge the pressure of the car's various fluids, including air, fuel, and oil. They make sure that the pressures stay within predetermined limits for ideal functioning and are frequently utilized in fuel injection and brake systems. They are predicated either on differential pressure sensing or absolute pressure sensing theory.
|
||||
|
||||
- **Temperature Sensors:** Integral to engine management, temperature sensors monitor the engine's coolant, oil, and air temperatures. By doing this, possible harm is avoided and the engine is guaranteed to run within a safe temperature range. Furthermore, temperature sensors are integrated into all power electronic controllers so that, in the event that the temperature rises above safe limits, the power can be derated or switched off.
|
||||
|
||||
- **Position Sensors:** These sensors determine where different parts are located. Examples are the Camshaft/Crankshaft Position Sensors, which help with engine timing, and the Throttle Position Sensor (TPS), which senses the position of the throttle in internal combustion engines.
|
||||
|
||||
- **Speed Sensors:** These sensors detect the rotational speed of the wheels and axis and are frequently used in the Anti-lock Braking System (ABS) and Transmission Control Units (TCU). This information enables the ECU, for example, to make real-time changes to prevent wheel lockup while braking.
|
||||
|
||||
- **Level Sensors:** These sensors keep an eye on the fluid levels in a variety of reservoirs, such as engine oil sump pumps, braking fluid reservoirs, and gasoline tanks.
|
||||
|
||||
#### Classification Based on Technology
|
||||
|
||||
- **Capacitive Sensors:** When a physical quantity varies, they work on the basis of capacitance alteration. In capacitive proximity sensors, for example, an object's approach modifies the capacitance, which is then detected. Certain fluid-level sensors rely on the fluid's capacitance.
|
||||
|
||||
- **Ultrasonic Sensors:** These sensors produce ultrasonic waves and are mostly utilized in parking assistance and obstacle detection. The sensor measures the distance by measuring the time it takes for the waves to reflect back after hitting an obstruction and receiving the information.
|
||||
|
||||
- **Infrared Sensors:** These sensors use the infrared spectrum to detect obstacles and provide night vision, particularly in low-light situations.
|
||||
|
||||
- **Piezoelectric Sensors:** These sensors produce a voltage in response to mechanical stress. Engine knock sensors use this feature to identify engine knock or pinging.
|
||||
|
||||
- **Hall-Effect Sensors:** Operating on the principle of the Hall Effect, these sensors can detect magnetic fields and are commonly employed for position detection, notably in the context of camshaft and crankshaft positions.
|
||||
|
||||
- **Resistive Sensors:** These sensors, such as temperature sensors, whose resistance varies inversely with temperature, alter their resistance in response to the physical quantity they detect.
|
||||
|
||||
### Applications of Sensors in Automotive Systems
|
||||
|
||||
#### Engine Management and Control
|
||||
|
||||
The engine management system's core components are the sensors, they enable peak performance, fuel economy, and emission control:
|
||||
|
||||
- **Fuel/Air Mixture Control:** By measuring the amount of oxygen in exhaust gasses through the use of oxygen sensors installed inside the exhaust system, the engine control module is able to modify the fuel-air mixture for the best possible combustion.
|
||||
|
||||
- **Ignition Timing:** Crankshaft and camshaft position sensors help establish the engine's phase and speed. This information helps the engine control unit (ECU) to time the spark for combustion exactly.
|
||||
|
||||
- **Cooling System:** Temperature sensors monitor the engine's coolant temperature. If the temperature crosses a defined threshold, the ECU can modify the functioning of the cooling fan or communicate a potential overheating issue to the driver.
|
||||
|
||||
- **Turbocharger Control:** Pressure sensors are used in turbocharged engines to monitor the boost pressure and ensure that it remains within the safe operating parameters established for the engine.
|
||||
|
||||
#### Safety Systems
|
||||
|
||||
Safety is fundamental in vehicle design, and sensors play a critical part in numerous safety-enhancing systems:
|
||||
|
||||
- **Airbag Deployment:** Accelerometers detect fast deceleration characteristics of a collision. The sensor alerts the airbag control unit to activate the airbags, which cushion the occupants and lower the possibility of injury in the event of a large accident.
|
||||
|
||||
- **Anti-Lock Braking System (ABS):** Wheel speed sensors constantly track the rotational speed of each wheel in the anti-lock braking system (ABS). The ABS adjusts brake pressure to prevent wheel lockup when it senses it is about to happen, preserving steering control.
|
||||
|
||||
- **Traction Control System:** This system detects when one or more wheels lose grip by using wheel speed sensors. In order to regain traction, the ECU can then lower engine power or apply brake force to particular wheels.
|
||||
|
||||
- **Collision Sensors:** These are particularly crucial for battery electric vehicles (BEVs), as they ensure that all high-voltage parts are deactivated in the event of a collision. This is accomplished via the collision sensor circuit, which modifies the crash signal state that high-voltage components expect in the case of a crash and ensures that any circuits that may have become accessible to persons due to the collision and vehicle damage are de-energized.
|
||||
|
||||
#### Driver-Assistance Systems
|
||||
|
||||
- **Parking Assistance:** This is provided by ultrasonic sensors installed all around the car to identify nearby obstructions. By giving the driver input regarding the distance to objects, these sensors help make parking in confined places easier to handle.
|
||||
|
||||
- **Lane-Keeping Assistance:** Roadside lane markers are detected by optical or infrared sensors. Depending on how sophisticated the system is, it may alert the driver or even take corrective action if it detects an inadvertent lane departure without signaling.
|
||||
|
||||
- **Adaptive Cruise Control:** This technology keeps a safe following distance between itself and the car in front of you using radar or LIDAR sensors. The mechanism automatically lowers speed to preserve the predetermined gap if the car in front of it slows down.
|
||||
|
||||
- **Blind Spot Detection:** This system lowers the likelihood of side-swiping accidents by alerting drivers to cars in their blind spots, usually through the use of radar or ultrasonic sensors.
|
||||
|
||||
### Key Specifications and Performance Criteria
|
||||
|
||||
#### Accuracy and Resolution
|
||||
|
||||
- **Accuracy:** This indicates the degree to which the sensor's reading agrees with the real value. A temperature sensor that is precise to within 0.5°C of the real temperature, for example, is more reliable than one that could be 2°C off.
|
||||
|
||||
- **Resolution:** The smallest change in the quantity being measured that causes the related output signal to alter noticeably is referred to as this. For example, a pressure sensor is said to have 0.01 psi resolution if it can measure variations as small as 0.01 psi.
|
||||
|
||||
#### Sensitivity and Range
|
||||
|
||||
- **Sensitivity:** This is defined as the sensor's response, or change in output, to a change in the input or amount being measured.
|
||||
|
||||
- **Range:** The physical quantity that the sensor is capable of measuring is shown, along with its minimum and maximum values.
|
||||
|
||||
#### Environmental Considerations
|
||||
|
||||
- **Temperature Stability:** Because cars operate in a variety of conditions, sensors need to be able to function accurately and consistently across a wide temperature range.
|
||||
|
||||
- **Resistance to Contaminants:** To ensure lifetime and reliable operation, automotive sensors should be resistant to fuel, oil, dust, moisture, and other contaminants.
|
||||
|
||||
- **Vibration Resistance:** Cars can cause a lot of vibrations and shock, especially in rough terrain. For constant readings, sensors must be unaffected by these vibrations.
|
||||
|
||||
#### Type of Sensor Errors
|
||||
|
||||
- **Offset Error:** An ongoing inaccuracy injected into the sensor data.
|
||||
- **Gain Error:** Errors proportionate to the input signal are called gain errors.
|
||||
- **Drift Error:** Errors that gradually change over time.
|
||||
- **Random Error:** Typically indicative of noise in the sensor circuit, random errors lack a clear pattern.
|
||||
- **Quantization Error:** This kind of error is caused by the sensor's restricted resolution.
|
||||
|
||||
#### Fault Diagnostics
|
||||
|
||||
Modern car systems have built-in self-diagnostic features to keep an eye on the condition and performance of their sensors.
|
||||
|
||||
- **5V Output Sensors:** Sensors with a 5-volt output voltage range frequently use the lower voltage band (below 0.5V) and upper voltage band (above 4.5V) to indicate a fault.
|
||||
|
||||
- **Digital Temperature Sensors:** High safety-rated temperature sensors frequently display a false, implausible temperature value, such as -200°C, to signify that a chip internal problem has occurred.
|
||||
|
||||
#### Detection of Faults
|
||||
|
||||
- **Redundancy:** Making use of several sensors to make a single measurement.
|
||||
- **Self-Test Mechanisms:** Modern sensors are equipped with self-test functions.
|
||||
- **Plausibility Checks:** Comparing sensor outputs to established physical models to make sure they are consistent.
|
||||
|
||||
---
|
||||
|
||||
## 3. Types and Functions of Actuators in Automotive Systems
|
||||
|
||||
### Classification of Automotive Actuators
|
||||
|
||||
In automotive systems, actuators operate as a conduit between the physical actions occurring inside a car and the control systems. They convert incoming energy into motion in order to carry out commands.
|
||||
|
||||
#### Classification Based on Control Action
|
||||
|
||||
**Linear Actuators**
|
||||
- **Description:** These actuators produce linear motion, usually in the form of push or pull actions.
|
||||
- **Application:** An example of an application is the operation of the brake master cylinder, in which the hydraulic fluid is pushed through the system by the actuator to engage the brake pads.
|
||||
|
||||
**Rotary Actuators**
|
||||
- **Description:** These produce rotational motion, which is usually expressed in terms of angles or whole revolutions.
|
||||
- **Application:** An example of an application is the fuel injection system's throttle plate adjustment, where the actuator spins the plate to regulate airflow. The liquid-cooled systems pressure pump serves as an additional illustration.
|
||||
|
||||
#### Classification Based on Technology
|
||||
|
||||
**Electric Motors**
|
||||
- **Description:** Produce motion by means of electrical energy. Their working principle is based on electromagnetic principles, in which motion is produced by a magnetic field created by current flowing through a coil.
|
||||
- **Application:** One example of such application is electric power steering systems, which, in response to driver input, use motors to help in steering.
|
||||
|
||||
**Solenoids**
|
||||
- **Description:** These are electromagnetic devices that, when powered on, create a regulated magnetic field. Subsequently, a plunger or rod experiences linear motion due to the magnetic field.
|
||||
- **Application:** An example of an application is transmission shift control, in which a solenoid engages or disengages gears in response to commands from the driver or computer.
|
||||
|
||||
**Piezoelectric Actuators**
|
||||
- **Description:** Use the piezoelectric effect. When mechanical stress is applied, some materials generate an electric charge. In contrast, these materials undergo a shape-changing process that results in mechanical motion when voltage is given to them.
|
||||
- **Application:** Fuel injector systems in some sophisticated engines. Because of their high-frequency response, piezoelectric actuators can provide injections that are extremely rapid and precise.
|
||||
|
||||
### Applications with Actuators in Automotive Systems
|
||||
|
||||
#### Throttle Control
|
||||
|
||||
- **Role of Actuators:** The throttle actuator controls how much air enters the engine. In the past, this operation was mainly mechanical. On the other hand, "drive-by-wire" or electronic throttle control (ETC) systems are used in modern systems.
|
||||
- **How It Works:** Rather than physically pulling a cable, depressing the gas pedal in an ETC system delivers an electrical signal. This signal is interpreted by an actuator at the throttle body, which then modifies the throttle plate to control engine airflow.
|
||||
|
||||
#### Transmission Shift Control
|
||||
|
||||
- **Role of Actuators:** In both automated and manual transmission systems, transmission actuators help with gear shifting.
|
||||
- **How It Works:** Solenoid actuators in contemporary automatic transmissions decode electrical signals from the transmission control module. By regulating the hydraulic fluid flow to various transmission tunnels, these solenoids regulate which gear set is in operation.
|
||||
|
||||
#### Active Suspension Systems
|
||||
|
||||
- **Role of Actuators:** Active suspensions are cutting-edge devices that instantly adjust to changing road conditions and driving demands to improve handling dynamics and ride comfort.
|
||||
- **How It Works:** The system uses a mix of actuators and sensors to identify cornering forces, vehicle speed, and road defects. Actuators quickly change the ride height or damper stiffness. They are typically electromagnetic or electro-hydraulic.
|
||||
|
||||
### Key Specifications and Performance Criteria
|
||||
|
||||
#### Force and Torque Capabilities
|
||||
|
||||
- **Definition:** Two essential indicators of an actuator's performance are force and torque. Torque, which is typically linked with rotary actuators, represents rotational force, whereas force is a push or pull action that is linear in nature.
|
||||
- **Measurement:** Generally, torque is expressed in Newton-meters (Nm) or foot-pounds (ft-lb), while force is expressed in Newton's (N) or pounds-force (lbf).
|
||||
|
||||
#### Speed and Response Time
|
||||
|
||||
- **Definition:** Response time is the amount of time an actuator takes to begin moving after receiving a command, whereas speed is the fastest an actuator may move to reach its desired location.
|
||||
- **Measurement:** For linear motions, speed can be stated in mm/sec, while for rotating actuators, it can be given in RPM. Milliseconds (ms) are commonly used to indicate response time.
|
||||
|
||||
#### Reliability and Durability
|
||||
|
||||
- **Definition:** Durability is the number of operational cycles an actuator can withstand before wearing out or malfunctioning, whereas reliability is the capacity to perform consistently over time without failure.
|
||||
- **Measurement:** While durability may be described in terms of operating cycles or hours of operation under specific conditions, reliability is frequently measured using metrics like Mean Time Between Failures (MTBF).
|
||||
|
||||
---
|
||||
|
||||
## 4. Power Management for Sensors and Actuators
|
||||
|
||||
### Power Requirements for Sensors and Actuators
|
||||
|
||||
#### Operating Voltage and Current Ranges
|
||||
|
||||
- **Definition:** Specific voltage and current ranges are intended for the operation of each sensor and actuator.
|
||||
- **Importance:** Staying within these parameters guarantees that the sensor or actuator operates as intended without running the risk of damage or malfunction.
|
||||
- **Measurement:** Common operating voltages for automotive applications may be between 5V and 24V.
|
||||
|
||||
#### Power Consumption and Efficiency
|
||||
|
||||
- **Definition:** Power consumption measures the total amount of energy that a sensor or actuator uses over time. Efficiency quantifies how well a device transforms the power it consumes into useful output.
|
||||
- **Importance:** Energy is a limited resource in automobiles, particularly in electric or hybrid versions.
|
||||
- **Factors Affecting Consumption and Efficiency:** The device's design, the materials utilized, the working environment, and operation frequency.
|
||||
- **Measurement:** For smaller devices, power consumption is commonly expressed in milliwatts (mW) or watts (W). Efficiency is the ratio of usable power output to total power input, stated as a percentage.
|
||||
|
||||
### Power Optimization Strategies
|
||||
|
||||
#### Power-Saving Modes for Sensors
|
||||
|
||||
- **Sleep Mode:** In sleep mode, the sensor uses very little power and is largely inactive. It can become "awakened" when its purpose is required.
|
||||
- **Idle Mode:** The sensor keeps working but at a reduced capacity, ready to go back to full operation when needed.
|
||||
- **Interrupt-Driven Mode:** Until an external trigger or interrupt activates the sensor, it stays in low-power mode.
|
||||
|
||||
#### Always-Awake Sensors in Vehicles
|
||||
|
||||
- **Theft-Detection Sensors:** They keep a close eye out for any indications of tampering or illegal access.
|
||||
- **Key Fob Detection Sensors:** These sensors are always on the lookout for signals from the key fob in cars with keyless entry systems.
|
||||
|
||||
#### Energy Efficient Actuation Techniques
|
||||
|
||||
- **Adaptive Control:** The actuator modifies its actions in response to immediate feedback.
|
||||
- *Variable Displacement Pumps:* Modify the fluid flow rate in accordance with the system's present requirements.
|
||||
- *Dynamic Brake Energy Recovery:* The energy generated during braking is recovered and transformed back into useful electrical energy.
|
||||
- *Electric Motors with Load Sensing:* The motor can adjust its power output according to the required torque.
|
||||
- **Pulse-Width Modulation (PWM):** Enables more precise control over the amount of energy utilized by altering the width of the electrical pulse delivered to the actuator.
|
||||
- **Optimized Drive Circuits:** Energy efficiency can be achieved in the design of the electronic circuits that drive actuators.
|
||||
- **Variable Load Sensing:** Certain sophisticated actuators have the ability to detect the load they are experiencing and modify their energy usage accordingly.
|
||||
|
||||
---
|
||||
|
||||
## 5. Integration and Interfacing of Sensors and Actuators
|
||||
|
||||
### Sensor and Actuator Interfaces
|
||||
|
||||
#### Analog vs. Digital Interfaces
|
||||
|
||||
**Analog Interfaces**
|
||||
- **Nature:** Use a continuous signal that fluctuates in frequency or amplitude to transmit data.
|
||||
- **Pros:** They offer a clear representation of a measured or controlled quantity and can be easy to use and reasonably priced.
|
||||
- **Cons:** Limited range and susceptibility to noise interference. The connecting ECU must supply a distinct sensor ground specifically for that sensor.
|
||||
- **Usage:** Commonly seen in simple sensors like pressure or temperature sensors.
|
||||
|
||||
**Digital Interfaces**
|
||||
- **Nature:** Discrete signals, mostly binary (0s and 1s), are used to transmit data.
|
||||
- **Pros:** They provide accurate and strong noise immunity.
|
||||
- **Cons:** Their cost is usually higher than that of analog sensors. They require additional computational power from the DSPs and microcontroller interface.
|
||||
- **Usage:** Common in contemporary automobile systems where accurate control and data collection are essential.
|
||||
|
||||
#### Communication Protocols for Sensors
|
||||
|
||||
**Inter-Integrated Circuit (I²C)**
|
||||
- A packet-switched, single-ended, multi-master, multi-slave serial communication protocol. Frequently used to connect slower peripheral integrated circuits (ICs) to microcontrollers and processors.
|
||||
- **Example:** Ambient light sensors in cars.
|
||||
|
||||
**Single-Edge Nibble Transmission (SENT)**
|
||||
- A point-to-point protocol that allows sensor readings to be sent from a controller to a sensor. Designed with low power consumption and the fewest possible sensor connection pins.
|
||||
- **Example:** Throttle position sensors.
|
||||
|
||||
**One-Wire**
|
||||
- This protocol just needs one wire to communicate. Intended for low-speed data transmission.
|
||||
- **Example:** Tire pressure monitoring sensors.
|
||||
|
||||
**Serial Peripheral Interface (SPI)**
|
||||
- A synchronous serial communication protocol that selects the target device using a select line in addition to distinct clock and data lines.
|
||||
- **Example:** High-speed gyroscopic sensors used in advanced stability control systems.
|
||||
|
||||
**Controller Area Network (CAN)**
|
||||
- A common protocol for higher-level vehicle communications. Reliable, able to function in noisy settings, and appropriate for real-time applications.
|
||||
- **Example:** Wheel speed sensors for ABS and traction control.
|
||||
|
||||
**Local Interconnect Network (LIN)**
|
||||
- For non-critical sub-networks inside a car, a more affordable option to CAN.
|
||||
- **Example:** Rain or light-detecting modules.
|
||||
|
||||
### Integration Challenges and Solutions
|
||||
|
||||
#### Ensuring Compatibility Between Components
|
||||
|
||||
**Challenge:** The variety of sensors and actuators that may originate from different manufacturers, different eras of technology, or different design paradigms.
|
||||
|
||||
**Solutions:**
|
||||
- **Standardization:** Using standardized interfaces, voltages, and communication protocols (SAE, ISO standards).
|
||||
- **ISO:** ISO 14229, ISO 15765 (vehicular communication), ISO 26262 (functional safety).
|
||||
- **SAE:** SAE J1979 (OBD systems), SAE J1939 (heavy-duty communication).
|
||||
- **Interfacing Modules:** Use interface modules or gateways that can translate between different protocols.
|
||||
- **Unified Development Platforms:** Develop and test on the same platform or environment.
|
||||
- **Comprehensive Documentation:** Keep detailed documentation for every component.
|
||||
|
||||
### Procedures for Sensors and Actuators
|
||||
|
||||
#### Sensor Calibration
|
||||
|
||||
- **Procedure:** Recording the sensor's reaction after subjecting it to a variety of known situations. The output is modified to match the anticipated values.
|
||||
- **Example:** A temperature sensor may be subjected to a range of exact temperatures while modifications are made to guarantee that its output corresponds to the input values that are known.
|
||||
|
||||
#### Actuator Calibration
|
||||
|
||||
- **Procedure:** Change the control signal that is supplied to the actuator, measure its reaction, and make adjustments as needed to get the desired result.
|
||||
- **Example:** To make sure a solenoid delivers the appropriate force or displacement for each level, it may be driven at different current levels. The correlation between current and displacement can be used as an integrated look-up table in the DSP or Microcontroller of the ECU.
|
||||
|
||||
---
|
||||
|
||||
*Сохранено с MPScholar (Monolithic Power Systems) — Automotive Electronics / Automotive Sensing and Actuators*
|
||||
@@ -0,0 +1,60 @@
|
||||
# Мнение по анализу динамического сбоя ELM327
|
||||
|
||||
Дата: 2026-06-14
|
||||
|
||||
## Общая оценка
|
||||
|
||||
Анализ написан правильно. Методология верная: исключение невозможного через уже проведённые эксперименты (паузы 4000 мс, автоподбор таймингов), затем ранжирование оставшихся гипотез. Главный вывод — проблема не в скорости, а в чтении потока — звучит убедительно.
|
||||
|
||||
---
|
||||
|
||||
## Что поддерживаю
|
||||
|
||||
**Гипотезы 1–3 (вероятность: высокая)** — расставлены верно.
|
||||
|
||||
Из трёх наиболее вероятных причин **непрочитанный `>` в InputStream** — самая классическая ELM327-ловушка. Если ScriptEngine завершает чтение по таймауту или по числу строк вместо `>`, это объясняет всё: первый запрос проходит, потому что `>` ещё не накапливается, второй ломается из-за хвоста. Это надо проверять первым.
|
||||
|
||||
**Buffer drain перед send, а не только после receive** — часто игнорируемое место. Если drain делается только после чтения, но перед отправкой нового запроса остаток `>` или пустая строка ещё лежат в буфере — это незаметно даже в логах, если читать только "полезные" байты.
|
||||
|
||||
---
|
||||
|
||||
## Что добавил бы
|
||||
|
||||
### 1. NO DATA / UNABLE TO CONNECT в динамике
|
||||
|
||||
В анализе не рассмотрен сценарий, когда в ходе динамики ELM вернул `NO DATA` или `UNABLE TO CONNECT`. Это вполне реально при смене контекста CAN. Если ScriptEngine на такой ответ зависает в ожидании данных или некорректно парсит следующий ответ — результат идентичен описанному сбою. Стоит явно проверить, как ScriptEngine обрабатывает негативные ответы ELM, и логировать их.
|
||||
|
||||
### 2. AT ST (тайм-аут ELM) может различаться между режимами
|
||||
|
||||
Если ElmChecker и ScriptEngine отправляют разные значения `AT ST` (или один вообще не устанавливает его), ELM сам будет обрезать ответ или отвечать с разной задержкой. При высокой нагрузке ECU (динамика) тайм-аут ELM по умолчанию (200 мс) может быть недостаточен, и ELM уйдёт в `NO DATA` раньше, чем ECU ответил. Нужно убедиться, что `AT ST FF` (максимальный) или фиксированное значение установлены одинаково в обоих путях.
|
||||
|
||||
### 3. Клон ELM327 vs оригинал
|
||||
|
||||
Клоны (особенно v1.5 китайские) имеют известный баг: при высокой частоте запросов они перестают выдавать `>` — промпт появляется только после задержки или вообще пропадает. Если адаптер — клон, нужно явно учесть это при трактовке сырых логов: отсутствие `>` может быть аппаратным поведением, а не ошибкой кода.
|
||||
|
||||
### 4. Конкурентный доступ — недооценённый риск
|
||||
|
||||
Гипотезе 5 (два потока на сокет) поставлена средняя вероятность, но в Android-проектах это случается чаще, чем кажется. Достаточно одного фонового alive-check, который читает тот же InputStream в момент динамического цикла. Стоит выйти не только на проверку thread id, но и на `synchronized`-блоки или single-threaded executor для всех операций с сокетом.
|
||||
|
||||
---
|
||||
|
||||
## Что менее убедительно
|
||||
|
||||
**Гипотеза 6 (порядок команд)** — оценка "средняя-низкая" верна, но её стоит проверять параллельно с гипотезами 1–3, не последовательно: это дёшево (достаточно дампа команд) и может мгновенно закрыть вопрос или исключить этот класс причин.
|
||||
|
||||
---
|
||||
|
||||
## Порядок расследования (скорректированный)
|
||||
|
||||
1. **Сырой RX/TX лог** с явным маркером `>` — сравнить статику и динамику. Первый приоритет.
|
||||
2. **Проверить обработку негативных ответов** (`NO DATA`, `UNABLE TO CONNECT`) в ScriptEngine.
|
||||
3. **Сравнить AT-последовательности** ElmChecker и ScriptEngine — весь init, включая `AT ST`.
|
||||
4. **Убедиться в drain перед send**, а не только после receive.
|
||||
5. **Thread id на каждый read/write** — исключить второй consumer.
|
||||
6. **Дамп команд** обоих режимов — закрыть гипотезу 6 параллельно с остальными.
|
||||
|
||||
---
|
||||
|
||||
## Итог
|
||||
|
||||
Анализ хороший. Главное не растягивать расследование на последовательное прохождение всех гипотез: сырой лог с маркером `>` и лог негативных ответов ELM — два дешёвых эксперимента, которые скорее всего сразу покажут, где рвётся синхронизация.
|
||||
@@ -0,0 +1,113 @@
|
||||
# Резюме проекта elmAI — 14 июня 2026
|
||||
|
||||
## Текущая версия: v1.18.0-dev
|
||||
|
||||
## Архитектура
|
||||
|
||||
**Сервер (Python/Flask):** `gitea.services.ngcloud.ru/Nail/elmer`, ветка `bugfix-2026-06-07`
|
||||
- Хост: `obdai.ru` (5.172.178.213), доступ по SSH: `ssh -i ~/.ssh/naeel_vm_id_ed25519 naeel@5.172.178.213`
|
||||
- Репо на сервере: `/opt/elmer`, сервис `elmer` (gunicorn), nginx прокси
|
||||
|
||||
**Android (Kotlin):** `github.com/Repinoid/elmer-android`, ветка `bugfix-2026-06-07`
|
||||
- APK собирается на сервере: `export ANDROID_SDK_ROOT=$HOME/android-sdk && cd /opt/elmer/android && ./gradlew clean assembleDebug`
|
||||
- APK на сайте: `web/static/app-debug.apk` → `https://obdai.ru/elmer.apk`
|
||||
|
||||
## Что работает ✅
|
||||
|
||||
1. **Статическая диагностика** — одиночные PID (0104-011F), DTC, VIN — ИДЕАЛЬНО
|
||||
2. **Speed-test** — замер задержек RPM/MAF/STFT при клике на 🔵 ELM (если нет профиля)
|
||||
3. **Серверный тестовый скрипт** — `GET /api/v1/script?mode=test`
|
||||
4. **Авто-подбор таймингов** — `POST /api/v1/test/next` — сервер получает результаты, увеличивает wait_ms если ошибок >20%
|
||||
|
||||
## Что НЕ работает ❌
|
||||
|
||||
1. **Динамический тест (СТАРТ/СТОП)** — ELM327 v1.5 замолкает после первых 1-2 команд. Статика работает, динамика нет. Причина не найдена.
|
||||
|
||||
## Ключевые файлы
|
||||
|
||||
### Сервер
|
||||
| Файл | Что |
|
||||
|------|-----|
|
||||
| `api/routes.py` | `?mode=test`, `POST /api/v1/test/next`, авто-подбор |
|
||||
| `api/scripts.py` | `build_test_script(wait_ms, pids, repeat)` |
|
||||
| `api/db.py` | `device_profiles` таблица с `response_time_ms` |
|
||||
| `api/ping.py` | ping/ping-llm эндпоинты |
|
||||
|
||||
### Android
|
||||
| Файл | Что |
|
||||
|------|-----|
|
||||
| `elm/ElmProtocol.kt` | Стейт-машина AndrOBD. `MAX_RETRIES=3`, `state=ERROR` убран |
|
||||
| `elm/ElmChecker.kt` | checkDevice, checkEcu, speed-test, quickCheck |
|
||||
| `script/DynamicCollector.kt` | Оригинальный DynamicCollector (не используется сейчас) |
|
||||
| `script/ScriptEngine.kt` | Выполнение скриптов с сервера, поддержка `wait` |
|
||||
| `server/ServerClient.kt` | `downloadTestScript()`, `postTestNext()` |
|
||||
| `ui/MainActivity.kt` | `startDynamicRecording()` — авто-подбор с сервера |
|
||||
|
||||
## Логика авто-подбора (v1.17+)
|
||||
|
||||
```
|
||||
Пользователь: СТАРТ
|
||||
↓
|
||||
Статика 9 PID (как обычно)
|
||||
↓
|
||||
Цикл 1: GET /api/v1/script?mode=test → wait=2000ms, 2 PID (010C,0106), 8 повторов
|
||||
↓ выполняет
|
||||
↓ POST /api/v1/test/next {run:0, results:[...]}
|
||||
↓ ответ: {done:false, message:"50% ошибок — увеличиваю до 2500ms"}
|
||||
↓
|
||||
Цикл 2: wait=2500ms → выполняет → POST → ответ
|
||||
↓
|
||||
... пока done:true или run≥5
|
||||
```
|
||||
|
||||
## Деплой
|
||||
|
||||
### Только сервер (без APK):
|
||||
```bash
|
||||
cd /home/naeel/elmer
|
||||
git add -A && git commit -m "..." && git push origin bugfix-2026-06-07
|
||||
ssh -i ~/.ssh/naeel_vm_id_ed25519 naeel@5.172.178.213 'cd /opt/elmer && git pull origin bugfix-2026-06-07 && sudo systemctl restart elmer'
|
||||
```
|
||||
|
||||
### APK + сервер:
|
||||
```bash
|
||||
# Бамп версии в android/app/build.gradle.kts и web/templates/index.html
|
||||
# Затем:
|
||||
cd /home/naeel/elmer/android
|
||||
git add -A && git commit -m "..." && git push origin bugfix-2026-06-07
|
||||
|
||||
cd /home/naeel/elmer
|
||||
git add -A && git commit -m "bump vX.Y.Z-dev" && git push origin bugfix-2026-06-07
|
||||
|
||||
cd /home/naeel/elmer
|
||||
tar czf /tmp/android-src.tar.gz --exclude='.git' --exclude='build' --exclude='.gradle' android/
|
||||
scp -i ~/.ssh/naeel_vm_id_ed25519 /tmp/android-src.tar.gz naeel@5.172.178.213:/tmp/
|
||||
ssh -i ~/.ssh/naeel_vm_id_ed25519 naeel@5.172.178.213 '\
|
||||
cd /opt/elmer && git pull origin bugfix-2026-06-07 && \
|
||||
export ANDROID_SDK_ROOT=$HOME/android-sdk && export ANDROID_HOME=$ANDROID_SDK_ROOT && \
|
||||
rm -rf android && tar xzf /tmp/android-src.tar.gz -C /opt/elmer/ && \
|
||||
cd android && ./gradlew clean assembleDebug && \
|
||||
cp app/build/outputs/apk/debug/app-debug.apk /opt/elmer/web/static/'
|
||||
```
|
||||
|
||||
## Нерешённая проблема
|
||||
|
||||
ELM327 v1.5 замолкает при последовательных OBD-командах. Статика (одиночные) — ок. Динамика (подряд) — пустые ответы. Уже пробовали:
|
||||
- Разные паузы (250ms → 4000ms) — не помогает
|
||||
- ATWS перед динамикой — делает хуже
|
||||
- Убирали/возвращали drainInput() — v1.9 без drain хуже
|
||||
- Retry в exec() — оригинальный AndrOBD код не помогает
|
||||
- Разное количество PID — не помогает
|
||||
- DynamicCollector → серверный скрипт — не помогает
|
||||
|
||||
Текущий авто-подбор должен найти рабочий интервал, но если даже 4000ms не помогает — проблема глубже таймингов.
|
||||
|
||||
## Конфигурация авто-подбора (api/routes.py)
|
||||
- Старт: 2000ms
|
||||
- Шаг: +500ms
|
||||
- Макс: 5 циклов
|
||||
- PIDs: 010C (RPM), 0106 (STFT)
|
||||
- Повторов: 6
|
||||
|
||||
## Профиль ELM
|
||||
Таблица `device_profiles` в `elmer.db`. MAC: `AA:BB:CC:11:22:33`. Был удалён старый мусорный профиль.
|
||||
@@ -0,0 +1,251 @@
|
||||
"""
|
||||
obd/raw_console.py — Сырой слой ELM327 (без стейт-машины).
|
||||
|
||||
НИКАКОЙ логики протокола:
|
||||
- Нет state machine (State)
|
||||
- Нет классификации ответов (Rsp)
|
||||
- Нет адаптивных таймингов (AdaptiveTiming)
|
||||
- Нет ретраев
|
||||
- Нет хендлеров ошибок
|
||||
|
||||
ТОЛЬКО:
|
||||
- send(cmd) → отправляет команду + CR
|
||||
- read(timeout) → читает ВСЁ до '>' или таймаута, байт-за-байтом
|
||||
- drain() → очищает входной буфер
|
||||
- available() → сколько байт ждёт в буфере
|
||||
|
||||
ПРЕДНАЗНАЧЕНИЕ:
|
||||
Изучение реального поведения ELM327.
|
||||
«Почему статика работает, а динамика ломается?»
|
||||
Ответ — в сырых байтах.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
logger = logging.getLogger("elm.raw")
|
||||
|
||||
# ── Конфигурация по умолчанию (можно переопределить) ──
|
||||
DEFAULT_TIMEOUT = 500 # мс
|
||||
INTER_CMD_DELAY = 0.05 # с — пауза между командой и чтением
|
||||
|
||||
|
||||
class RawELM:
|
||||
"""Сырой слой ELM327 — только send/read/drain, без протокольной логики."""
|
||||
|
||||
def __init__(self, transport):
|
||||
"""
|
||||
Args:
|
||||
transport: объект с методами .write(str) и .read(timeout_ms) → str
|
||||
(обычно SerialTransport из obd.connection)
|
||||
"""
|
||||
self._t = transport
|
||||
self._timeout = DEFAULT_TIMEOUT
|
||||
self._inter_delay = INTER_CMD_DELAY
|
||||
self._log: list[dict] = [] # история команд
|
||||
|
||||
# ── Настройка ────────────────────────────────────
|
||||
|
||||
@property
|
||||
def timeout(self) -> int:
|
||||
return self._timeout
|
||||
|
||||
@timeout.setter
|
||||
def timeout(self, ms: int):
|
||||
self._timeout = ms
|
||||
|
||||
@property
|
||||
def inter_delay(self) -> float:
|
||||
return self._inter_delay
|
||||
|
||||
@inter_delay.setter
|
||||
def inter_delay(self, sec: float):
|
||||
self._inter_delay = sec
|
||||
|
||||
# ── Основные операции ────────────────────────────
|
||||
|
||||
def send(self, cmd: str, timeout: int | None = None) -> dict:
|
||||
"""Отправить команду и прочитать сырой ответ.
|
||||
|
||||
Args:
|
||||
cmd: команда (без \r, добавится автоматически)
|
||||
timeout: таймаут в мс (None = использовать self.timeout)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"cmd": str, # что отправили
|
||||
"raw": str, # сырой ответ (без '>')
|
||||
"prompt": bool, # получен ли '>'
|
||||
"elapsed_ms": int, # сколько мс заняло
|
||||
"bytes": int, # сколько байт в ответе
|
||||
"error": str|None, # ошибка если есть
|
||||
}
|
||||
|
||||
Не бросает исключений — всегда возвращает dict с полем error.
|
||||
"""
|
||||
tmo = timeout if timeout is not None else self._timeout
|
||||
entry = {"cmd": cmd, "timeout_ms": tmo, "ts": time.time()}
|
||||
|
||||
try:
|
||||
# 1. Отправить
|
||||
self._t.write(cmd)
|
||||
|
||||
# 2. Пауза (ELM начинает отвечать не мгновенно)
|
||||
if self._inter_delay > 0:
|
||||
time.sleep(self._inter_delay)
|
||||
|
||||
# 3. Прочитать
|
||||
t0 = time.monotonic()
|
||||
raw, prompt, nbytes = self._read_raw(tmo)
|
||||
elapsed = int((time.monotonic() - t0) * 1000)
|
||||
|
||||
entry.update({
|
||||
"raw": raw,
|
||||
"prompt": prompt,
|
||||
"elapsed_ms": elapsed,
|
||||
"bytes": nbytes,
|
||||
"error": None,
|
||||
})
|
||||
except TimeoutError:
|
||||
entry.update({
|
||||
"raw": "",
|
||||
"prompt": False,
|
||||
"elapsed_ms": tmo,
|
||||
"bytes": 0,
|
||||
"error": f"timeout {tmo}ms",
|
||||
})
|
||||
except Exception as e:
|
||||
entry.update({
|
||||
"raw": "",
|
||||
"prompt": False,
|
||||
"elapsed_ms": 0,
|
||||
"bytes": 0,
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
self._log.append(entry)
|
||||
return entry
|
||||
|
||||
def drain(self) -> dict:
|
||||
"""Очистить входной буфер. Возвращает что было выброшено.
|
||||
|
||||
Returns:
|
||||
{"drained": str, "bytes": int}
|
||||
"""
|
||||
t0 = time.monotonic()
|
||||
drained = []
|
||||
total = 0
|
||||
dl = t0 + 0.5 # 500 мс максимум на дренаж
|
||||
while time.monotonic() < dl:
|
||||
try:
|
||||
ch = self._read_byte(0.05)
|
||||
if ch is not None:
|
||||
drained.append(chr(ch))
|
||||
total += 1
|
||||
else:
|
||||
break # буфер пуст
|
||||
except Exception:
|
||||
break
|
||||
elapsed = int((time.monotonic() - t0) * 1000)
|
||||
result = {"drained": "".join(drained), "bytes": total, "elapsed_ms": elapsed}
|
||||
if total > 0:
|
||||
logger.info(f"RawELM: drained {total} bytes: {result['drained']!r}")
|
||||
return result
|
||||
|
||||
def available(self) -> int:
|
||||
"""Сколько байт ждёт во входном буфере (0 = пусто)."""
|
||||
try:
|
||||
return self._t._ser.in_waiting
|
||||
except Exception:
|
||||
return -1
|
||||
|
||||
# ── Лог ──────────────────────────────────────────
|
||||
|
||||
@property
|
||||
def log(self) -> list[dict]:
|
||||
"""История всех команд."""
|
||||
return self._log
|
||||
|
||||
def clear_log(self):
|
||||
"""Очистить историю."""
|
||||
self._log.clear()
|
||||
|
||||
def last(self) -> dict | None:
|
||||
"""Последняя команда."""
|
||||
return self._log[-1] if self._log else None
|
||||
|
||||
# ── Приватные ────────────────────────────────────
|
||||
|
||||
def _read_raw(self, timeout_ms: int) -> tuple[str, bool, int]:
|
||||
"""Читает байт-за-байтом до '>' или таймаута.
|
||||
|
||||
Returns:
|
||||
(raw_text, got_prompt, byte_count)
|
||||
"""
|
||||
dl = time.monotonic() + timeout_ms / 1000.0
|
||||
lines, cur = [], []
|
||||
got_prompt = False
|
||||
|
||||
while time.monotonic() < dl:
|
||||
ch = self._read_byte(0.05)
|
||||
if ch is None:
|
||||
continue
|
||||
cp = ch
|
||||
|
||||
if cp == 62: # '>' — промпт ELM327
|
||||
if cur:
|
||||
lines.append("".join(cur))
|
||||
cur.clear()
|
||||
got_prompt = True
|
||||
break
|
||||
elif cp == 13: # CR — конец строки
|
||||
if cur:
|
||||
lines.append("".join(cur))
|
||||
cur.clear()
|
||||
elif cp in (10, 32): # LF и пробел — игнорируем
|
||||
pass
|
||||
else:
|
||||
cur.append(chr(cp))
|
||||
|
||||
if cur:
|
||||
lines.append("".join(cur))
|
||||
|
||||
return ("\n".join(lines), got_prompt, sum(len(s) for s in lines))
|
||||
|
||||
def _read_byte(self, timeout_s: float) -> int | None:
|
||||
"""Прочитать один байт с таймаутом. None = таймаут/нет данных."""
|
||||
import serial
|
||||
try:
|
||||
if self._t._ser.in_waiting > 0:
|
||||
b = self._t._ser.read(1)
|
||||
return b[0] if b else None
|
||||
else:
|
||||
time.sleep(0.001) # поллинг 1мс
|
||||
return None
|
||||
except serial.SerialException:
|
||||
return None
|
||||
|
||||
|
||||
# ── Хелпер ───────────────────────────────────────────
|
||||
|
||||
def format_response(entry: dict) -> str:
|
||||
"""Форматирует ответ RawELM.send() для вывода в консоль."""
|
||||
lines = [
|
||||
f"→ {entry['cmd']}",
|
||||
f"← {entry['raw']!r}" if entry["raw"] else "← (пусто)",
|
||||
]
|
||||
if entry["prompt"]:
|
||||
lines.append(" prompt: ✅ >")
|
||||
else:
|
||||
lines.append(" prompt: ❌")
|
||||
lines.append(f" time: {entry['elapsed_ms']}ms, bytes: {entry['bytes']}")
|
||||
if entry["error"]:
|
||||
lines.append(f" ⚠️ {entry['error']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def format_log(entries: list[dict]) -> str:
|
||||
"""Форматирует всю историю команд."""
|
||||
return "\n" + "─" * 50 + "\n" + \
|
||||
"\n".join(format_response(e) for e in entries) + \
|
||||
"\n" + "─" * 50
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
import sqlite3, json
|
||||
db = sqlite3.connect("/opt/elmer/elmer.db")
|
||||
for sid in [41, 40]:
|
||||
r = db.execute("SELECT id, created_at, raw_responses FROM sessions WHERE id=?", (sid,)).fetchone()
|
||||
print(f"\n=== SESSION #{r[0]} {r[1]} ===")
|
||||
if not r[2]: print(" (no raw data)"); continue
|
||||
data = json.loads(r[2])
|
||||
print(f" Total responses: {len(data)}")
|
||||
cmds = {}
|
||||
for d in data:
|
||||
c = d.get("cmd","?")
|
||||
s = d.get("step_id","?")
|
||||
raw = d.get("raw","")
|
||||
dec = d.get("decoded","")
|
||||
key = f"{s} ({c})"
|
||||
if key not in cmds:
|
||||
cmds[key] = {"cnt": 0, "err": 0, "empty": 0, "ok": 0, "samples": []}
|
||||
cmds[key]["cnt"] += 1
|
||||
if not raw or raw in ["?","(err)","NO DATA"]:
|
||||
cmds[key]["err"] += 1
|
||||
elif raw == "":
|
||||
cmds[key]["empty"] += 1
|
||||
else:
|
||||
cmds[key]["ok"] += 1
|
||||
if len(cmds[key]["samples"]) < 2:
|
||||
cmds[key]["samples"].append(f"{raw} -> {dec}")
|
||||
for k, v in sorted(cmds.items()):
|
||||
print(f" {k:30s} total={v['cnt']:3d} ok={v['ok']} err={v['err']} empty={v['empty']}")
|
||||
for s in v["samples"]:
|
||||
print(f" {s}")
|
||||
db.close()
|
||||
Executable
+298
@@ -0,0 +1,298 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
elm_console.py — Интерактивная консоль ELM327 (сырой режим).
|
||||
|
||||
НИКАКОЙ автоматики:
|
||||
- Нет init(), probe(), send() со стейт-машиной
|
||||
- Нет классификации ответов
|
||||
- Нет адаптивных таймингов
|
||||
|
||||
ТОЛЬКО вы вводите команду — ELM отвечает сырыми байтами.
|
||||
|
||||
ЗАПУСК:
|
||||
python tools/elm_console.py # порт по умолчанию /dev/rfcomm0
|
||||
python tools/elm_console.py --port /dev/rfcomm0 # явно указать порт
|
||||
python tools/elm_console.py --baud 38400 # другая скорость
|
||||
python tools/elm_console.py --timeout 1000 # таймаут 1с
|
||||
python tools/elm_console.py --no-init # не слать AT-инит
|
||||
|
||||
КОМАНДЫ КОНСОЛИ:
|
||||
ATZ — отправить "ATZ" в ELM
|
||||
0105 — отправить "0105" (PID coolant temp)
|
||||
!drain — очистить входной буфер
|
||||
!timeout 2000 — установить таймаут 2000 мс
|
||||
!delay 0.5 — пауза между командой и чтением (сек)
|
||||
!log — показать историю команд
|
||||
!available — сколько байт в буфере
|
||||
!save file.json — сохранить лог в файл
|
||||
!help — справка
|
||||
!quit — выход
|
||||
|
||||
ЦЕЛЬ:
|
||||
Понять, КАК на самом деле работает ELM327.
|
||||
Почему статика работает, а динамика ломается?
|
||||
Ответ — в сырых байтах.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import cmd
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# Добавляем корень проекта в PYTHONPATH
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from obd.connection import SerialTransport
|
||||
from obd.raw_console import RawELM, format_response, format_log
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG,
|
||||
format="%(asctime)s [%(name)s] %(message)s",
|
||||
datefmt="%H:%M:%S",
|
||||
)
|
||||
|
||||
logger = logging.getLogger("elm.console")
|
||||
|
||||
|
||||
class ElmConsole(cmd.Cmd):
|
||||
"""Интерактивная консоль ELM327."""
|
||||
|
||||
intro = """
|
||||
╔══════════════════════════════════════════════════════╗
|
||||
║ ELM327 Raw Console ║
|
||||
║ Сырое взаимодействие — без стейт-машины ║
|
||||
║ Команды: ATZ, 0105, !drain, !help, !quit ║
|
||||
╚══════════════════════════════════════════════════════╝
|
||||
"""
|
||||
prompt = "\nelm> "
|
||||
|
||||
def __init__(self, port: str, baudrate: int, timeout: int, delay: float, no_init: bool):
|
||||
super().__init__()
|
||||
self._port = port
|
||||
self._baud = baudrate
|
||||
self._no_init = no_init
|
||||
self._transport = None
|
||||
self._elm: RawELM | None = None
|
||||
|
||||
# ── Подключение ─────────────────────────────────
|
||||
|
||||
def connect(self):
|
||||
"""Открыть порт и создать RawELM."""
|
||||
print(f"🔌 Подключение к {self._port} @ {self._baud}...")
|
||||
try:
|
||||
self._transport = SerialTransport(self._port, self._baud)
|
||||
self._transport.connect()
|
||||
except Exception as e:
|
||||
print(f"❌ Не удалось открыть порт: {e}")
|
||||
print(" Проверь: bash scripts/setup-bt.sh")
|
||||
return False
|
||||
|
||||
self._elm = RawELM(self._transport)
|
||||
print(f"✅ Порт открыт. RawELM готов.")
|
||||
print(f" Таймаут: {self._elm.timeout}ms, пауза: {self._elm.inter_delay}s")
|
||||
print(f" Буфер: {self._elm.available()} байт")
|
||||
|
||||
if not self._no_init:
|
||||
print("\n📡 Быстрая проверка связи (ATZ)...")
|
||||
r = self._elm.send("ATZ", timeout=3000)
|
||||
print(format_response(r))
|
||||
if r["error"]:
|
||||
print("⚠️ ELM327 не ответил на ATZ. Проверь питание адаптера.")
|
||||
print(" Продолжаем, но команды могут не работать.")
|
||||
|
||||
return True
|
||||
|
||||
def close(self):
|
||||
"""Закрыть порт."""
|
||||
if self._transport:
|
||||
self._transport.close()
|
||||
print("🔌 Порт закрыт.")
|
||||
|
||||
# ── cmd.Cmd overrides ────────────────────────────
|
||||
|
||||
def default(self, line: str):
|
||||
"""Любая не-! команда = отправить в ELM327."""
|
||||
cmd_str = line.strip()
|
||||
if not cmd_str:
|
||||
return
|
||||
|
||||
if cmd_str.startswith("!"):
|
||||
print(f"Неизвестная команда: {cmd_str}. !help для списка.")
|
||||
return
|
||||
|
||||
# Отправить в ELM
|
||||
result = self._elm.send(cmd_str)
|
||||
print(format_response(result))
|
||||
|
||||
def emptyline(self):
|
||||
"""Пустая строка — ничего не делаем."""
|
||||
pass
|
||||
|
||||
# ── Специальные команды (!) ──────────────────────
|
||||
|
||||
def do_drain(self, arg):
|
||||
"""!drain — очистить входной буфер ELM327."""
|
||||
r = self._elm.drain()
|
||||
if r["bytes"] > 0:
|
||||
print(f"🗑 Выброшено {r['bytes']} байт: {r['drained']!r}")
|
||||
else:
|
||||
print("✅ Буфер пуст.")
|
||||
|
||||
def do_timeout(self, arg):
|
||||
"""!timeout <ms> — установить таймаут чтения."""
|
||||
try:
|
||||
ms = int(arg.strip())
|
||||
self._elm.timeout = ms
|
||||
print(f"⏱ Таймаут: {ms}ms")
|
||||
except ValueError:
|
||||
print(f"❌ Нужно число: !timeout 2000")
|
||||
|
||||
def do_delay(self, arg):
|
||||
"""!delay <sec> — пауза между командой и чтением."""
|
||||
try:
|
||||
sec = float(arg.strip())
|
||||
self._elm.inter_delay = sec
|
||||
print(f"⏱ Пауза: {sec}s")
|
||||
except ValueError:
|
||||
print(f"❌ Нужно число: !delay 0.5")
|
||||
|
||||
def do_log(self, arg):
|
||||
"""!log [N] — показать последние N команд (по умолчанию все)."""
|
||||
entries = self._elm.log
|
||||
if not entries:
|
||||
print("📭 Лог пуст.")
|
||||
return
|
||||
|
||||
try:
|
||||
n = int(arg.strip()) if arg.strip() else len(entries)
|
||||
except ValueError:
|
||||
n = len(entries)
|
||||
|
||||
to_show = entries[-n:] if n < len(entries) else entries
|
||||
print(format_log(to_show))
|
||||
print(f"Всего: {len(entries)} команд.")
|
||||
|
||||
def do_available(self, arg):
|
||||
"""!available — сколько байт в буфере."""
|
||||
n = self._elm.available()
|
||||
if n < 0:
|
||||
print("⚠️ Не удалось проверить буфер (порт закрыт?).")
|
||||
elif n == 0:
|
||||
print("✅ Буфер пуст.")
|
||||
else:
|
||||
print(f"📥 В буфере: {n} байт.")
|
||||
|
||||
def do_save(self, arg):
|
||||
"""!save <file.json> — сохранить лог в JSON."""
|
||||
path = arg.strip()
|
||||
if not path:
|
||||
print("❌ Укажи имя файла: !save log.json")
|
||||
return
|
||||
try:
|
||||
with open(path, "w") as f:
|
||||
json.dump(self._elm.log, f, indent=2, default=str)
|
||||
print(f"💾 Сохранено: {path} ({len(self._elm.log)} команд)")
|
||||
except Exception as e:
|
||||
print(f"❌ Ошибка: {e}")
|
||||
|
||||
def do_raw(self, arg):
|
||||
"""!raw — показать последний ответ в repr (все символы)."""
|
||||
last = self._elm.last()
|
||||
if not last:
|
||||
print("📭 Нет команд.")
|
||||
return
|
||||
print(f"raw = {last['raw']!r}")
|
||||
print(f"prompt = {last['prompt']}")
|
||||
print(f"elapsed = {last['elapsed_ms']}ms")
|
||||
print(f"bytes = {last['bytes']}")
|
||||
|
||||
def do_help(self, arg):
|
||||
"""!help — справка."""
|
||||
print("""
|
||||
╔══════════════════════════════════════════════════════╗
|
||||
║ КОМАНДЫ ELM327 (вводи как есть): ║
|
||||
║ ATZ — сброс ║
|
||||
║ ATI — идентификация ║
|
||||
║ ATE0 — echo off ║
|
||||
║ ATL0 — linefeeds off ║
|
||||
║ ATS0 — spaces off ║
|
||||
║ ATH1 — headers on ║
|
||||
║ ATSP0 — авто-протокол ║
|
||||
║ ATRV — напряжение ║
|
||||
║ ATDPN — номер протокола ║
|
||||
║ 0105 — температура ОЖ (PID) ║
|
||||
║ 010C — обороты ║
|
||||
║ 010D — скорость ║
|
||||
║ 03 — сохранённые DTC ║
|
||||
║ 07 — pending DTC ║
|
||||
║ 0902 — VIN ║
|
||||
║ ║
|
||||
║ КОМАНДЫ КОНСОЛИ (с !): ║
|
||||
║ !drain — очистить буфер ║
|
||||
║ !timeout N — таймаут (ms) ║
|
||||
║ !delay N — пауза перед чтением (s) ║
|
||||
║ !log [N] — история команд ║
|
||||
║ !raw — последний ответ в repr ║
|
||||
║ !available — байт в буфере ║
|
||||
║ !save f.json — сохранить лог ║
|
||||
║ !help — эта справка ║
|
||||
║ !quit — выход ║
|
||||
╚══════════════════════════════════════════════════════╝
|
||||
""")
|
||||
|
||||
def do_quit(self, arg):
|
||||
"""!quit — выход."""
|
||||
print("👋")
|
||||
self.close()
|
||||
return True
|
||||
|
||||
def do_exit(self, arg):
|
||||
"""!exit — то же что !quit."""
|
||||
return self.do_quit(arg)
|
||||
|
||||
# Сокращения
|
||||
do_q = do_quit
|
||||
do_h = do_help
|
||||
do_d = do_drain
|
||||
do_t = do_timeout
|
||||
do_l = do_log
|
||||
do_a = do_available
|
||||
|
||||
|
||||
# ── main ─────────────────────────────────────────────
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="ELM327 Raw Console — интерактивное сырое взаимодействие"
|
||||
)
|
||||
parser.add_argument("--port", default="/dev/rfcomm0", help="Порт (default: /dev/rfcomm0)")
|
||||
parser.add_argument("--baud", type=int, default=38400, help="Скорость (default: 38400)")
|
||||
parser.add_argument("--timeout", type=int, default=500, help="Таймаут чтения ms (default: 500)")
|
||||
parser.add_argument("--delay", type=float, default=0.05, help="Пауза перед чтением s (default: 0.05)")
|
||||
parser.add_argument("--no-init", action="store_true", help="Не слать ATZ при старте")
|
||||
args = parser.parse_args()
|
||||
|
||||
console = ElmConsole(
|
||||
port=args.port,
|
||||
baudrate=args.baud,
|
||||
timeout=args.timeout,
|
||||
delay=args.delay,
|
||||
no_init=args.no_init,
|
||||
)
|
||||
|
||||
if not console.connect():
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
console.cmdloop()
|
||||
except KeyboardInterrupt:
|
||||
print("\n👋")
|
||||
finally:
|
||||
console.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+270
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
elm_relay.py — Интерактивная консоль для удалённого управления ELM327 через Android.
|
||||
|
||||
Работает через HTTP-очередь на сервере:
|
||||
1. Ставит команду → POST /api/v1/elm/raw/cmd
|
||||
2. Ждёт ответ → GET /api/v1/elm/raw/response?wait=N
|
||||
3. Показывает сырой ответ
|
||||
4. Анализирует → следующая команда
|
||||
|
||||
ЗАПУСК:
|
||||
python3 tools/elm_relay.py # сервер по умолчанию http://localhost:5005
|
||||
python3 tools/elm_relay.py --server https://obdai.ru
|
||||
python3 tools/elm_relay.py --timeout 1000 # таймаут команд 1000мс
|
||||
|
||||
ИНТЕРАКТИВНЫЕ КОМАНДЫ:
|
||||
ATZ — отправить "ATZ"
|
||||
0105 — отправить PID
|
||||
!status — статус устройства
|
||||
!history [N] — последние N ответов
|
||||
!drain — очистить буфер (ATPC)
|
||||
!mode raw — включить raw-режим на сервере
|
||||
!mode normal — выключить
|
||||
!timeout N — таймаут команд (мс)
|
||||
!help — справка
|
||||
!quit — выход
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import cmd
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
DEFAULT_SERVER = "http://localhost:5005"
|
||||
|
||||
|
||||
class ElmRelay(cmd.Cmd):
|
||||
"""Интерактивная консоль для удалённого ELM327."""
|
||||
|
||||
intro = """
|
||||
╔══════════════════════════════════════════════════════╗
|
||||
║ ELM327 Remote Relay Console ║
|
||||
║ Сервер → Android → ELM327 → ответ → анализ ║
|
||||
║ !help для списка команд ║
|
||||
╚══════════════════════════════════════════════════════╝
|
||||
"""
|
||||
prompt = "\nelm-relay> "
|
||||
|
||||
def __init__(self, server: str, timeout: int):
|
||||
super().__init__()
|
||||
self.server = server.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self._last_seq = 0
|
||||
|
||||
# ── Отправка команд ──────────────────────────────
|
||||
|
||||
def default(self, line: str):
|
||||
"""Любая не-! команда → отправить в ELM327."""
|
||||
cmd_str = line.strip()
|
||||
if not cmd_str:
|
||||
return
|
||||
if cmd_str.startswith("!"):
|
||||
print(f"Неизвестная команда: {cmd_str}")
|
||||
return
|
||||
|
||||
self._send_and_wait(cmd_str)
|
||||
|
||||
def _send_and_wait(self, cmd: str, drain_first: bool = False):
|
||||
"""Поставить команду в очередь и дождаться ответа."""
|
||||
# 1. Отправить команду
|
||||
try:
|
||||
enq = self._post("/api/v1/elm/raw/cmd", {
|
||||
"cmd": cmd,
|
||||
"timeout_ms": self.timeout,
|
||||
"drain_first": drain_first,
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"❌ Ошибка отправки: {e}")
|
||||
return
|
||||
|
||||
seq = enq.get("seq", 0)
|
||||
print(f"→ {cmd} (seq={seq}, timeout={self.timeout}ms)")
|
||||
|
||||
# 2. Ждать ответ
|
||||
try:
|
||||
resp = self._get(f"/api/v1/elm/raw/response?wait=30&seq={self._last_seq}")
|
||||
except Exception as e:
|
||||
print(f"❌ Ошибка ожидания: {e}")
|
||||
return
|
||||
|
||||
self._last_seq = resp.get("seq", seq)
|
||||
|
||||
# 3. Показать
|
||||
self._print_response(resp)
|
||||
|
||||
# ── Вывод ответа ──────────────────────────────────
|
||||
|
||||
def _print_response(self, r: dict):
|
||||
raw = r.get("raw", "")
|
||||
prompt = r.get("prompt", False)
|
||||
elapsed = r.get("elapsed_ms", 0)
|
||||
nbytes = r.get("bytes", 0)
|
||||
error = r.get("error")
|
||||
|
||||
print(f"← {raw!r}" if raw else "← (пусто)")
|
||||
status = []
|
||||
if prompt:
|
||||
status.append("✅ >")
|
||||
else:
|
||||
status.append("❌ нет >")
|
||||
status.append(f"{elapsed}ms")
|
||||
status.append(f"{nbytes}B")
|
||||
if error:
|
||||
status.append(f"⚠️ {error}")
|
||||
print(f" {' | '.join(status)}")
|
||||
|
||||
# ── Специальные команды ───────────────────────────
|
||||
|
||||
def do_status(self, arg):
|
||||
"""!status — статус устройства."""
|
||||
try:
|
||||
s = self._get("/api/v1/elm/raw/status")
|
||||
except Exception as e:
|
||||
print(f"❌ {e}")
|
||||
return
|
||||
print(f"Устройство: {'✅ готово' if s.get('device_ready') else '❌ не подключено'}")
|
||||
info = s.get("device_info", {})
|
||||
if info:
|
||||
print(f" ID: {info.get('device_id', '?')}")
|
||||
print(f" ELM: {info.get('elm_version', '?')}")
|
||||
print(f" Протокол: {info.get('protocol', '?')}")
|
||||
print(f" Напряжение: {info.get('voltage', '?')}")
|
||||
print(f"Очередь: {'есть команда' if s.get('pending_cmd') else 'пусто'}")
|
||||
print(f"Последний seq: {s.get('last_response_seq', 0)}")
|
||||
print(f"История: {s.get('history_count', 0)} команд")
|
||||
|
||||
def do_history(self, arg):
|
||||
"""!history [N] — последние N ответов."""
|
||||
try:
|
||||
n = int(arg.strip()) if arg.strip() else 10
|
||||
except ValueError:
|
||||
n = 10
|
||||
try:
|
||||
h = self._get(f"/api/v1/elm/raw/history?n={n}")
|
||||
except Exception as e:
|
||||
print(f"❌ {e}")
|
||||
return
|
||||
items = h.get("history", [])
|
||||
if not items:
|
||||
print("📭 История пуста.")
|
||||
return
|
||||
print(f"Последние {len(items)} из {h.get('total', 0)}:\n")
|
||||
for r in items:
|
||||
seq = r.get("seq", "?")
|
||||
cmd = r.get("cmd", "?")
|
||||
raw = (r.get("raw") or "")[:60]
|
||||
elapsed = r.get("elapsed_ms", 0)
|
||||
prompt = "✅>" if r.get("prompt") else "❌"
|
||||
error = f" ⚠️{r['error']}" if r.get("error") else ""
|
||||
print(f" #{seq} → {cmd} ← {raw}{'…' if len(r.get('raw',''))>60 else ''} ({elapsed}ms, {prompt}){error}")
|
||||
|
||||
def do_drain(self, arg):
|
||||
"""!drain — попросить Android очистить буфер ELM327."""
|
||||
self._send_and_wait("ATPC", drain_first=False)
|
||||
print("🗑 Буфер очищен.")
|
||||
|
||||
def do_mode(self, arg):
|
||||
"""!mode raw|normal — переключить режим сервера."""
|
||||
mode = arg.strip().lower()
|
||||
if mode not in ("raw", "normal"):
|
||||
print("❌ !mode raw или !mode normal")
|
||||
return
|
||||
on = mode == "raw"
|
||||
try:
|
||||
self._post("/api/v1/elm/raw/mode", {"raw_mode": on})
|
||||
print(f"✅ Режим: {'RAW' if on else 'NORMAL'}")
|
||||
except Exception as e:
|
||||
print(f"❌ {e}")
|
||||
|
||||
def do_timeout(self, arg):
|
||||
"""!timeout N — таймаут команд (мс)."""
|
||||
try:
|
||||
self.timeout = int(arg.strip())
|
||||
print(f"⏱ Таймаут: {self.timeout}ms")
|
||||
except ValueError:
|
||||
print(f"❌ Нужно число: !timeout 1000")
|
||||
|
||||
def do_help(self, arg):
|
||||
"""!help — справка."""
|
||||
print("""
|
||||
╔══════════════════════════════════════════════════════╗
|
||||
║ ELM327 КОМАНДЫ (вводи как есть): ║
|
||||
║ ATZ ATI ATE0 ATL0 ATS0 ║
|
||||
║ ATH1 ATSP0 ATRV ATDPN ATSTxx ║
|
||||
║ 0105 (ОЖ) 010C (RPM) 010D (Speed) ║
|
||||
║ 03 (DTC) 07 (pending) 0902 (VIN) ║
|
||||
║ ║
|
||||
║ КОНСОЛЬ: ║
|
||||
║ !status — статус устройства ║
|
||||
║ !history [N] — последние ответы ║
|
||||
║ !drain — очистить буфер ║
|
||||
║ !mode raw — включить raw-режим ║
|
||||
║ !timeout N — таймаут команд ║
|
||||
║ !help — эта справка ║
|
||||
║ !quit — выход ║
|
||||
╚══════════════════════════════════════════════════════╝
|
||||
""")
|
||||
|
||||
def do_quit(self, arg):
|
||||
print("👋")
|
||||
return True
|
||||
|
||||
def do_exit(self, arg):
|
||||
return self.do_quit(arg)
|
||||
|
||||
do_q = do_quit
|
||||
do_h = do_help
|
||||
do_s = do_status
|
||||
|
||||
# ── HTTP-хелперы ──────────────────────────────────
|
||||
|
||||
def _get(self, path: str) -> dict:
|
||||
url = f"{self.server}{path}"
|
||||
req = urllib.request.Request(url)
|
||||
with urllib.request.urlopen(req, timeout=35) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
|
||||
def _post(self, path: str, data: dict) -> dict:
|
||||
url = f"{self.server}{path}"
|
||||
body = json.dumps(data).encode()
|
||||
req = urllib.request.Request(url, data=body,
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST")
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
|
||||
|
||||
# ── main ─────────────────────────────────────────────
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="ELM327 Remote Relay Console — удалённое управление через Android"
|
||||
)
|
||||
parser.add_argument("--server", default=DEFAULT_SERVER, help=f"URL сервера (default: {DEFAULT_SERVER})")
|
||||
parser.add_argument("--timeout", type=int, default=500, help="Таймаут команд ms (default: 500)")
|
||||
args = parser.parse_args()
|
||||
|
||||
console = ElmRelay(server=args.server, timeout=args.timeout)
|
||||
|
||||
# Проверим связь с сервером
|
||||
try:
|
||||
s = console._get("/api/v1/elm/raw/status")
|
||||
ready = s.get("device_ready", False)
|
||||
print(f"Сервер: {args.server}")
|
||||
print(f"Устройство: {'✅ готово' if ready else '❌ не подключено (запусти Android-приложение)'}")
|
||||
except Exception as e:
|
||||
print(f"⚠️ Сервер недоступен: {e}")
|
||||
print(f" Проверь: curl {args.server}/api/v1/ping")
|
||||
|
||||
try:
|
||||
console.cmdloop()
|
||||
except KeyboardInterrupt:
|
||||
print("\n👋")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+24
@@ -22,6 +22,7 @@ from api.config import load
|
||||
from api.routes import register as register_api
|
||||
from api.dtc import register as register_dtc
|
||||
from api.ping import register as register_ping
|
||||
from api.raw_elm import bp as raw_bp, is_raw_mode
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(name)s] %(message)s")
|
||||
|
||||
@@ -30,6 +31,23 @@ config = load()
|
||||
register_api(app)
|
||||
register_dtc(app)
|
||||
register_ping(app)
|
||||
app.register_blueprint(raw_bp)
|
||||
|
||||
# ── Режим RAW: отключаем все эндпоинты кроме /elm/raw/* ──
|
||||
_RAW_PREFIX = "/api/v1/elm/raw"
|
||||
|
||||
@app.before_request
|
||||
def _check_raw_mode():
|
||||
"""В режиме RAW все эндпоинты кроме /elm/raw/* отключены."""
|
||||
if is_raw_mode() and not request.path.startswith(_RAW_PREFIX):
|
||||
# Разрешаем только статику и корень
|
||||
if request.path not in ("/", "/elmer.apk") and not request.path.startswith("/static"):
|
||||
return jsonify({
|
||||
"error": "raw_mode_active",
|
||||
"hint": "Сервер в режиме сырого взаимодействия с ELM327. "
|
||||
"Все остальные эндпоинты отключены. "
|
||||
"Используйте /api/v1/elm/raw/mode чтобы выключить."
|
||||
}), 503
|
||||
|
||||
|
||||
@app.route("/")
|
||||
@@ -44,6 +62,12 @@ def download_apk():
|
||||
return send_from_directory("static", "app-debug.apk", as_attachment=True, download_name="elmer.apk")
|
||||
|
||||
|
||||
@app.route("/elm-raw.apk")
|
||||
def download_raw_apk():
|
||||
"""Прямая ссылка на APK Raw Relay."""
|
||||
return send_from_directory("static", "elm-raw.apk", as_attachment=True, download_name="elm-raw.apk")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"🌐 elmAI Web: http://localhost:5005")
|
||||
app.run(host="0.0.0.0", port=5005, debug=False)
|
||||
|
||||
@@ -64,7 +64,7 @@ def register(app):
|
||||
def upload_session():
|
||||
from flask import request, jsonify
|
||||
from elmer.config import load
|
||||
from elmer.db import Database
|
||||
from api.db import Database
|
||||
from elmer.diagnose import Diagnoser
|
||||
from elmer.prompts import SYSTEM_PROMPT
|
||||
|
||||
|
||||
@@ -13,14 +13,22 @@
|
||||
<img src="/static/logo.png" alt="elmAI" style="width:96px;height:96px;border-radius:20px;margin-bottom:10px;">
|
||||
<h1>elmAI</h1>
|
||||
<p class="subtitle">Диагностика авто через ELM327 + ИИ</p>
|
||||
<p class="subtitle" style="font-size:12px;opacity:0.7;">v0.78.0-dev — 7 июня 2026</p>
|
||||
<p class="subtitle" style="font-size:12px;opacity:0.7;">v1.18.0-dev — 7 июня 2026</p>
|
||||
|
||||
<div class="card" style="text-align:center;margin-bottom:20px;">
|
||||
<p style="margin:0 0 10px 0;">📱 Скачай приложение на телефон:</p>
|
||||
<a href="/static/app-debug.apk" style="color:#ff6b35;font-size:18px;font-weight:bold;text-decoration:none;">
|
||||
<a href="/elmer.apk" style="color:#ff6b35;font-size:18px;font-weight:bold;text-decoration:none;">
|
||||
⬇️ Скачать elmAI APK
|
||||
</a>
|
||||
<p style="font-size:11px;opacity:0.6;margin:4px 0 0 0;">v0.78.0-dev • нажмите чтобы скачать</p>
|
||||
<p style="font-size:11px;opacity:0.6;margin:4px 0 0 0;">v1.18.0-dev • основное приложение</p>
|
||||
</div>
|
||||
|
||||
<div class="card" style="text-align:center;margin-bottom:20px;background:#1a1a2e;">
|
||||
<p style="margin:0 0 10px 0;">🔧 Отладка ELM327:</p>
|
||||
<a href="/static/elm-raw.apk" style="color:#00ff88;font-size:18px;font-weight:bold;text-decoration:none;">
|
||||
⬇️ Скачать ELM Raw Relay
|
||||
</a>
|
||||
<p style="font-size:11px;opacity:0.6;margin:4px 0 0 0;">v0.1.1-dev • ретранслятор команд</p>
|
||||
</div>
|
||||
|
||||
<!-- Кнопка десктоп-диагностики скрыта — только для разработчика с прямым ELM327 -->
|
||||
|
||||
Reference in New Issue
Block a user