91 lines
2.9 KiB
Python
91 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
||
"""逐模块校验固件里的 QR 编码器:C++ 生成的矩阵必须和 python qrcode 完全一致。
|
||
|
||
做法:C++ 侧输出矩阵与它选中的掩码,python 侧用同一版本、同一纠错等级、
|
||
同一掩码重新生成,然后逐位比较。完全一致才能说明数据编码、RS 纠错、交织、
|
||
功能图案、掩码与格式信息全部正确(掩码是否"最优"不影响可扫描性)。
|
||
|
||
用法:
|
||
python3 tools/qr_verify.py
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import subprocess
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import qrcode
|
||
from qrcode.constants import ERROR_CORRECT_M
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
BIN = ROOT / "build" / "qr_dump"
|
||
|
||
CASES = [
|
||
"http://192.168.2.147:5173/qr?t=34RQUPF6S3",
|
||
"http://nexbuddy.local/qr?t=ABCDEFGHJK",
|
||
"https://buddy.example.com/qr?t=ZZZZZZZZZZ",
|
||
"http://10.0.0.2:5173/qr?t=ABCD2345EF", # 短 → v3
|
||
"http://192.168.100.200:5173/qr?t=ABCDEFGHJK", # 略长 → v5
|
||
"https://a-very-long-subdomain.example.com/knot/qr?t=" + "A" * 30, # v6
|
||
"https://a-very-long-subdomain.example.com/knot/qr?t=" + "B" * 64, # v7:带版本信息块
|
||
"a",
|
||
]
|
||
|
||
|
||
def dump(text: str) -> tuple[int, int, list[str]]:
|
||
out = subprocess.run([str(BIN), text], capture_output=True, text=True, check=True).stdout
|
||
lines = out.splitlines()
|
||
head = lines[0].split()
|
||
if head[0] == "FAIL":
|
||
raise SystemExit(f"C++ 侧编码失败:{text!r}")
|
||
side, mask = int(head[0]), int(head[1])
|
||
rows = lines[1:]
|
||
assert len(rows) == side, f"行数 {len(rows)} != {side}"
|
||
return side, mask, rows
|
||
|
||
|
||
def verify(text: str) -> None:
|
||
side, mask, rows = dump(text)
|
||
ver = (side - 8 - 17) // 4
|
||
|
||
qr = qrcode.QRCode(
|
||
version=ver,
|
||
error_correction=ERROR_CORRECT_M,
|
||
box_size=1,
|
||
border=4,
|
||
mask_pattern=mask,
|
||
)
|
||
qr.add_data(text.encode("utf-8"), optimize=0) # 固定走 byte 模式
|
||
qr.make(fit=False)
|
||
mod = qr.get_matrix() # 已含静区
|
||
|
||
if len(mod) != side:
|
||
raise SystemExit(f"{text!r}: 尺寸不一致 {len(mod)} vs {side}")
|
||
|
||
diff = 0
|
||
first = None
|
||
for y in range(side):
|
||
row = "".join("1" if m else "0" for m in mod[y])
|
||
if row != rows[y]:
|
||
for x in range(side):
|
||
if row[x] != rows[y][x]:
|
||
diff += 1
|
||
if first is None:
|
||
first = (x, y)
|
||
if diff:
|
||
raise SystemExit(f"{text!r}: {diff} 个模块不一致,首个差异 @{first}")
|
||
print(f"[PASS] v{ver} mask={mask} {len(text):2d}B {text!r}")
|
||
|
||
|
||
def main() -> None:
|
||
if not BIN.exists():
|
||
raise SystemExit(f"缺少 {BIN},先跑 tools/qr_verify.sh")
|
||
for c in CASES:
|
||
verify(c)
|
||
print("\nQR 编码器与 python qrcode 完全一致")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|