feat(match): 同步比赛计时与装甲板扣血许可
- feat(client): 增加裁判比赛计时、技术暂停与选手端局域网同步 - feat(armor): 红蓝共用通用固件,按客户端选队并显示网络连接状态 - feat(armor): 仅在对局进行中允许扣血,其他阶段保留受击闪烁 - feat(client): 将计时置于血条中间并增加开赛前五秒全屏动画 - fix(client): 修复连续血条、对手镜像和图传断连灰度遮罩 - fix(client): 统一界面中文字体并整理各页面文案 - fix(maintenance): 备份迁移装甲板分区,恢复 SDK 构建与固件打包 - refactor(repo): 按 armor、vt 和 client 整理工程与脚本,移除旧参考实现 - test: 补充线路、受击许可、回环 UDP、维护和 HUD 验证 - docs: 同步构建、协议、比赛控制和硬件验证边界 验证:前端构建与 19 项相关测试通过;核心 91 项单元测试与 2 项回环 UDP 集成测试通过;装甲板规则 25 项、线路 26 项、Tauri 51 项测试通过;独立探测器 5 项与目录回归 4 项通过。完成 C3 两组阈值实际编译、导出与 ZIP 校验,检查 900×600 / 1280×720 页面、倒计时和随包中文字体。 未执行烧录、板上运行、跨电脑广播或硬件稳定性验证。
This commit is contained in:
581 files changed
+6596
-7683
No files matched your search
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize opt-in client marker reports using explicit, half-open row ranges."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
|
||||
|
||||
def describe(values):
|
||||
ordered = sorted(values)
|
||||
if not ordered:
|
||||
raise ValueError('No valid marker samples in the selected range')
|
||||
return {
|
||||
'count': len(ordered),
|
||||
'mean': statistics.mean(ordered),
|
||||
'p50': statistics.median(ordered),
|
||||
'p95': ordered[int((len(ordered)-1)*.95)],
|
||||
'p99': ordered[int((len(ordered)-1)*.99)],
|
||||
'minimum': ordered[0],
|
||||
'maximum': ordered[-1],
|
||||
}
|
||||
|
||||
|
||||
def summarize(rows, selection):
|
||||
start, end = selection['start_row'], selection['end_row']
|
||||
if not 0 <= start < end <= len(rows):
|
||||
raise ValueError('Range must select complete rows from the report')
|
||||
samples = rows[start:end]
|
||||
seen = set()
|
||||
for sample in samples:
|
||||
if not all(isinstance(v, (int, float)) and math.isfinite(v) for v in sample.values()):
|
||||
raise ValueError('Sample contains a nonfinite value')
|
||||
if not 0 <= sample['lowerMs'] <= sample['upperMs'] <= 5000:
|
||||
raise ValueError('Invalid refresh bracket')
|
||||
key = (sample['counter'], sample['sourceDrawMs'])
|
||||
if key in seen:
|
||||
raise ValueError('A source marker was counted more than once')
|
||||
seen.add(key)
|
||||
return {
|
||||
**selection,
|
||||
'samples': len(samples),
|
||||
'sample_span_seconds': (samples[-1]['drawMs']-samples[0]['drawMs'])/1000,
|
||||
'marker_event_to_paint_ms': describe([(s['lowerMs']+s['upperMs'])/2 for s in samples]),
|
||||
'lower_bound_ms': describe([s['lowerMs'] for s in samples]),
|
||||
'upper_bound_ms': describe([s['upperMs'] for s in samples]),
|
||||
'refresh_bracket_width_ms': describe([s['upperMs']-s['lowerMs'] for s in samples]),
|
||||
'decoded_to_draw_ms': describe([s['decodeToDrawMs'] for s in samples]),
|
||||
'marker_analysis_ms': describe([s['analysisMs'] for s in samples]),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--report', type=Path, required=True)
|
||||
parser.add_argument('--range', type=Path, action='append', required=True, dest='ranges')
|
||||
parser.add_argument('--out', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
rows = [json.loads(line) for line in args.report.read_text().splitlines() if line.strip()]
|
||||
trials = [summarize(rows, json.loads(path.read_text())) for path in args.ranges]
|
||||
result = {
|
||||
'method': '50 ms source marker events; first decodable echo on production VideoSurface; midpoint of adjacent-rAF brackets',
|
||||
'scope': 'Source-screen marker to camera exposure/capture, Wi-Fi/UDP, native reassembly, local WebSocket, JPEG decode and canvas draw',
|
||||
'limitations': [
|
||||
'rAF brackets estimate display scheduling; panel scanout and pixel response are not measured',
|
||||
'Mixed-exposure or unrecognized markers are excluded; first decodable echo can follow an earlier ambiguous image',
|
||||
'Not every displayed frame is a sample; accepted samples describe this calibration scene and network',
|
||||
'decodeToDrawMs starts after JPEG decoding, not at UDP or WebSocket arrival',
|
||||
],
|
||||
'physical_panel_response_measured': False,
|
||||
'trials': trials,
|
||||
}
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.out.write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
|
||||
for trial in trials:
|
||||
print(json.dumps({k: trial[k] for k in ('fb_count', 'samples', 'marker_event_to_paint_ms')}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,101 @@
|
||||
# Build the ESP32-S3 firmware from PowerShell without executing .env as code.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$EnvFile = '.env',
|
||||
[switch]$Package,
|
||||
[Parameter(ValueFromRemainingArguments = $true)]
|
||||
[string[]]$CargoArgs = @()
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
Push-Location (Split-Path -Parent $PSScriptRoot)
|
||||
$buildEnvironment = @{}
|
||||
foreach ($name in @('CARGO_WORKSPACE_DIR', 'ESP_IDF_GLOB_BASE', 'ESP_IDF_GLOB_PARTITIONS')) {
|
||||
$buildEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
|
||||
}
|
||||
try {
|
||||
if (Test-Path -LiteralPath $EnvFile) {
|
||||
$lineNumber = 0
|
||||
foreach ($line in Get-Content -LiteralPath $EnvFile -Encoding UTF8) {
|
||||
$lineNumber++
|
||||
if ($line -match '^\s*(#|$)') { continue }
|
||||
if ($line -notmatch '^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$') {
|
||||
throw "Invalid assignment in ${EnvFile}:${lineNumber}"
|
||||
}
|
||||
$key = $Matches[1]
|
||||
$value = $Matches[2].Trim()
|
||||
if ($value.StartsWith("'") -or $value.StartsWith('"')) {
|
||||
$quote = $value.Substring(0, 1)
|
||||
if ($value.Length -lt 2 -or -not $value.EndsWith($quote)) {
|
||||
throw "Unclosed quote in ${EnvFile}:${lineNumber}"
|
||||
}
|
||||
$value = $value.Substring(1, $value.Length - 2)
|
||||
} else {
|
||||
$value = ($value -replace '\s+#.*$', '').TrimEnd()
|
||||
}
|
||||
[Environment]::SetEnvironmentVariable($key, $value, 'Process')
|
||||
}
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($env:WIFI_SSID) -or $env:WIFI_SSID -eq 'your-ssid') {
|
||||
throw 'Set WIFI_SSID in .env (copy .env.example) or the environment before building.'
|
||||
}
|
||||
if ($null -eq $env:WIFI_PASS) { $env:WIFI_PASS = '' }
|
||||
|
||||
# bindgen 要加载 esp-clang 自带的 libclang.dll,而它依赖**同目录**的 libLLVM-21.dll、
|
||||
# libclang-cpp.dll 等。LoadLibraryEx 默认不会去 DLL 自己的目录找依赖,所以必须把这个
|
||||
# 目录放进 PATH,否则报的是一句毫不相干的话:
|
||||
# Unable to find libclang: "...\libclang.dll could not be opened: LoadLibraryExW failed"
|
||||
# (`espup` 的 shell 会替你导出这些变量,直接跑脚本的人不会。)
|
||||
$espClang = Join-Path $env:USERPROFILE '.rustup\toolchains\esp-1.97.0.0\xtensa-esp32-elf-clang\esp-clang\bin'
|
||||
if (Test-Path -LiteralPath (Join-Path $espClang 'libclang.dll')) {
|
||||
$env:LIBCLANG_PATH = $espClang
|
||||
# An existing entry can be behind another LLVM installation. Move it
|
||||
# to the front so libclang-cpp.dll and the runtime match libclang.dll.
|
||||
$otherPaths = @($env:PATH -split ';' | Where-Object { $_ -ne $espClang })
|
||||
$env:PATH = (@($espClang) + $otherPaths) -join ';'
|
||||
}
|
||||
|
||||
$env:CARGO_WORKSPACE_DIR = (Get-Location).Path
|
||||
$env:ESP_IDF_GLOB_BASE = (Get-Location).Path
|
||||
$env:ESP_IDF_GLOB_PARTITIONS = 'partitions.csv'
|
||||
|
||||
$firmwareElf = $null
|
||||
if ($Package) {
|
||||
# Use Cargo's actual artifact path, including --target-dir / --config
|
||||
# overrides, rather than guessing where this build wrote its ELF.
|
||||
& cargo build --release --locked --message-format=json-render-diagnostics @CargoArgs | ForEach-Object {
|
||||
$message = $_ | ConvertFrom-Json
|
||||
if ($message.reason -eq 'compiler-artifact' -and $message.target.name -eq 'esp32' -and $message.executable) {
|
||||
$firmwareElf = $message.executable
|
||||
}
|
||||
}
|
||||
} else {
|
||||
& cargo build --release --locked @CargoArgs
|
||||
}
|
||||
if ($LASTEXITCODE -ne 0) { throw "cargo build failed (exit $LASTEXITCODE)." }
|
||||
|
||||
if ($Package) {
|
||||
if (-not $firmwareElf) { throw 'Cargo did not report the esp32 firmware ELF; refusing to package old images.' }
|
||||
$python = Get-Command python -ErrorAction SilentlyContinue
|
||||
if ($null -eq $python) {
|
||||
throw '-Package requires Python 3 on PATH (used by scripts/package_firmware.py).'
|
||||
}
|
||||
# 固件包的版本号与客户端同源:都读仓库根的 version.json(由 scripts/version.mjs
|
||||
# 从 git 历史算出)。不传的话 make_bundle.py 会退回 BUILD-INFO.json 里的
|
||||
# 变体名+提交号,那是另一套编号,装到客户端里会与界面上的版本对不上。
|
||||
$versionArgs = @()
|
||||
if (Test-Path -LiteralPath '../version.json') {
|
||||
$info = Get-Content -LiteralPath '../version.json' -Raw | ConvertFrom-Json
|
||||
$versionArgs = @('--version', "v$($info.version)+$($info.build)")
|
||||
}
|
||||
& python scripts/package_firmware.py --firmware target/firmware --elf $firmwareElf --name 'RMIC 图传固件' @versionArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "package_firmware.py failed (exit $LASTEXITCODE)." }
|
||||
}
|
||||
} finally {
|
||||
foreach ($name in $buildEnvironment.Keys) {
|
||||
[Environment]::SetEnvironmentVariable($name, $buildEnvironment[$name], 'Process')
|
||||
}
|
||||
Pop-Location
|
||||
}
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds the firmware with the credentials from .env (see .env.example).
|
||||
#
|
||||
# esp-idf-sys downloads the pinned ESP-IDF automatically. Set IDF_PATH in the
|
||||
# environment to reuse an existing installation (see README.md).
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Resolve the SDK defaults/components from this repository even when the build
|
||||
# cache is elsewhere, and copy the partition table into the CMake project.
|
||||
export CARGO_WORKSPACE_DIR="$PWD"
|
||||
export ESP_IDF_GLOB_BASE="$PWD"
|
||||
export ESP_IDF_GLOB_PARTITIONS="partitions.csv"
|
||||
|
||||
if [ -f .env ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
. ./.env
|
||||
set +a
|
||||
fi
|
||||
|
||||
: "${WIFI_SSID:?set WIFI_SSID in .env (or export it) before building}"
|
||||
export WIFI_PASS="${WIFI_PASS:-}"
|
||||
|
||||
package=0
|
||||
cargo_args=()
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--package) package=1 ;;
|
||||
*) cargo_args+=("$arg") ;;
|
||||
esac
|
||||
done
|
||||
|
||||
cargo build --release --locked "${cargo_args[@]}"
|
||||
|
||||
if [ "$package" -eq 1 ]; then
|
||||
if ! command -v python3 >/dev/null 2>&1; then
|
||||
echo "error: --package requires python3 on PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
python3 scripts/package_firmware.py --firmware target/firmware
|
||||
fi
|
||||
Executable
+131
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds, picks a flash offset that avoids the module's defective byte, flashes,
|
||||
# and prints the serial log.
|
||||
#
|
||||
# The module this was developed against has one byte in its SPI flash at
|
||||
# 0xFADE7 whose bits 5..7 cannot be programmed (see README). Whatever value the
|
||||
# app image places there gets corrupted, the image checksum fails, and the
|
||||
# bootloader refuses to boot it. The image itself is unaffected by where it is
|
||||
# placed in flash, so moving the app partition is enough: this picks the lowest
|
||||
# 64 KB-aligned offset whose byte at that address the flash can actually store.
|
||||
#
|
||||
# Usage from the repository root: vt/scripts/flash.sh [--monitor SECONDS]
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
readonly BAD_FLASH_ADDR="${BAD_FLASH_ADDR:-0xFADE7}"
|
||||
readonly ALIGN="${ALIGN:-0x10000}"
|
||||
# The same module also showed a high-bit write mismatch at 0x10863. Keep the application
|
||||
# above its sector; this does not remove the separate 0xFADE7 constraint.
|
||||
readonly MIN_APP_OFFSET="${MIN_APP_OFFSET:-0x20000}"
|
||||
readonly MAX_APP_SIZE="${MAX_APP_SIZE:-0x120000}"
|
||||
|
||||
MONITOR_SECS=25
|
||||
if [ "${1:-}" = "--monitor" ]; then
|
||||
MONITOR_SECS="${2:-25}"
|
||||
fi
|
||||
|
||||
port="${ESP_PORT:-}"
|
||||
if [ -z "$port" ]; then
|
||||
port=$(ls /dev/cu.usbmodem* /dev/cu.wchusbserial* /dev/cu.SLAB* /dev/cu.usbserial* 2>/dev/null | head -1 || true)
|
||||
fi
|
||||
if [ -z "$port" ]; then
|
||||
echo "no serial port found; set ESP_PORT=/dev/cu.xxx" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
out=$(ls -d target/xtensa-esp32s3-espidf/release/build/esp-idf-sys-*/out/build 2>/dev/null | head -1 || true)
|
||||
|
||||
echo "==> build"
|
||||
./scripts/build.sh
|
||||
|
||||
echo "==> pick app offset"
|
||||
espflash save-image --chip esp32s3 --format esp-idf \
|
||||
target/xtensa-esp32s3-espidf/release/esp32 /tmp/esp32-cam-app.bin >/dev/null
|
||||
|
||||
read -r offset < <(python3 - <<PY
|
||||
import sys
|
||||
data = open("/tmp/esp32-cam-app.bin", "rb").read()
|
||||
bad = $BAD_FLASH_ADDR
|
||||
align = $ALIGN
|
||||
flash_size = 16 * 1024 * 1024
|
||||
for off in range(max(align, $MIN_APP_OFFSET), flash_size - len(data), align):
|
||||
at = bad - off
|
||||
if at < 0 or at >= len(data):
|
||||
continue
|
||||
if data[at] & 0xE0 == 0: # top three bits must be storable
|
||||
print(off)
|
||||
break
|
||||
else:
|
||||
sys.exit("no usable app offset found; this module's flash is too broken")
|
||||
PY
|
||||
)
|
||||
|
||||
printf '0x%x\n' "$offset"
|
||||
|
||||
# Write the chosen offset into partitions.csv.
|
||||
python3 - "$offset" <<'PY'
|
||||
import re, sys
|
||||
offset = int(sys.argv[1], 0)
|
||||
p = "partitions.csv"
|
||||
s = open(p).read()
|
||||
s2 = re.sub(r"^(factory,\s+app,\s+factory,\s+)0x[0-9a-fA-F]+",
|
||||
lambda m: m.group(1) + "0x%06x" % offset, s, flags=re.M)
|
||||
if s2 != s:
|
||||
open(p, "w").write(s2)
|
||||
print("partitions.csv updated")
|
||||
else:
|
||||
print("partitions.csv already at 0x%06x" % offset)
|
||||
PY
|
||||
|
||||
echo "==> reconfigure + rebuild with the new table"
|
||||
rm -rf target/xtensa-esp32s3-espidf/release/build/esp-idf-sys-*
|
||||
./scripts/build.sh
|
||||
|
||||
espflash save-image --chip esp32s3 --format esp-idf \
|
||||
target/xtensa-esp32s3-espidf/release/esp32 /tmp/esp32-cam-app.bin >/dev/null
|
||||
|
||||
out=$(ls -d target/xtensa-esp32s3-espidf/release/build/esp-idf-sys-*/out/build | head -1)
|
||||
|
||||
# The rebuild can shift the image, so confirm before committing to the flash.
|
||||
python3 - <<PY || { echo "image moved onto the bad byte again; rerun" >&2; exit 1; }
|
||||
import sys
|
||||
data = open("/tmp/esp32-cam-app.bin", "rb").read()
|
||||
at = $BAD_FLASH_ADDR - $offset
|
||||
if not (0 <= at < len(data)) or data[at] & 0xE0:
|
||||
print("byte at 0x%X is 0x%02X, not storable" % ($BAD_FLASH_ADDR, data[at] if 0 <= at < len(data) else -1))
|
||||
sys.exit(1)
|
||||
print("byte at 0x%X is 0x%02X, storable" % ($BAD_FLASH_ADDR, data[at]))
|
||||
PY
|
||||
|
||||
echo "==> flash $port"
|
||||
esptool_py=$(ls "$HOME"/.espressif/tools/python/*/venv/bin/python 2>/dev/null | head -1)
|
||||
"$esptool_py" -m esptool --chip esp32s3 --port "$port" --baud 460800 write-flash \
|
||||
0x0 "$out/bootloader/bootloader.bin" \
|
||||
0x8000 "$out/partition_table/partition-table.bin" \
|
||||
"$offset" /tmp/esp32-cam-app.bin 2>&1 | grep -viE 'writing at|^\[1A' | tail -4
|
||||
|
||||
if [ "$MONITOR_SECS" -gt 0 ]; then
|
||||
echo "==> serial log (${MONITOR_SECS}s)"
|
||||
python3 - "$port" "$MONITOR_SECS" <<'PY'
|
||||
import os, sys, termios, time
|
||||
fd = os.open(sys.argv[1], os.O_RDONLY | os.O_NOCTTY)
|
||||
a = termios.tcgetattr(fd)
|
||||
a[0] = a[1] = a[3] = 0
|
||||
a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
|
||||
a[4] = a[5] = termios.B115200
|
||||
a[6][termios.VMIN] = 0
|
||||
a[6][termios.VTIME] = 1
|
||||
termios.tcsetattr(fd, termios.TCSANOW, a)
|
||||
end = time.time() + float(sys.argv[2])
|
||||
while time.time() < end:
|
||||
try:
|
||||
d = os.read(fd, 4096)
|
||||
except OSError:
|
||||
break
|
||||
if d:
|
||||
sys.stdout.write(d.decode("utf-8", "replace"))
|
||||
sys.stdout.flush()
|
||||
PY
|
||||
fi
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把一个已构建的固件目录封装成客户端认的官方 bundle。
|
||||
|
||||
官方 bundle 是一个目录,至少包含:
|
||||
|
||||
bundle.json
|
||||
esp32s3-app.bin
|
||||
partition-table.bin
|
||||
bootloader.bin # 可选,客户端默认不写
|
||||
|
||||
客户端会先校验 bundle.json 里声明的 SHA256,再读设备当前分区表、选择空闲槽位、
|
||||
写 App + 整段回读;只有回读通过才切换分区表。它不会按这里的 partition-table.bin
|
||||
直接覆盖设备分区表——设备上的 NVS/PHY 布局以设备当前表为准。
|
||||
|
||||
用法(在仓库根目录):
|
||||
|
||||
python vt/scripts/make_bundle.py --firmware vt/target/firmware
|
||||
|
||||
可选参数:
|
||||
|
||||
--name "ESP32-S3 图传固件"
|
||||
--version "..." 默认读 BUILD-INFO.json 的 build_variant+source_revision
|
||||
--app-partition-size 0x140000
|
||||
--flash-size 16mb --flash-mode dio --flash-frequency 40mhz
|
||||
--notes "..."
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def read_build_info(firmware: Path) -> dict:
|
||||
path = firmware / "BUILD-INFO.json"
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="生成官方固件 bundle.json")
|
||||
parser.add_argument("--firmware", default=str(Path(__file__).resolve().parents[1] / "target/firmware"), help="固件产物目录,默认 vt/target/firmware")
|
||||
parser.add_argument("--name", default="ESP32-S3 图传固件")
|
||||
parser.add_argument("--version", default="")
|
||||
parser.add_argument("--app", default="esp32s3-app.bin")
|
||||
parser.add_argument("--partition-table", default="partition-table.bin")
|
||||
parser.add_argument("--bootloader", default="bootloader.bin")
|
||||
parser.add_argument("--app-partition-size", default="0x140000")
|
||||
parser.add_argument("--flash-size", default="16mb")
|
||||
parser.add_argument("--flash-mode", default="dio")
|
||||
parser.add_argument("--flash-frequency", default="40mhz")
|
||||
parser.add_argument("--chip", default="esp32s3")
|
||||
parser.add_argument("--notes", default="官方 bundle:客户端只写 App 与 patch 后的分区表,不重写 bootloader;旧 App/分区表会先备份。")
|
||||
args = parser.parse_args()
|
||||
|
||||
firmware = Path(args.firmware)
|
||||
if not firmware.is_dir():
|
||||
print(f"固件目录不存在:{firmware}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
app = firmware / args.app
|
||||
partition_table = firmware / args.partition_table
|
||||
bootloader = firmware / args.bootloader
|
||||
|
||||
for required, label in ((app, "App"), (partition_table, "分区表")):
|
||||
if not required.is_file():
|
||||
print(f"{label}文件不存在:{required}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if partition_table.stat().st_size != 0xC00:
|
||||
print(
|
||||
f"分区表应为 0xC00 字节,实际 {partition_table.stat().st_size}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
build = read_build_info(firmware)
|
||||
version = args.version
|
||||
if not version:
|
||||
variant = build.get("build_variant")
|
||||
revision = build.get("source_revision")
|
||||
if variant and revision:
|
||||
version = f"{variant}+{revision[:7]}"
|
||||
else:
|
||||
version = "0.1.0"
|
||||
|
||||
manifest = {
|
||||
"format": 1,
|
||||
"name": args.name,
|
||||
"version": version,
|
||||
"chip": args.chip,
|
||||
"app": args.app,
|
||||
"appSha256": sha256(app),
|
||||
"partitionTable": args.partition_table,
|
||||
"partitionTableSha256": sha256(partition_table),
|
||||
"appPartitionSize": args.app_partition_size,
|
||||
"flashSize": args.flash_size,
|
||||
"flashMode": args.flash_mode,
|
||||
"flashFrequency": args.flash_frequency,
|
||||
"notes": args.notes,
|
||||
}
|
||||
|
||||
if bootloader.is_file():
|
||||
manifest["bootloader"] = args.bootloader
|
||||
manifest["bootloaderSha256"] = sha256(bootloader)
|
||||
else:
|
||||
print(f"提示:没有 {bootloader},bundle 将不包含 bootloader", file=sys.stderr)
|
||||
|
||||
output = firmware / "bundle.json"
|
||||
output.write_text(
|
||||
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
print(f"已写入 {output}")
|
||||
print(f" {manifest['name']} {manifest['version']}")
|
||||
print(f" App {app.name} · {app.stat().st_size} 字节 · {manifest['appSha256']}")
|
||||
print(f" App 分区 {manifest['appPartitionSize']} · Flash {manifest['flashSize']}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,278 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把编译后的固件目录打成客户端可直接读取的 .zip 官方包。
|
||||
|
||||
流程(在 cargo build 之后):
|
||||
|
||||
package_firmware.py
|
||||
├─ 从 Cargo 产物导出 App,同步 Bootloader / 分区表
|
||||
├─ 刷新 BUILD-INFO.json,并调用 make_bundle.py 生成 bundle.json
|
||||
├─ 固定条目顺序与 mtime,生成可复现的 zip
|
||||
└─ 写 <zip>.sha256
|
||||
|
||||
zip 根目录结构:
|
||||
|
||||
bundle.json
|
||||
esp32s3-app.bin
|
||||
partition-table.bin (0xC00 字节)
|
||||
bootloader.bin (可选)
|
||||
BUILD-INFO.json (可选)
|
||||
|
||||
客户端读取 zip 时不要求先解压;目录包仍然兼容。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def sanitize(value: str) -> str:
|
||||
value = re.sub(r"[^A-Za-z0-9._-]+", "-", value.strip())
|
||||
return value.strip("-") or "firmware"
|
||||
|
||||
|
||||
def parse_epoch(build: dict) -> int:
|
||||
raw = os.environ.get("SOURCE_DATE_EPOCH")
|
||||
if raw:
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
packaged = build.get("packaged_at")
|
||||
if packaged:
|
||||
try:
|
||||
return int(datetime.fromisoformat(packaged).timestamp())
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
return int(time.time())
|
||||
|
||||
|
||||
def resolve_elf(repo: Path, explicit: str) -> Path:
|
||||
if explicit:
|
||||
return Path(explicit).resolve()
|
||||
# Cargo metadata also respects build.target-dir in Cargo configuration.
|
||||
result = subprocess.run(
|
||||
["cargo", "metadata", "--no-deps", "--format-version", "1"],
|
||||
cwd=repo, capture_output=True, text=True, check=True,
|
||||
)
|
||||
target = Path(json.loads(result.stdout)["target_directory"])
|
||||
return target / "xtensa-esp32s3-espidf" / "release" / "esp32"
|
||||
|
||||
|
||||
def export_app(repo: Path, firmware: Path, elf: Path, allow_stale: bool) -> None:
|
||||
"""从选中的 ELF 导出 App,并同步同次构建的配套镜像。"""
|
||||
app = firmware / "esp32s3-app.bin"
|
||||
if not elf.is_file():
|
||||
if allow_stale and app.is_file():
|
||||
print(f"警告:缺少 {elf};继续打包现有镜像", file=sys.stderr)
|
||||
return
|
||||
raise SystemExit(f"固件 ELF 不存在:{elf}。请先构建,或用 --elf 指定本次构建的 ELF。")
|
||||
|
||||
companions = [elf.parent / name for name in ("bootloader.bin", "partition-table.bin")]
|
||||
for source in companions:
|
||||
if not source.is_file():
|
||||
raise SystemExit(f"缺少同次构建的配套镜像:{source}")
|
||||
|
||||
espflash = repo / "target" / "tools" / "espflash" / "espflash.exe"
|
||||
if not espflash.is_file():
|
||||
found = shutil.which("espflash")
|
||||
espflash = Path(found) if found else Path("")
|
||||
if not espflash.is_file():
|
||||
message = "找不到 espflash,无法从最新 ELF 导出 App 镜像"
|
||||
if allow_stale:
|
||||
print(f"警告:{message};继续打包现有镜像", file=sys.stderr)
|
||||
return
|
||||
raise SystemExit(f"{message}。请安装 espflash,或加 --allow-stale 打包现有镜像。")
|
||||
|
||||
firmware.mkdir(parents=True, exist_ok=True)
|
||||
print(f"导出 App:{elf} -> {app}")
|
||||
result = subprocess.run(
|
||||
[
|
||||
str(espflash),
|
||||
"save-image",
|
||||
"--chip",
|
||||
"esp32s3",
|
||||
"--format",
|
||||
"esp-idf",
|
||||
"--flash-size",
|
||||
"16mb",
|
||||
"--flash-mode",
|
||||
"dio",
|
||||
"--flash-freq",
|
||||
"40mhz",
|
||||
"--skip-update-check",
|
||||
str(elf),
|
||||
str(app),
|
||||
]
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise SystemExit(f"espflash save-image 失败(exit {result.returncode})")
|
||||
|
||||
for source in companions:
|
||||
destination = firmware / source.name
|
||||
if source.resolve() != destination.resolve():
|
||||
shutil.copy2(source, destination)
|
||||
|
||||
# Do not attach a previous build's hardware/performance claims to new images.
|
||||
revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
|
||||
dirty = subprocess.check_output(
|
||||
["git", "status", "--porcelain", "--untracked-files=normal"], cwd=repo, text=True,
|
||||
).strip()
|
||||
build = {
|
||||
"packaged_at": datetime.fromtimestamp(elf.stat().st_mtime, timezone.utc).isoformat(),
|
||||
"source_revision": revision,
|
||||
"includes_local_changes": bool(dirty),
|
||||
"target": "xtensa-esp32s3-espidf",
|
||||
"app_sha256": hashlib.sha256(app.read_bytes()).hexdigest(),
|
||||
"verification": {"hardware_flashed_and_tested": False},
|
||||
}
|
||||
(firmware / "BUILD-INFO.json").write_text(
|
||||
json.dumps(build, ensure_ascii=False, indent=2) + "\n", encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="生成官方 .zip 固件包")
|
||||
firmware_root = Path(__file__).resolve().parent.parent
|
||||
parser.add_argument("--firmware", default=str(firmware_root / "target/firmware"), help="固件产物目录,默认 vt/target/firmware")
|
||||
parser.add_argument("--elf", default="", help="本次构建的 ELF;默认通过 cargo metadata 查找 release 产物")
|
||||
parser.add_argument("--name", default="", help="传递给 make_bundle.py 的名称")
|
||||
parser.add_argument("--version", default="", help="传递给 make_bundle.py 的版本;默认读取 version.json")
|
||||
parser.add_argument("--skip-manifest", action="store_true", help="不重新生成 bundle.json")
|
||||
parser.add_argument("--allow-stale", action="store_true", help="缺少 ELF 或 espflash 时,允许打包目录中的现有镜像")
|
||||
parser.add_argument("--output", default="", help="输出 zip 路径;默认 target/firmware/camfw-*.zip")
|
||||
args = parser.parse_args()
|
||||
|
||||
repo = firmware_root
|
||||
if not args.version and (repo.parent / "version.json").is_file():
|
||||
version = json.loads((repo.parent / "version.json").read_text(encoding="utf-8"))
|
||||
args.version = f"v{version['version']}+{version['build']}"
|
||||
firmware = Path(args.firmware)
|
||||
if not firmware.is_absolute():
|
||||
firmware = (Path.cwd() / firmware).resolve()
|
||||
try:
|
||||
export_app(repo, firmware, resolve_elf(repo, args.elf), args.allow_stale)
|
||||
except (SystemExit, OSError, subprocess.CalledProcessError, ValueError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if not args.skip_manifest:
|
||||
make_bundle = repo / "scripts" / "make_bundle.py"
|
||||
command = [sys.executable, str(make_bundle), "--firmware", str(firmware)]
|
||||
if args.name:
|
||||
command += ["--name", args.name]
|
||||
if args.version:
|
||||
command += ["--version", args.version]
|
||||
result = subprocess.run(command, text=True)
|
||||
if result.returncode != 0:
|
||||
print("make_bundle.py 失败,未生成 zip", file=sys.stderr)
|
||||
return result.returncode
|
||||
|
||||
bundle_path = firmware / "bundle.json"
|
||||
if not bundle_path.is_file():
|
||||
print(f"缺少 {bundle_path}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
bundle = json.loads(bundle_path.read_text(encoding="utf-8"))
|
||||
build = {}
|
||||
build_info_path = firmware / "BUILD-INFO.json"
|
||||
if build_info_path.is_file():
|
||||
try:
|
||||
build = json.loads(build_info_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
build = {}
|
||||
|
||||
app = firmware / bundle["app"]
|
||||
partition_table = firmware / bundle["partitionTable"]
|
||||
if not app.is_file() or not partition_table.is_file():
|
||||
print("bundle.json 里的 App/分区表文件不存在", file=sys.stderr)
|
||||
return 1
|
||||
if partition_table.stat().st_size != 0xC00:
|
||||
print("partition-table.bin 必须是 0xC00 字节", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
bootloader_name = bundle.get("bootloader")
|
||||
bootloader = firmware / bootloader_name if bootloader_name else None
|
||||
if bootloader is not None and not bootloader.is_file():
|
||||
print(f"bundle.json 声明的 bootloader 不存在:{bootloader}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
epoch = parse_epoch(build)
|
||||
stamp = time.gmtime(epoch)
|
||||
date_time = (
|
||||
stamp.tm_year,
|
||||
stamp.tm_mon,
|
||||
stamp.tm_mday,
|
||||
stamp.tm_hour,
|
||||
stamp.tm_min,
|
||||
stamp.tm_sec,
|
||||
)
|
||||
date_text = f"{stamp.tm_year:04d}{stamp.tm_mon:02d}{stamp.tm_mday:02d}"
|
||||
|
||||
variant = sanitize(str(build.get("build_variant", "firmware")))
|
||||
revision = sanitize(str(build.get("source_revision", ""))[:7])
|
||||
chip = sanitize(str(bundle.get("chip", "esp32s3")))
|
||||
|
||||
# 文件名优先用**传进来的版本**(`--version`,来自仓库根的 version.json)。
|
||||
#
|
||||
# 原来只用 BUILD-INFO.json 里的变体名 + 提交号 + 日期,那是另一套编号:固件包叫
|
||||
# `...-4794bed-20261018.zip`,而客户端里显示的是 `v0.2.0+34`,两个数对不上,
|
||||
# 现场拿到一个 zip 没法说清它是不是界面上那一版。给了版本就用版本,没给才退回旧格式。
|
||||
if args.version:
|
||||
filename = f"camfw-{chip}-{sanitize(args.version)}.zip"
|
||||
else:
|
||||
suffix = f"-{revision}" if revision else ""
|
||||
filename = f"camfw-{chip}-{variant}{suffix}-{date_text}.zip"
|
||||
|
||||
output = Path(args.output) if args.output else firmware / filename
|
||||
if not output.is_absolute():
|
||||
output = (Path.cwd() / output).resolve()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
entries: list[tuple[str, bytes]] = [
|
||||
("bundle.json", bundle_path.read_bytes()),
|
||||
(app.name, app.read_bytes()),
|
||||
(partition_table.name, partition_table.read_bytes()),
|
||||
]
|
||||
if bootloader is not None:
|
||||
entries.append((bootloader.name, bootloader.read_bytes()))
|
||||
if build_info_path.is_file():
|
||||
entries.append(("BUILD-INFO.json", build_info_path.read_bytes()))
|
||||
|
||||
with zipfile.ZipFile(
|
||||
output,
|
||||
mode="w",
|
||||
compression=zipfile.ZIP_DEFLATED,
|
||||
compresslevel=9,
|
||||
) as archive:
|
||||
for name, data in entries:
|
||||
info = zipfile.ZipInfo(filename=name, date_time=date_time)
|
||||
info.compress_type = zipfile.ZIP_DEFLATED
|
||||
info.create_system = 3
|
||||
info.external_attr = 0o100644 << 16
|
||||
archive.writestr(info, data)
|
||||
|
||||
digest = hashlib.sha256(output.read_bytes()).hexdigest()
|
||||
sidecar = output.with_name(output.name + ".sha256")
|
||||
sidecar.write_text(f"{digest} {output.name}\n", encoding="utf-8")
|
||||
|
||||
print(f"已生成 {output}")
|
||||
print(f" {output.stat().st_size} 字节 · {len(entries)} 项 · SHA256 {digest}")
|
||||
print(f" {sidecar}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure real UDP video throughput, complete-frame loss and receive jitter.
|
||||
|
||||
Uses an ephemeral port by default so it can run beside the desktop client.
|
||||
The timings are receive-side metrics, not camera-to-display latency.
|
||||
"""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import secrets
|
||||
import struct
|
||||
import time
|
||||
|
||||
from udp_probe import decode
|
||||
|
||||
PORT = 5600
|
||||
FRAGMENT = 1400
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
return round(values[int((len(values) - 1) * p)], 3)
|
||||
|
||||
|
||||
def summary(source, duration):
|
||||
counts = source['counts']
|
||||
frames = counts['complete_frames']
|
||||
dropped = counts['superseded_frames'] + counts['missing_frames'] + counts['invalid_jpeg'] + counts['timed_out_frames']
|
||||
span = source['last_complete'] - source['first_complete'] if frames > 1 else 0
|
||||
return dict(
|
||||
address=source['address'], counts=dict(counts),
|
||||
window_fps=round(frames / duration, 3) if duration else 0,
|
||||
active_fps=round((frames - 1) / span, 3) if span else 0,
|
||||
frame_loss_percent=round(100 * dropped / max(1, frames + dropped), 3),
|
||||
resolution=source.get('resolution'),
|
||||
mean_jpeg_bytes=round(counts['jpeg_bytes'] / frames) if frames else 0,
|
||||
inter_frame_p50_ms=percentile(source['intervals'], .5),
|
||||
inter_frame_p95_ms=percentile(source['intervals'], .95),
|
||||
inter_frame_max_ms=round(max(source['intervals']), 3) if source['intervals'] else None,
|
||||
assembly_p95_ms=percentile(source['assembly'], .95),
|
||||
pending_frames=int(source['pending'] is not None),
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('host', help='Board IPv4 address; avoids VPN limited-broadcast routing')
|
||||
parser.add_argument('--seconds', type=float, default=30)
|
||||
parser.add_argument('--local-port', type=int, default=0)
|
||||
parser.add_argument('--local-ip', default='')
|
||||
parser.add_argument('--receive-buffer', type=int, default=1024 * 1024, help='0 keeps the OS default')
|
||||
parser.add_argument('--json', type=Path)
|
||||
parser.add_argument('--save-frame', type=Path)
|
||||
args = parser.parse_args()
|
||||
client_id = secrets.randbelow(0xFFFFFFFF) + 1
|
||||
if client_id == 0x0C110001:
|
||||
client_id += 1
|
||||
subscribe = struct.pack('<IBHIIHHIHHB', 0x4D564331, 2, 1, client_id, 0, 0, 0, 0, 0, 0, 2)
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
if args.receive_buffer:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, args.receive_buffer)
|
||||
sock.bind((args.local_ip, args.local_port))
|
||||
local_port = sock.getsockname()[1]
|
||||
buffer_bytes = sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
|
||||
sock.settimeout(.05)
|
||||
sources = {}
|
||||
invalid = 0
|
||||
saved = False
|
||||
started = time.perf_counter()
|
||||
renew = started
|
||||
report_at = started + 5
|
||||
previous_frames = 0
|
||||
previous_report = started
|
||||
try:
|
||||
while time.perf_counter() - started < args.seconds:
|
||||
now = time.perf_counter()
|
||||
for source in sources.values():
|
||||
if source['pending'] is not None and now-source['pending']['started'] > .5:
|
||||
source['counts']['timed_out_frames'] += 1
|
||||
source['pending'] = None
|
||||
if now >= renew:
|
||||
sock.sendto(subscribe, (args.host, PORT))
|
||||
renew = now + .8
|
||||
if now >= report_at:
|
||||
frames = sum(s['counts']['complete_frames'] for s in sources.values())
|
||||
print(f'{now-started:5.1f}s {(frames-previous_frames)/(now-previous_report):5.1f} fps complete={frames}', flush=True)
|
||||
previous_frames, previous_report, report_at = frames, now, now + 5
|
||||
try:
|
||||
data, address = sock.recvfrom(2048)
|
||||
except socket.timeout:
|
||||
continue
|
||||
now = time.perf_counter()
|
||||
parsed = decode(data)
|
||||
if parsed is None:
|
||||
invalid += 1
|
||||
continue
|
||||
kind, h, payload = parsed
|
||||
if kind != 1:
|
||||
continue
|
||||
size = h['total_len']
|
||||
index, count = h['frag_index'], h['frag_count']
|
||||
offset = index * FRAGMENT
|
||||
if h['version'] != 1 or size > 4 * 1024 * 1024 or count != max(1, (size + FRAGMENT - 1) // FRAGMENT) or index >= count or offset > size or len(payload) != min(FRAGMENT, size-offset):
|
||||
invalid += 1
|
||||
continue
|
||||
sender, frame = h['sender_id'], h['frame_id']
|
||||
if sender not in sources:
|
||||
sources[sender] = dict(address=address[0], counts=Counter(), latest=None, last_seen=now, pending=None, intervals=[], assembly=[], first_complete=None, last_complete=None)
|
||||
s = sources[sender]
|
||||
counts = s['counts']
|
||||
counts['video_datagrams'] += 1
|
||||
latest = s['latest']
|
||||
if latest is not None:
|
||||
distance = (frame - latest) & 0xFFFFFFFF
|
||||
if distance >= 0x80000000 and now-s['last_seen'] >= 1:
|
||||
counts['restarts'] += 1
|
||||
latest = s['latest'] = None
|
||||
s['pending'] = None
|
||||
elif distance >= 0x80000000 or (distance == 0 and s['pending'] is None):
|
||||
counts['late_or_repeated_datagrams'] += 1
|
||||
continue
|
||||
elif distance > 0:
|
||||
counts['missing_frames'] += distance - 1
|
||||
counts['superseded_frames'] += int(s['pending'] is not None)
|
||||
s['pending'] = None
|
||||
s['latest'], s['last_seen'] = frame, now
|
||||
if s['pending'] is None:
|
||||
s['pending'] = dict(buffer=bytearray(size), seen=set(), count=count, size=size, width=h['width'], height=h['height'], started=now)
|
||||
pending = s['pending']
|
||||
if (size, count, h['width'], h['height']) != (pending['size'], pending['count'], pending['width'], pending['height']):
|
||||
counts['inconsistent_metadata'] += 1
|
||||
continue
|
||||
if index in pending['seen']:
|
||||
counts['duplicate_fragments'] += 1
|
||||
continue
|
||||
pending['seen'].add(index)
|
||||
pending['buffer'][offset:offset+len(payload)] = payload
|
||||
if len(pending['seen']) != count:
|
||||
continue
|
||||
jpeg = bytes(pending['buffer'])
|
||||
if jpeg[:2] == b'\xff\xd8' and jpeg[-2:] == b'\xff\xd9':
|
||||
completed = time.perf_counter()
|
||||
counts['complete_frames'] += 1
|
||||
counts['jpeg_bytes'] += size
|
||||
if s['last_complete'] is not None:
|
||||
s['intervals'].append((completed-s['last_complete'])*1000)
|
||||
s['last_complete'] = completed
|
||||
if s['first_complete'] is None:
|
||||
s['first_complete'] = completed
|
||||
s['assembly'].append((completed-pending['started'])*1000)
|
||||
s['resolution'] = [h['width'], h['height']]
|
||||
if args.save_frame and not saved:
|
||||
args.save_frame.write_bytes(jpeg)
|
||||
saved = True
|
||||
else:
|
||||
counts['invalid_jpeg'] += 1
|
||||
s['pending'] = None
|
||||
finally:
|
||||
sock.close()
|
||||
elapsed = time.perf_counter()-started
|
||||
result = dict(seconds=round(elapsed, 3), host=args.host, local_port=local_port, receive_buffer_bytes=buffer_bytes, invalid_datagrams=invalid, sources={f'0x{sender:08X}': summary(s, elapsed) for sender, s in sources.items()}, timing_scope='receiver inter-frame spacing and first-to-last fragment assembly; not camera-to-display latency')
|
||||
if args.json:
|
||||
args.json.write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return 0 if any(s['counts']['complete_frames'] for s in sources.values()) else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Record firmware telemetry continuously (requires pyserial; no UDP subscriber)."""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
import serial
|
||||
|
||||
|
||||
FIELDS = {
|
||||
'submitted_fps': (r'([\d.]+) fps submitted', float),
|
||||
'attempted_fps': (r'([\d.]+) fps attempted', float),
|
||||
'kilobytes_per_second': (r'([\d.]+) kB/s', float),
|
||||
'send_failures': (r'(\d+) send failures', int),
|
||||
'retries': (r'(\d+) retries', int),
|
||||
'peer_frames_dropped': (r'(\d+) peer frames dropped', int),
|
||||
'send_ms': (r'([\d.]+) ms/send', float),
|
||||
'subscribers': (r'(\d+) clients subscribed', int),
|
||||
'heap_free': (r'internal heap (\d+) free', int),
|
||||
'heap_largest': (r'free / (\d+) largest bytes', int),
|
||||
'rssi_dbm': (r'RSSI (-?\d+) dBm', int),
|
||||
'max_tx_power_dbm': (r'max TX power ([\w.+-]+) dBm', float),
|
||||
'chip_temperature_c': (r'chip temp ([\w.+-]+) C', float),
|
||||
'target_fps': (r'target (\d+) fps', int),
|
||||
'capture_errors': (r'capture errors (\d+)', int),
|
||||
'exposure_lines': (r'exposure (-?\d+) lines', int),
|
||||
'jpeg_quality': (r'jpeg quality (\d+)', int),
|
||||
'gain_multiplier': (r'gain ([\d.]+)x', float),
|
||||
'capture_queue_skipped': (r'capture queue skipped (\d+)', int),
|
||||
'stale_frames_dropped': (r'stale frames dropped (\d+)', int),
|
||||
'deadline_peer_drops': (r'deadline peer drops (\d+)', int),
|
||||
'max_submitted_capture_age_ms': (r'max submitted capture age ([\d.]+) ms', float),
|
||||
'max_send_hold_ms': (r'max send hold ([\d.]+) ms', float),
|
||||
}
|
||||
|
||||
|
||||
def parse_sample(line):
|
||||
if 'fps submitted' not in line:
|
||||
return None
|
||||
sample = {}
|
||||
match = re.search(r'\((\d+)\)', line)
|
||||
if match:
|
||||
sample['uptime_ms'] = int(match[1])
|
||||
for name, (pattern, convert) in FIELDS.items():
|
||||
match = re.search(pattern, line)
|
||||
if match:
|
||||
value = convert(match[1])
|
||||
sample[name] = value if not isinstance(value, float) or math.isfinite(value) else None
|
||||
sample['thermal_limited'] = 'thermal_limited true' in line
|
||||
return sample
|
||||
|
||||
|
||||
def write_json(path, data):
|
||||
temporary = path.with_suffix(path.suffix+'.tmp')
|
||||
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--port', default='COM7')
|
||||
parser.add_argument('--seconds', type=float, default=1860)
|
||||
parser.add_argument('--out', type=Path, required=True, help='Output path prefix')
|
||||
parser.add_argument('--reset', action='store_true')
|
||||
parser.add_argument('--stop-file', type=Path, help='Finish cleanly when this file exists')
|
||||
args = parser.parse_args()
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
port = serial.Serial()
|
||||
port.port, port.baudrate, port.timeout = args.port, 115200, .2
|
||||
port.dtr = port.rts = False
|
||||
records, events = [], []
|
||||
started = time.perf_counter()
|
||||
last_uptime, reboot_count, last_sample_at = None, 0, None
|
||||
serial_error = None
|
||||
try:
|
||||
port.open()
|
||||
if args.reset:
|
||||
port.rts = True
|
||||
time.sleep(.15)
|
||||
port.rts = False
|
||||
with args.out.with_suffix('.serial.log').open('w', encoding='utf-8') as raw, args.out.with_suffix('.telemetry.ndjson').open('w', encoding='utf-8') as telemetry:
|
||||
while time.perf_counter()-started < args.seconds:
|
||||
if args.stop_file and args.stop_file.exists():
|
||||
break
|
||||
line = port.readline().decode('utf-8', errors='replace')
|
||||
if not line:
|
||||
continue
|
||||
raw.write(line)
|
||||
raw.flush()
|
||||
elapsed = time.perf_counter()-started
|
||||
sample = parse_sample(line)
|
||||
if sample:
|
||||
sample.update(elapsed_seconds=round(elapsed, 3), utc=datetime.now(timezone.utc).isoformat())
|
||||
uptime = sample.get('uptime_ms')
|
||||
if uptime is not None and last_uptime is not None and uptime+1000 < last_uptime:
|
||||
reboot_count += 1
|
||||
last_uptime = uptime
|
||||
last_sample_at = elapsed
|
||||
records.append(sample)
|
||||
telemetry.write(json.dumps(sample)+'\n')
|
||||
telemetry.flush()
|
||||
write_json(args.out.with_suffix('.latest.json'), dict(elapsed_seconds=round(elapsed, 3), samples=len(records), reboot_count=reboot_count, latest=sample))
|
||||
if len(records) % 12 == 0:
|
||||
print(json.dumps(dict(minutes=round(elapsed/60, 1), reboot_count=reboot_count, latest=sample)), flush=True)
|
||||
elif re.search(r'panic|Guru Meditation|Brownout|watchdog|NO-EOI|OVF|thermal load limit|reset reason|capture cap|configured capture', line, re.I):
|
||||
events.append(dict(elapsed_seconds=round(elapsed, 3), text=line.strip()))
|
||||
except (serial.SerialException, OSError) as error:
|
||||
serial_error = str(error)
|
||||
finally:
|
||||
port.close()
|
||||
result = dict(elapsed_seconds=round(time.perf_counter()-started, 3), requested_seconds=args.seconds, stopped_by_request=bool(args.stop_file and args.stop_file.exists()), serial_error=serial_error, samples=len(records), reboot_count=reboot_count, last_sample_at=last_sample_at, events=events, records=records)
|
||||
write_json(args.out.with_suffix('.summary.json'), result)
|
||||
print(json.dumps({k:v for k,v in result.items() if k not in ('records', 'events')}))
|
||||
if serial_error:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the actual driver handoff function with deterministic queue stubs."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
source = (root/'components/esp32-camera/driver/cam_hal.c').read_text()
|
||||
start = source.index('camera_fb_t *cam_take_latest(')
|
||||
end = source.index('\nvoid cam_give(', start)
|
||||
function = source[start:end]
|
||||
out = root/'target/latest-frame-test'
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
test = r'''
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
typedef unsigned TickType_t;
|
||||
typedef struct { int id; } camera_fb_t;
|
||||
static struct { size_t frame_cnt; } object = {3}, *cam_obj = &object;
|
||||
static camera_fb_t frames[] = {{0},{1},{2},{3},{4},{5}};
|
||||
static int calls, releases[6], mode;
|
||||
static camera_fb_t *cam_take(TickType_t wait) {
|
||||
assert(wait == (calls == 0 ? 100 : 0));
|
||||
++calls;
|
||||
if (mode == 1 || (mode == 2 && calls == 2)) return NULL;
|
||||
assert(calls < 6);
|
||||
return &frames[calls];
|
||||
}
|
||||
static void cam_give(camera_fb_t *frame) { releases[frame->id]++; }
|
||||
'''+function+r'''
|
||||
static void reset(int scenario) {
|
||||
mode=scenario; calls=0;
|
||||
for(int i=0;i<6;i++) releases[i]=0;
|
||||
}
|
||||
int main(void) {
|
||||
uint32_t skipped=99;
|
||||
// A producer that stays ahead cannot make the drain loop run forever.
|
||||
reset(0);
|
||||
camera_fb_t *latest=cam_take_latest(100,&skipped);
|
||||
assert(calls==3 && latest->id==3 && skipped==2);
|
||||
assert(releases[1]==1 && releases[2]==1 && releases[3]==0);
|
||||
// An unavailable/invalid newer candidate must not release our valid frame.
|
||||
reset(2);
|
||||
latest=cam_take_latest(100,&skipped);
|
||||
assert(calls==2 && latest->id==1 && skipped==0 && releases[1]==0);
|
||||
// A first-frame timeout has no handle to return, and resets the skip count.
|
||||
reset(1);
|
||||
assert(cam_take_latest(100,&skipped)==NULL && skipped==0 && calls==1);
|
||||
// A single capture buffer performs no second, nonblocking acquisition.
|
||||
reset(0); object.frame_cnt=1;
|
||||
latest=cam_take_latest(100,NULL);
|
||||
assert(calls==1 && latest->id==1 && releases[1]==0);
|
||||
puts("4 latest-frame ownership and bounded-drain scenarios passed");
|
||||
}
|
||||
'''
|
||||
(out/'latest-frame.c').write_text(test)
|
||||
compiler = shutil.which('clang') or shutil.which('gcc')
|
||||
if not compiler:
|
||||
sys.exit('A host clang or gcc is required for this optional driver test')
|
||||
binary = out/('latest-frame.exe' if sys.platform=='win32' else 'latest-frame')
|
||||
subprocess.run([compiler,'-std=c11','-Wall','-Wextra','-Werror',str(out/'latest-frame.c'),'-o',str(binary)],check=True)
|
||||
subprocess.run([str(binary)],check=True)
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
"""固件打包回归:外部 Cargo 目录、旧镜像隔离、配套文件及 ZIP 完整性。"""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import zipfile
|
||||
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
spec = importlib.util.spec_from_file_location("package_firmware", REPO / "scripts/package_firmware.py")
|
||||
package = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(package)
|
||||
|
||||
|
||||
class PackageFirmwareTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="rmic-package-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
self.release = self.root / "external-target/xtensa-esp32s3-espidf/release"
|
||||
self.release.mkdir(parents=True)
|
||||
self.elf = self.release / "esp32"
|
||||
self.elf.write_bytes(b"current-elf")
|
||||
(self.release / "bootloader.bin").write_bytes(b"current-bootloader")
|
||||
(self.release / "partition-table.bin").write_bytes(b"\xff" * 0xC00)
|
||||
self.output = self.root / "new-firmware"
|
||||
|
||||
def test_cargo_metadata_respects_external_target_directory(self):
|
||||
with patch.dict(os.environ, {"CARGO_TARGET_DIR": str(self.root / "external-target")}):
|
||||
self.assertEqual(package.resolve_elf(REPO, "").resolve(), self.elf.resolve())
|
||||
|
||||
def test_cargo_config_target_directory(self):
|
||||
# Run real metadata in an isolated crate, without compiling dependencies.
|
||||
crate = self.root / "crate"
|
||||
(crate / ".cargo").mkdir(parents=True)
|
||||
(crate / "src").mkdir()
|
||||
(crate / "src/main.rs").write_text("fn main() {}\n")
|
||||
(crate / "Cargo.toml").write_text('[package]\nname="fixture"\nversion="0.1.0"\n')
|
||||
(crate / ".cargo/config.toml").write_text(
|
||||
'[build]\ntarget-dir=' + json.dumps(str(self.root / "external-target")) + "\n"
|
||||
)
|
||||
with patch.dict(os.environ):
|
||||
os.environ.pop("CARGO_TARGET_DIR", None)
|
||||
self.assertEqual(package.resolve_elf(crate, "").resolve(), self.elf.resolve())
|
||||
|
||||
def test_missing_elf_does_not_reuse_old_app(self):
|
||||
self.output.mkdir()
|
||||
app = self.output / "esp32s3-app.bin"
|
||||
app.write_bytes(b"old-app")
|
||||
with self.assertRaisesRegex(SystemExit, "ELF 不存在"):
|
||||
package.export_app(REPO, self.output, self.release / "missing", False)
|
||||
self.assertEqual(app.read_bytes(), b"old-app")
|
||||
|
||||
def test_missing_companion_stops_before_export(self):
|
||||
(self.release / "bootloader.bin").unlink()
|
||||
with patch.object(package.subprocess, "run") as run:
|
||||
with self.assertRaisesRegex(SystemExit, "配套镜像"):
|
||||
package.export_app(REPO, self.output, self.elf, False)
|
||||
run.assert_not_called()
|
||||
|
||||
def test_export_failure_does_not_create_archive(self):
|
||||
with patch.object(package.shutil, "which", return_value=sys.executable):
|
||||
with patch.object(package.subprocess, "run", return_value=subprocess.CompletedProcess([], 1)):
|
||||
with self.assertRaisesRegex(SystemExit, "save-image 失败"):
|
||||
package.export_app(REPO, self.output, self.elf, False)
|
||||
self.assertEqual(list(self.root.rglob("*.zip")), [])
|
||||
|
||||
def test_package_replaces_newer_old_images_and_is_reproducible(self):
|
||||
self.output.mkdir()
|
||||
old_app = self.output / "esp32s3-app.bin"
|
||||
old_app.write_bytes(b"old-app")
|
||||
os.utime(old_app, (self.elf.stat().st_mtime + 100, self.elf.stat().st_mtime + 100))
|
||||
(self.output / "BUILD-INFO.json").write_text(
|
||||
'{"verification":{"hardware_flashed_and_tested":true},"old_test_results":true}'
|
||||
)
|
||||
original_run = subprocess.run
|
||||
|
||||
def run(command, *args, **kwargs):
|
||||
if "save-image" in command:
|
||||
self.assertEqual(Path(command[-2]).resolve(), self.elf.resolve())
|
||||
Path(command[-1]).write_bytes(b"app-from-current-elf")
|
||||
return subprocess.CompletedProcess(command, 0)
|
||||
return original_run(command, *args, **kwargs)
|
||||
|
||||
arguments = ["package_firmware.py", "--elf", str(self.elf), "--firmware", str(self.output)]
|
||||
with patch.object(sys, "argv", arguments), patch.object(package.subprocess, "run", side_effect=run):
|
||||
with patch.object(package.shutil, "which", return_value=sys.executable):
|
||||
self.assertEqual(package.main(), 0)
|
||||
archive = next(self.output.glob("*.zip"))
|
||||
first = archive.read_bytes()
|
||||
self.assertEqual(package.main(), 0)
|
||||
self.assertEqual(archive.read_bytes(), first)
|
||||
|
||||
with zipfile.ZipFile(archive) as bundle:
|
||||
self.assertIsNone(bundle.testzip())
|
||||
self.assertEqual(len(bundle.namelist()), 5)
|
||||
self.assertEqual(bundle.read("esp32s3-app.bin"), b"app-from-current-elf")
|
||||
self.assertEqual(bundle.read("bootloader.bin"), b"current-bootloader")
|
||||
self.assertEqual(bundle.read("partition-table.bin"), b"\xff" * 0xC00)
|
||||
manifest = json.loads(bundle.read("bundle.json"))
|
||||
for filename, key in (("esp32s3-app.bin", "appSha256"),
|
||||
("partition-table.bin", "partitionTableSha256"),
|
||||
("bootloader.bin", "bootloaderSha256")):
|
||||
self.assertEqual(hashlib.sha256(bundle.read(filename)).hexdigest(), manifest[key])
|
||||
metadata = json.loads(bundle.read("BUILD-INFO.json"))
|
||||
self.assertFalse(metadata["verification"]["hardware_flashed_and_tested"])
|
||||
self.assertNotIn("old_test_results", metadata)
|
||||
digest = hashlib.sha256(first).hexdigest()
|
||||
self.assertEqual(archive.with_name(archive.name + ".sha256").read_text().split()[0], digest)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,237 @@
|
||||
#!/usr/bin/env python3
|
||||
"""独立验证相机 UDP 图传线路的诊断脚本。
|
||||
|
||||
不依赖 Rust,也不依赖 protocol crate——正因为如此,它能当作线路格式的
|
||||
**独立**检查:如果 protocol crate 的编码有错,这个脚本(手写的常量)仍然
|
||||
按文档解析,会立刻报出不一致。
|
||||
|
||||
用法:
|
||||
|
||||
python3 vt/scripts/udp_probe.py [秒数]
|
||||
|
||||
它做三件事:
|
||||
1. 广播一次 Subscribe,触发板子开始推流
|
||||
2. 解析收到的数据报,按 sender_id 重组
|
||||
3. 报告帧率、丢帧、以及是否发现了板子的 Hello
|
||||
|
||||
常量是手写的,与 protocol/src/lib.rs 保持一致。改了协议记得改这里——
|
||||
这正是它作为交叉检查的价值所在。
|
||||
"""
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
# ---- 与 protocol/src/lib.rs 一致 ----
|
||||
HEADER = 27 # magic4 + type1 + ver2 + sender4 + frame4 + idx2 + cnt2 + len4 + w2 + h2
|
||||
MAGIC = 0x4D564331 # "MVC1"
|
||||
FRAG = 1400 # MAX_FRAGMENT_PAYLOAD
|
||||
PORT = 5600 # DEFAULT_PORT
|
||||
BROADCAST = "255.255.255.255"
|
||||
|
||||
MSG_VIDEO = 1
|
||||
MSG_SUBSCRIBE = 2
|
||||
MSG_HELLO = 3
|
||||
MSG_HEARTBEAT = 4
|
||||
MSG_ARMOR_HEALTH = 5
|
||||
MSG_ARMOR_CONTROL = 6
|
||||
MSG_MATCH_STATE = 7
|
||||
MSG_ARMOR_DAMAGE_CONTROL = 8
|
||||
|
||||
TYPE_NAMES = {
|
||||
MSG_VIDEO: "video",
|
||||
MSG_SUBSCRIBE: "subscribe",
|
||||
MSG_HELLO: "hello",
|
||||
MSG_HEARTBEAT: "heartbeat",
|
||||
MSG_ARMOR_HEALTH: "armor-health",
|
||||
MSG_ARMOR_CONTROL: "armor-control",
|
||||
MSG_MATCH_STATE: "match-state",
|
||||
MSG_ARMOR_DAMAGE_CONTROL: "armor-damage-control",
|
||||
}
|
||||
|
||||
|
||||
def decode(data):
|
||||
"""把一个数据报解析成 (msg_type, header_dict, payload)。"""
|
||||
if len(data) < HEADER:
|
||||
return None
|
||||
|
||||
magic = int.from_bytes(data[0:4], "little")
|
||||
if magic != MAGIC:
|
||||
return None
|
||||
|
||||
msg_type = data[4]
|
||||
header = {
|
||||
"version": int.from_bytes(data[5:7], "little"),
|
||||
"sender_id": int.from_bytes(data[7:11], "little"),
|
||||
"frame_id": int.from_bytes(data[11:15], "little"),
|
||||
"frag_index": int.from_bytes(data[15:17], "little"),
|
||||
"frag_count": int.from_bytes(data[17:19], "little"),
|
||||
"total_len": int.from_bytes(data[19:23], "little"),
|
||||
"width": int.from_bytes(data[23:25], "little"),
|
||||
"height": int.from_bytes(data[25:27], "little"),
|
||||
}
|
||||
return msg_type, header, data[HEADER:]
|
||||
|
||||
|
||||
def main():
|
||||
duration = float(sys.argv[1]) if len(sys.argv) > 1 else 10.0
|
||||
host = sys.argv[2] if len(sys.argv) > 2 else BROADCAST
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
sock.bind(("", PORT))
|
||||
sock.settimeout(0.5)
|
||||
|
||||
# 订阅:板子看到它就开始往本机推流。
|
||||
#
|
||||
# role 字节紧跟在 HEADER 之后,也就是偏移 HEADER 处。之前这里多填了 12 个
|
||||
# 零字节,role 落到了偏移 39——板子的 Subscribe::decode 严格按偏移读,于是
|
||||
# 认不出 role 而拒收,表现为"板子在线但 0 clients subscribed"。
|
||||
# 这里刻意手写而不是复用 protocol crate:这个脚本的意义就在于独立验证,
|
||||
# role 的位置写错时它会给出和固件一致的结论,而不是把错误藏起来。
|
||||
header = (
|
||||
MAGIC.to_bytes(4, "little")
|
||||
+ bytes([MSG_SUBSCRIBE])
|
||||
+ (1).to_bytes(2, "little") # version
|
||||
+ (0x0C110001).to_bytes(4, "little") # client_id
|
||||
+ b"\x00" * 4 # frame_id
|
||||
+ b"\x00" * 4 # frag_index + frag_count
|
||||
+ b"\x00" * 4 # total_len
|
||||
+ b"\x00" * 4 # width + height
|
||||
)
|
||||
sub = header + bytes([2]) # role = referee,紧跟 27 字节头
|
||||
sock.sendto(sub, (host, PORT))
|
||||
print(f"已向 {host}:{PORT} 广播订阅(role=referee),监听 {duration:.0f} 秒…")
|
||||
|
||||
# 每个发送方一份重组状态:两块板的 frame_id 各自独立,混在一起会互相顶掉。
|
||||
pending = {}
|
||||
boards = {}
|
||||
counters = defaultdict(int)
|
||||
sizes = []
|
||||
start = time.time()
|
||||
last_print = start
|
||||
prev_frames = 0
|
||||
prev_pkts = 0
|
||||
prev_drops = 0
|
||||
last_subscribe = start
|
||||
|
||||
while time.time() - start < duration:
|
||||
if time.time() - last_subscribe >= 0.8:
|
||||
sock.sendto(sub, (host, PORT))
|
||||
last_subscribe = time.time()
|
||||
try:
|
||||
data, addr = sock.recvfrom(2048)
|
||||
except socket.timeout:
|
||||
continue
|
||||
|
||||
parsed = decode(data)
|
||||
if parsed is None:
|
||||
counters["无法解析"] += 1
|
||||
continue
|
||||
|
||||
msg_type, h, payload = parsed
|
||||
counters[f"type:{TYPE_NAMES.get(msg_type, msg_type)}"] += 1
|
||||
|
||||
if msg_type in (MSG_HELLO, MSG_HEARTBEAT):
|
||||
boards[h["sender_id"]] = addr
|
||||
continue
|
||||
|
||||
if msg_type != MSG_VIDEO:
|
||||
continue
|
||||
|
||||
sid = h["sender_id"]
|
||||
|
||||
# 与 Fragment::decode 相同的自洽性检查。
|
||||
if h["frag_count"] == 0 or h["frag_index"] >= h["frag_count"]:
|
||||
counters["分片索引非法"] += 1
|
||||
continue
|
||||
if len(payload) > h["total_len"]:
|
||||
counters["载荷超过总长"] += 1
|
||||
continue
|
||||
|
||||
# 重组状态必须按 (sender_id, frame_id) 存,缺一不可。
|
||||
#
|
||||
# 之前这里只按 sender_id 存,于是某一帧丢了分片之后,下一帧的分片会接着往
|
||||
# 同一个计数器里凑,凑够了就交出去一张混着两帧的坏 JPEG——报成 34 张
|
||||
# "JPEG 不完整",看起来像重复分片或丢包的证据,其实是这个键选错了。
|
||||
# protocol crate 的 FrameAssembler 一直按 frame_id 区分(换个 frame_id
|
||||
# 就重置),这里原先跟它不一致。
|
||||
key = (sid, h["frame_id"])
|
||||
|
||||
state = pending.get(key)
|
||||
if state is None:
|
||||
# 新的一帧到了:丢掉之前那帧的半成品。实时画面宁可少一帧,也不等它。
|
||||
# 这些帧算"被新帧取代",不是"JPEG 不完整"——它们本来就不完整,
|
||||
# 混在一起会把两种情形都算成链路有问题。
|
||||
counters["被新帧取代"] += len(pending)
|
||||
pending = {
|
||||
key: {
|
||||
"buf": bytearray(h["total_len"]),
|
||||
"have": set(),
|
||||
"expect": h["frag_count"],
|
||||
"total": h["total_len"],
|
||||
"w": h["width"],
|
||||
"h": h["height"],
|
||||
"started": time.time(),
|
||||
}
|
||||
}
|
||||
state = pending[key]
|
||||
|
||||
# 同一帧内的重复分片直接跳过且不计数:否则 seen 达标而缓冲区仍有空洞。
|
||||
if h["frag_index"] in state["have"]:
|
||||
counters["重复分片"] += 1
|
||||
continue
|
||||
state["have"].add(h["frag_index"])
|
||||
|
||||
off = h["frag_index"] * FRAG
|
||||
state["buf"][off:off + len(payload)] = payload
|
||||
|
||||
tail = (h["total_len"] - 1) // FRAG
|
||||
if len(state["have"]) >= state["expect"] and tail in state["have"]:
|
||||
jpeg = bytes(state["buf"][:state["total"]])
|
||||
if jpeg[:2] == b"\xff\xd8" and jpeg[-2:] == b"\xff\xd9":
|
||||
counters["完整帧"] += 1
|
||||
sizes.append((state["total"], state["w"], state["h"]))
|
||||
else:
|
||||
counters["JPEG 不完整"] += 1
|
||||
del pending[key]
|
||||
|
||||
now = time.time()
|
||||
if now - last_print >= 2.0:
|
||||
# 分子分母必须都是本窗口的增量。早先用累计帧数除以窗口时长,于是报出
|
||||
# 39、61、79 这种随时间单调上升的假 fps——看起来像板子越跑越快。
|
||||
elapsed = now - last_print
|
||||
window_frames = counters["完整帧"] - prev_frames
|
||||
window_pkts = counters["type:video"] - prev_pkts
|
||||
window_drops = counters["JPEG 不完整"] - prev_drops
|
||||
loss = 100.0 * window_drops / max(window_frames + window_drops, 1)
|
||||
print(
|
||||
f" {window_frames / elapsed:5.1f} fps "
|
||||
f"包/s={window_pkts / elapsed:5.0f} "
|
||||
f"完整帧={counters['完整帧']:4d} "
|
||||
f"丢弃={window_drops:3d} ({loss:.1f}%)"
|
||||
)
|
||||
prev_frames, prev_pkts, prev_drops = (
|
||||
counters["完整帧"],
|
||||
counters["type:video"],
|
||||
counters["JPEG 不完整"],
|
||||
)
|
||||
last_print = now
|
||||
|
||||
sock.close()
|
||||
|
||||
total_time = time.time() - start
|
||||
print()
|
||||
print("板子:", ", ".join(f"0x{k:08X} @ {v[0]}" for k, v in boards.items()) or "(未发现)")
|
||||
print("完整帧:", counters["完整帧"], " 累计视频包:", counters["type:video"])
|
||||
if counters["完整帧"]:
|
||||
avg = sum(s[0] for s in sizes) / len(sizes)
|
||||
print(f"平均帧: {avg:.0f} 字节 {sizes[0][1]}x{sizes[0][2]}")
|
||||
print(f"吞吐: {sum(s[0] for s in sizes) / total_time / 1024:.1f} kB/s")
|
||||
bad = {k: v for k, v in counters.items() if k.startswith(("无法", "JPEG", "分片", "载荷"))}
|
||||
print("异常:", bad or "无")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user