V0.4.0加入锁定二维码
This commit is contained in:
@@ -1,27 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
import re
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
gradle = (ROOT/'android/app/build.gradle.kts').read_text()
|
||||
manifest = (ROOT/'android/app/src/main/AndroidManifest.xml').read_text()
|
||||
wifi = (ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_text()
|
||||
upload = (ROOT/'android/app/src/main/java/com/qft/optical/UploadClient.kt').read_text()
|
||||
main = (ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text()
|
||||
gray = (ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text()
|
||||
security = (ROOT/'android/app/src/main/res/xml/network_security_config.xml').read_text()
|
||||
|
||||
assert re.search(r'minSdk\s*=\s*24', gradle)
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
gradle=(ROOT/'android/app/build.gradle.kts').read_text(); manifest=(ROOT/'android/app/src/main/AndroidManifest.xml').read_text()
|
||||
wifi=(ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_text(); upload=(ROOT/'android/app/src/main/java/com/qft/optical/UploadClient.kt').read_text()
|
||||
main=(ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text(); analyzer=(ROOT/'android/app/src/main/java/com/qft/optical/QrAnalyzer.kt').read_text()
|
||||
gray=(ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text(); protocol=(ROOT/'android/app/src/main/java/com/qft/optical/Protocol.kt').read_text(); base45=(ROOT/'android/app/src/main/java/com/qft/optical/Base45.kt').read_text(); overlay=(ROOT/'android/app/src/main/java/com/qft/optical/QrLockOverlay.kt').read_text(); security=(ROOT/'android/app/src/main/res/xml/network_security_config.xml').read_text()
|
||||
assert re.search(r'minSdk\s*=\s*24',gradle)
|
||||
assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest
|
||||
assert 'ACCESS_FINE_LOCATION" android:maxSdkVersion="32"' in manifest
|
||||
assert 'NEARBY_WIFI_DEVICES' in manifest
|
||||
assert 'networkSecurityConfig="@xml/network_security_config"' in manifest
|
||||
assert 'cleartextTrafficPermitted="true"' in security
|
||||
assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi
|
||||
assert 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi
|
||||
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload and 'workers = 24' in upload and 'desiredChunkSize' in upload and 'CHUNK_LARGE' in upload
|
||||
assert 'Size(640, 480)' in main and 'Size(1280, 720)' in main
|
||||
assert 'STRATEGY_KEEP_ONLY_LATEST' in main
|
||||
assert 'rotate90' not in gray and 'image.imageInfo.rotationDegrees' not in gray
|
||||
all_kotlin = '\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt'))
|
||||
assert 'ACCESS_FINE_LOCATION" android:maxSdkVersion="32"' in manifest and 'NEARBY_WIFI_DEVICES' in manifest
|
||||
assert 'networkSecurityConfig="@xml/network_security_config"' in manifest and 'cleartextTrafficPermitted="true"' in security
|
||||
assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi and 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi
|
||||
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload
|
||||
assert 'val targetSize = Size(640, 480)' in main and 'Size(960, 540)' not in main
|
||||
assert 'Camera2Interop.Extender' in main and 'CONTROL_AE_TARGET_FPS_RANGE' in main and 'STRATEGY_KEEP_ONLY_LATEST' in main
|
||||
assert '设备拒绝显式高帧率请求' in main and 'fallbackAnalysis' in main
|
||||
assert 'OPTICAL_LOCKED' in analyzer and 'OPTICAL_MULTI' not in analyzer and 'QRCodeReader' in analyzer and 'MultiFormatReader' not in analyzer
|
||||
assert 'LockRect.fromPoints' in analyzer and 'grayBuffer.capture(image, current)' in analyzer
|
||||
assert 'GrayFrameBuffer' in gray and 'scratch = ByteArray(0)' in gray
|
||||
assert 'Base45.decode' in protocol and 'QFT2' in protocol and 'looksLikeBinaryFrame' not in protocol
|
||||
assert 'lockedCenterInView' in overlay and 'postInvalidateDelayed' in overlay and 'maybeRefocusLockedQr' in main
|
||||
assert 'assembler.acceptText(code.text)' in main and 'acceptBinary' not in main
|
||||
assert 'BB8' in base45 or 'ALPHABET' in base45
|
||||
all_kotlin='\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt'))
|
||||
assert 'java.util.Base64' not in all_kotlin
|
||||
print('PASS Android compatibility/static guards: minSdk24, API29 split, legacy storage/location, Android13 nearby-WiFi, cleartext local config, subnet fallback, fast scanner paths')
|
||||
print('PASS Android static guards: API24+, 640x480 single-QR ROI, reusable luma buffer, QFT2/Base45 text parse, dynamic lock/refocus, Camera2 FPS request, legacy/new Wi-Fi compatibility')
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Host-side Kotlin smoke tests. Uses kotlinc if present; does not require Android SDK."""
|
||||
from pathlib import Path
|
||||
import shutil, subprocess, tempfile, textwrap, os
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
K=ROOT/'android/app/src/main/java/com/qft/optical'
|
||||
kotlinc=shutil.which('kotlinc')
|
||||
if not kotlinc:
|
||||
print('SKIP Kotlin host smoke: kotlinc not installed (Android Gradle tests still cover these files on a dev host)')
|
||||
raise SystemExit(0)
|
||||
|
||||
def run(args):
|
||||
env=os.environ.copy(); env.setdefault('TERM','xterm')
|
||||
p=subprocess.run(args, text=True, capture_output=True, env=env)
|
||||
if p.returncode:
|
||||
print(p.stdout); print(p.stderr); raise SystemExit(p.returncode)
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td=Path(td)
|
||||
smoke=td/'Smoke.kt'
|
||||
smoke.write_text(textwrap.dedent(r'''
|
||||
package com.qft.optical
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.zip.CRC32
|
||||
fun b45e(data: ByteArray): String { val a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; val o=StringBuilder(); var i=0; while(i+1<data.size){val v=(data[i].toInt() and 255)*256+(data[i+1].toInt() and 255);o.append(a[v%45]).append(a[(v/45)%45]).append(a[v/2025]);i+=2};if(i<data.size){val v=data[i].toInt() and 255;o.append(a[v%45]).append(a[v/45])};return o.toString() }
|
||||
fun fr(p:ByteArray):String { val b=ByteBuffer.allocate(24+p.size+4).order(ByteOrder.BIG_ENDIAN);b.put("QFT2".toByteArray()).put(2).put(2).putLong(7L).putInt(9).putInt(11).putShort(p.size.toShort()).put(p);val n=b.position();val c=CRC32().apply{update(b.array(),0,n)}.value;b.putInt(c.toInt());return "QFT2:"+b45e(b.array()) }
|
||||
fun main(){check(Base45.decode("BB8")!!.contentEquals("AB".toByteArray()));check(Base45.decode("%69 VD92EX0")!!.contentEquals("Hello!!".toByteArray()));val p="hello-qft2".toByteArray();val f=QftProtocol.parseText(fr(p))!!;check(f.kind==FrameKind.DATA&&f.sessionId==7L&&f.seq==9L&&f.payload.contentEquals(p));val c=LockRect(100,100,300,300).smoothToward(LockRect(140,130,340,340),.25f);check(c.left in 101..139);println("PASS Kotlin QFT2/Base45 protocol + ROI lock smoothing")}
|
||||
'''))
|
||||
jar=td/'smoke.jar'
|
||||
run([kotlinc, str(K/'Base45.kt'), str(K/'Base64Url.kt'), str(K/'Protocol.kt'), str(K/'LockRect.kt'), str(smoke), '-include-runtime', '-d', str(jar)])
|
||||
p=subprocess.run(['java','-jar',str(jar)],text=True,capture_output=True,env={**os.environ,'TERM':'xterm'},check=True)
|
||||
print(p.stdout.strip())
|
||||
|
||||
# CameraX/ZXing-shaped compile stubs: catches Kotlin signature/syntax drift in the analyzer without Android SDK.
|
||||
for d in ['android/os','androidx/camera/core','com/google/zxing/common','com/google/zxing/qrcode','com/google/zxing']:
|
||||
(td/d).mkdir(parents=True,exist_ok=True)
|
||||
(td/'android/os/SystemClock.kt').write_text('package android.os\nobject SystemClock { fun elapsedRealtime(): Long = 0L }\n')
|
||||
(td/'androidx/camera/core/Core.kt').write_text(textwrap.dedent('''
|
||||
package androidx.camera.core
|
||||
import java.nio.ByteBuffer
|
||||
interface ImageAnalysis { interface Analyzer { fun analyze(image: ImageProxy) } }
|
||||
interface ImageProxy { val width:Int; val height:Int; val planes:Array<PlaneProxy>; val imageInfo:ImageInfo; fun close(); interface PlaneProxy { val buffer:ByteBuffer; val rowStride:Int; val pixelStride:Int }; interface ImageInfo { val rotationDegrees:Int } }
|
||||
'''))
|
||||
(td/'com/google/zxing/Zxing.kt').write_text('package com.google.zxing\nopen class LuminanceSource(val width:Int,val height:Int)\nclass PlanarYUVLuminanceSource(data:ByteArray,dataWidth:Int,dataHeight:Int,left:Int,top:Int,width:Int,height:Int,reverseHorizontal:Boolean):LuminanceSource(width,height)\nclass BinaryBitmap(val binarizer:Any)\ndata class ResultPoint(val x:Float,val y:Float)\nclass Result(val text:String?="",val rawBytes:ByteArray?=null,val resultPoints:Array<ResultPoint>?=null)\n')
|
||||
(td/'com/google/zxing/common/Common.kt').write_text('package com.google.zxing.common\nimport com.google.zxing.LuminanceSource\nclass GlobalHistogramBinarizer(source:LuminanceSource)\nclass HybridBinarizer(source:LuminanceSource)\n')
|
||||
(td/'com/google/zxing/qrcode/QRCodeReader.kt').write_text('package com.google.zxing.qrcode\nimport com.google.zxing.BinaryBitmap\nimport com.google.zxing.Result\nclass QRCodeReader { fun decode(bitmap:BinaryBitmap):Result=Result(); fun reset(){} }\n')
|
||||
out=td/'analyzer.jar'
|
||||
sources=[td/'android/os/SystemClock.kt',td/'androidx/camera/core/Core.kt',td/'com/google/zxing/Zxing.kt',td/'com/google/zxing/common/Common.kt',td/'com/google/zxing/qrcode/QRCodeReader.kt',K/'LockRect.kt',K/'ScannerLockState.kt',K/'GrayFrame.kt',K/'QrAnalyzer.kt']
|
||||
run([kotlinc,*map(str,sources),'-d',str(out)])
|
||||
print('PASS Kotlin QrAnalyzer compile smoke with CameraX/ZXing-shaped stubs')
|
||||
@@ -2,16 +2,9 @@
|
||||
MAX_CACHE_MIB = 768
|
||||
MAX_PAGES = 192
|
||||
HARD_MIB = 1100
|
||||
|
||||
def calc(side):
|
||||
bpp = side * side * 4
|
||||
pages = max(4, min(MAX_PAGES, MAX_CACHE_MIB * 1024 * 1024 // bpp))
|
||||
managed = pages * bpp / (1024 * 1024)
|
||||
return pages, managed
|
||||
|
||||
p4, m4 = calc(960)
|
||||
p1, m1 = calc(760)
|
||||
# Include a conservative 64 MiB transient batch/decoder allowance in this design-level bound.
|
||||
assert m4 + 64 < HARD_MIB
|
||||
assert m1 + 64 < HARD_MIB
|
||||
print(f"PASS memory budget: 4QR cache={p4} pages/{m4:.1f} MiB; 1QR cache={p1} pages/{m1:.1f} MiB; hard design ceiling={HARD_MIB} MiB")
|
||||
SIDE = 1024
|
||||
bpp = SIDE * SIDE * 4
|
||||
pages = max(4, min(MAX_PAGES, MAX_CACHE_MIB * 1024 * 1024 // bpp))
|
||||
managed = pages * bpp / (1024 * 1024)
|
||||
assert managed + 96 < HARD_MIB
|
||||
print(f"PASS memory budget: single-QR cache={pages} frames/{managed:.1f} MiB + 96 MiB transient allowance < {HARD_MIB} MiB")
|
||||
|
||||
@@ -1,55 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synthetic visual-path smoke test for the 4-QR optical page and QFTPAIR2.
|
||||
Requires: qrcode, numpy, opencv-python, pyzbar/libzbar.
|
||||
This is intentionally not a substitute for a real display/camera test.
|
||||
"""
|
||||
import base64, json, os, time
|
||||
"""Synthetic QFT2/Base45 single-QR acquisition/ROI smoke test. Not a physical camera test."""
|
||||
import binascii, os, struct, time
|
||||
import cv2
|
||||
import numpy as np
|
||||
import qrcode
|
||||
from pyzbar.pyzbar import decode as zdecode, ZBarSymbol
|
||||
from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M
|
||||
from qrcode.constants import ERROR_CORRECT_L
|
||||
|
||||
B45="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
|
||||
def b45(data):
|
||||
out=[]; i=0
|
||||
while i+1 < len(data):
|
||||
v=data[i]*256+data[i+1]; out += [B45[v%45],B45[(v//45)%45],B45[v//2025]]; i+=2
|
||||
if i<len(data):
|
||||
v=data[i]; out += [B45[v%45],B45[v//45]]
|
||||
return ''.join(out)
|
||||
|
||||
def make_qr(text: str, ec, target: int):
|
||||
qr = qrcode.QRCode(version=None, error_correction=ec, box_size=1, border=4)
|
||||
qr.add_data(text); qr.make(fit=True)
|
||||
mat = np.asarray(qr.get_matrix(), dtype=np.uint8)
|
||||
scale = max(1, target // mat.shape[0])
|
||||
return ((1 - np.kron(mat, np.ones((scale, scale), np.uint8))) * 255).astype(np.uint8), qr.version
|
||||
payload=os.urandom(450)
|
||||
body=b"QFT2"+bytes([2,2])+struct.pack(">QIIH",0x1020304050607080,7,1000,len(payload))+payload
|
||||
raw=body+struct.pack(">I",binascii.crc32(body)&0xffffffff)
|
||||
text="QFT2:"+b45(raw)
|
||||
qr=qrcode.QRCode(version=None,error_correction=ERROR_CORRECT_L,box_size=1,border=4)
|
||||
qr.add_data(text); qr.make(fit=True)
|
||||
assert qr.version <= 15, qr.version
|
||||
mat=np.asarray(qr.get_matrix(),dtype=np.uint8)
|
||||
# Make the large single code fill ~70% of the 480px analysis height.
|
||||
scale=max(1,340//mat.shape[0])
|
||||
symbol=((1-np.kron(mat,np.ones((scale,scale),np.uint8)))*255).astype(np.uint8)
|
||||
canvas=np.full((480,640),255,np.uint8)
|
||||
side=symbol.shape[0]; x=max(8,(640-side)//2); y=max(8,(480-side)//2)
|
||||
canvas[y:y+side,x:x+side]=symbol
|
||||
rot=cv2.getRotationMatrix2D((320,240),3.0,1.0)
|
||||
frame=cv2.warpAffine(canvas,rot,(640,480),borderValue=255)
|
||||
frame=cv2.GaussianBlur(frame,(3,3),0.35)
|
||||
expected=text.encode()
|
||||
found=zdecode(frame,symbols=[ZBarSymbol.QRCODE]); assert any(r.data==expected for r in found)
|
||||
r=next(r for r in found if r.data==expected)
|
||||
pad=int(max(r.rect.width,r.rect.height)*0.08)
|
||||
l=max(0,r.rect.left-pad); t=max(0,r.rect.top-pad); rr=min(frame.shape[1],r.rect.left+r.rect.width+pad); bb=min(frame.shape[0],r.rect.top+r.rect.height+pad)
|
||||
roi=frame[t:bb,l:rr]
|
||||
assert any(z.data==expected for z in zdecode(roi,symbols=[ZBarSymbol.QRCODE]))
|
||||
area=roi.size/frame.size; assert area < 0.80
|
||||
|
||||
# Four data QR symbols at the same density used by v0.3 (about 1243 chars/frame).
|
||||
texts = ["QFT1:" + base64.urlsafe_b64encode(os.urandom(928)).decode().rstrip("=") for _ in range(4)]
|
||||
canvas = np.full((960, 960), 255, np.uint8)
|
||||
gutter = 15
|
||||
cell = (960 - gutter * 3) // 2
|
||||
for idx, text in enumerate(texts):
|
||||
img, version = make_qr(text, ERROR_CORRECT_L, cell)
|
||||
row, col = divmod(idx, 2)
|
||||
x = gutter + col * (cell + gutter) + (cell - img.shape[1]) // 2
|
||||
y = gutter + row * (cell + gutter) + (cell - img.shape[0]) // 2
|
||||
canvas[y:y+img.shape[0], x:x+img.shape[1]] = img
|
||||
started = time.perf_counter()
|
||||
found = {r.data.decode() for r in zdecode(canvas, symbols=[ZBarSymbol.QRCODE])}
|
||||
elapsed = time.perf_counter() - started
|
||||
assert found == set(texts), (len(found), len(texts))
|
||||
|
||||
# Pairing QR: downscale + rotate + slight blur to exercise acquisition margin.
|
||||
v2 = {
|
||||
"v":2,"s":"qft_test_session_128bit_XY","n":"DESKTOP-QFT","p":39393,
|
||||
"e":["http://192.168.137.1:39393"],
|
||||
"w":["QFT-DESKTOP-abc123","3xamplePassw0rd"],
|
||||
}
|
||||
raw = json.dumps(v2, separators=(",", ":"), ensure_ascii=False).encode()
|
||||
pair_text = "QFTPAIR2:" + base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||
pair, pair_ver = make_qr(pair_text, ERROR_CORRECT_M, 520)
|
||||
pair = cv2.resize(pair, (260, 260), interpolation=cv2.INTER_NEAREST)
|
||||
rot = cv2.getRotationMatrix2D((130, 130), 7.0, 1.0)
|
||||
pair = cv2.warpAffine(pair, rot, (300, 300), borderValue=255)
|
||||
pair = cv2.GaussianBlur(pair, (3, 3), 0.5)
|
||||
started2 = time.perf_counter()
|
||||
pair_found = [r.data.decode() for r in zdecode(pair, symbols=[ZBarSymbol.QRCODE])]
|
||||
elapsed2 = time.perf_counter() - started2
|
||||
assert pair_text in pair_found
|
||||
print(f"PASS synthetic QR decode: 4/4 optical QR v{version} decoded from 960px page in {elapsed*1000:.1f} ms; "
|
||||
f"QFTPAIR2 QR-M v{pair_ver} decoded after 7deg rotate+blur in {elapsed2*1000:.1f} ms")
|
||||
def avg_ms(img,loops=40):
|
||||
started=time.perf_counter()
|
||||
for _ in range(loops): zdecode(img,symbols=[ZBarSymbol.QRCODE])
|
||||
return (time.perf_counter()-started)*1000/loops
|
||||
full_ms=avg_ms(frame); roi_ms=avg_ms(roi)
|
||||
assert roi_ms < full_ms*1.15
|
||||
print(f"PASS synthetic QFT2 lock: QR-L v{qr.version}, {len(text)} chars; full={full_ms:.1f}ms, lockedROI={roi_ms:.1f}ms, ROI area={area*100:.1f}%")
|
||||
|
||||
@@ -3,96 +3,114 @@ import base64, binascii, hashlib, math, os, random, struct
|
||||
import qrcode
|
||||
from qrcode.constants import ERROR_CORRECT_L
|
||||
|
||||
PREFIX = "QFT1:"
|
||||
CHUNK = 900
|
||||
LANES = 4
|
||||
PREFIX = "QFT2:"
|
||||
LEGACY_PREFIX = "QFT1:"
|
||||
CHUNK = 450
|
||||
DISPLAY_FPS = 60
|
||||
B45 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
|
||||
|
||||
|
||||
def enc(kind, sid, seq, total, payload=b""):
|
||||
def b45encode(data: bytes) -> str:
|
||||
out=[]
|
||||
i=0
|
||||
while i+1 < len(data):
|
||||
v=data[i]*256+data[i+1]
|
||||
out += [B45[v%45], B45[(v//45)%45], B45[v//2025]]
|
||||
i += 2
|
||||
if i < len(data):
|
||||
v=data[i]
|
||||
out += [B45[v%45], B45[v//45]]
|
||||
return ''.join(out)
|
||||
|
||||
|
||||
def b45decode(text: str) -> bytes:
|
||||
rev={c:i for i,c in enumerate(B45)}
|
||||
out=bytearray(); i=0
|
||||
while i < len(text):
|
||||
rem=len(text)-i
|
||||
if rem == 1: raise ValueError('bad Base45 length')
|
||||
if rem >= 3:
|
||||
v=rev[text[i]] + 45*rev[text[i+1]] + 2025*rev[text[i+2]]
|
||||
if v > 0xffff: raise ValueError('overflow')
|
||||
out += bytes((v//256, v%256)); i += 3
|
||||
else:
|
||||
v=rev[text[i]] + 45*rev[text[i+1]]
|
||||
if v > 0xff: raise ValueError('overflow')
|
||||
out.append(v); i += 2
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def enc_binary(kind, sid, seq, total, payload=b""):
|
||||
body = b"QFT2" + bytes([2, kind]) + struct.pack(">QIIH", sid, seq, total, len(payload)) + payload
|
||||
crc = binascii.crc32(body) & 0xFFFFFFFF
|
||||
return body + struct.pack(">I", crc)
|
||||
|
||||
|
||||
def enc_text(kind, sid, seq, total, payload=b""):
|
||||
return PREFIX + b45encode(enc_binary(kind, sid, seq, total, payload))
|
||||
|
||||
|
||||
def legacy_text(kind, sid, seq, total, payload=b""):
|
||||
body = b"QFT1" + bytes([1, kind]) + struct.pack(">QIIH", sid, seq, total, len(payload)) + payload
|
||||
crc = binascii.crc32(body) & 0xFFFFFFFF
|
||||
return PREFIX + base64.urlsafe_b64encode(body + struct.pack(">I", crc)).decode().rstrip("=")
|
||||
raw=body+struct.pack(">I",crc)
|
||||
return LEGACY_PREFIX + base64.urlsafe_b64encode(raw).decode().rstrip('=')
|
||||
|
||||
|
||||
def dec(text):
|
||||
def dec_text(text):
|
||||
assert text.startswith(PREFIX)
|
||||
b64 = text[len(PREFIX):]
|
||||
raw = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
|
||||
raw=b45decode(text[len(PREFIX):])
|
||||
body, crc_raw = raw[:-4], raw[-4:]
|
||||
assert (binascii.crc32(body) & 0xFFFFFFFF) == struct.unpack(">I", crc_raw)[0]
|
||||
assert body[:4] == b"QFT1" and body[4] == 1
|
||||
kind = body[5]
|
||||
sid, seq, total, plen = struct.unpack(">QIIH", body[6:24])
|
||||
payload = body[24:]
|
||||
assert len(payload) == plen
|
||||
return kind, sid, seq, total, payload
|
||||
assert body[:4] == b"QFT2" and body[4] == 2
|
||||
kind=body[5]
|
||||
sid,seq,total,plen=struct.unpack(">QIIH", body[6:24])
|
||||
payload=body[24:]
|
||||
assert len(payload)==plen
|
||||
return kind,sid,seq,total,payload
|
||||
|
||||
|
||||
def test_qr_density(sample):
|
||||
qr = qrcode.QRCode(version=None, error_correction=ERROR_CORRECT_L, box_size=1, border=4)
|
||||
qr.add_data(sample)
|
||||
qr.make(fit=True)
|
||||
modules_with_quiet = qr.modules_count + 8
|
||||
canvas = 960
|
||||
gutter = max(12, min(24, canvas // 64))
|
||||
cell = (canvas - gutter * 3) // 2
|
||||
module_px = cell // modules_with_quiet
|
||||
assert module_px >= 3, (qr.version, qr.modules_count, cell, module_px)
|
||||
return qr.version, module_px, len(sample)
|
||||
def qr_info(sample: str):
|
||||
qr=qrcode.QRCode(version=None,error_correction=ERROR_CORRECT_L,box_size=1,border=4)
|
||||
qr.add_data(sample); qr.make(fit=True)
|
||||
modules_with_quiet=qr.modules_count+8
|
||||
return qr.version, 1024//modules_with_quiet, modules_with_quiet
|
||||
|
||||
|
||||
def main():
|
||||
assert b45encode(b"AB") == "BB8" and b45decode("BB8") == b"AB"
|
||||
assert b45encode(b"Hello!!") == "%69 VD92EX0" and b45decode("%69 VD92EX0") == b"Hello!!"
|
||||
assert b45encode(b"base-45") == "UJCLQE7W581" and b45decode("UJCLQE7W581") == b"base-45"
|
||||
|
||||
random.seed(20260810)
|
||||
data = os.urandom(2_500_123)
|
||||
digest = hashlib.sha256(data).digest()
|
||||
total = math.ceil(len(data) / CHUNK)
|
||||
sid = 0x1234567890ABCDEF
|
||||
name = b"sample.bin"
|
||||
device = b"DESKTOP-QFT"
|
||||
manifest = (
|
||||
struct.pack(">QH", len(data), CHUNK)
|
||||
+ digest
|
||||
+ struct.pack(">H", len(name)) + name
|
||||
+ struct.pack(">H", len(device)) + device
|
||||
)
|
||||
playlist = [enc(1, sid, 0, total, manifest)]
|
||||
playlist += [enc(2, sid, i, total, data[i*CHUNK:(i+1)*CHUNK]) for i in range(total)]
|
||||
playlist += [enc(3, sid, 0, total)]
|
||||
pages = [playlist[i:i+LANES] for i in range(0, len(playlist), LANES)]
|
||||
data=os.urandom(1_200_123); digest=hashlib.sha256(data).digest()
|
||||
total=math.ceil(len(data)/CHUNK); sid=0x1234567890ABCDEF
|
||||
name=b"sample.bin"; device=b"DESKTOP-QFT"
|
||||
manifest=struct.pack(">QH",len(data),CHUNK)+digest+struct.pack(">H",len(name))+name+struct.pack(">H",len(device))+device
|
||||
playlist=[enc_text(1,sid,0,total,manifest)]
|
||||
playlist += [enc_text(2,sid,i,total,data[i*CHUNK:(i+1)*CHUNK]) for i in range(total)]
|
||||
playlist += [enc_text(3,sid,0,total)]
|
||||
|
||||
version, module_px, chars = test_qr_density(playlist[min(2, len(playlist)-1)])
|
||||
sample=playlist[min(2,len(playlist)-1)]
|
||||
version,module_px,modules=qr_info(sample)
|
||||
legacy=legacy_text(2,sid,0,total,os.urandom(480))
|
||||
legacy_version,legacy_px,_=qr_info(legacy)
|
||||
assert version <= 15,(version,len(sample))
|
||||
assert module_px >= 10,(version,modules,module_px)
|
||||
assert version < legacy_version,(version,legacy_version)
|
||||
|
||||
got = [None] * total
|
||||
rounds = 0
|
||||
manifests = 0
|
||||
# Model both whole-camera-frame losses and per-lane decode failures.
|
||||
got=[None]*total; rounds=0
|
||||
while any(x is None for x in got):
|
||||
rounds += 1
|
||||
for page in pages:
|
||||
if random.random() < 0.24: # display page/camera frame missed
|
||||
continue
|
||||
for text in page:
|
||||
if random.random() < 0.14: # one quadrant not decoded
|
||||
continue
|
||||
kind, rsid, seq, rtotal, payload = dec(text)
|
||||
assert rsid == sid and rtotal == total
|
||||
if kind == 1:
|
||||
manifests += 1
|
||||
elif kind == 2 and got[seq] is None:
|
||||
got[seq] = payload
|
||||
for text in playlist:
|
||||
if random.random() < 0.22: continue
|
||||
kind,rsid,seq,rtotal,payload=dec_text(text)
|
||||
assert rsid==sid and rtotal==total
|
||||
if kind==2 and got[seq] is None: got[seq]=payload
|
||||
assert rounds < 60
|
||||
rebuilt=b''.join(got)[:len(data)]
|
||||
assert rebuilt==data and hashlib.sha256(rebuilt).digest()==digest
|
||||
rate=CHUNK*DISPLAY_FPS
|
||||
print(f"PASS QFT2/Base45 single-QR: {len(data)} bytes, {total} chunks, 22% frame loss, recovered in {rounds} rounds; QR-L v{version} vs legacy Base64 v{legacy_version}, {module_px}px/module@1024, text={len(sample)} chars, theoretical payload={rate/1024:.1f} KiB/s")
|
||||
|
||||
rebuilt = b"".join(got)[:len(data)]
|
||||
assert rebuilt == data
|
||||
assert hashlib.sha256(rebuilt).digest() == digest
|
||||
raw_rate = CHUNK * LANES * DISPLAY_FPS
|
||||
print(
|
||||
f"PASS optical: {len(data)} bytes, {total} chunks, {LANES} QR/page @ {DISPLAY_FPS} FPS, "
|
||||
f"24% page loss + 14% lane loss, recovered in {rounds} rounds; "
|
||||
f"QR v{version}, {module_px}px/module, frame chars={chars}, theoretical payload={raw_rate/1024:.1f} KiB/s"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
if __name__=='__main__': main()
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
qrcode>=7.4
|
||||
numpy>=1.24
|
||||
opencv-python>=4.8
|
||||
pyzbar>=0.1.9
|
||||
@@ -4,14 +4,17 @@ from pathlib import Path
|
||||
root = Path(__file__).resolve().parent
|
||||
scripts = [
|
||||
'protocol_selftest.py',
|
||||
'optical_image_decode_selftest.py',
|
||||
'pairing_selftest.py',
|
||||
'parallel_upload_selftest.py',
|
||||
'udp_discovery_selftest.py',
|
||||
'local_transfer_integration_selftest.py',
|
||||
'memory_budget_selftest.py',
|
||||
'android_compat_selftest.py',
|
||||
'single_channel_guard_selftest.py',
|
||||
'kotlin_host_smoke.py',
|
||||
]
|
||||
for name in scripts:
|
||||
print(f'== {name} ==', flush=True)
|
||||
subprocess.run([sys.executable, str(root/name)], check=True)
|
||||
print('ALL CORE PYTHON SELFTESTS PASSED')
|
||||
print('ALL HOST SELFTESTS PASSED')
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
main=(ROOT/'windows/src/main.rs').read_text()
|
||||
cache=(ROOT/'windows/src/optical_cache.rs').read_text()
|
||||
qr=(ROOT/'windows/src/qr.rs').read_text()
|
||||
protocol=(ROOT/'windows/src/protocol.rs').read_text()
|
||||
base45=(ROOT/'windows/src/base45.rs').read_text()
|
||||
analyzer=(ROOT/'android/app/src/main/java/com/qft/optical/QrAnalyzer.kt').read_text()
|
||||
android_protocol=(ROOT/'android/app/src/main/java/com/qft/optical/Protocol.kt').read_text()
|
||||
activity=(ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text()
|
||||
assert 'render_qr_grid' not in qr+cache+main
|
||||
assert 'self.optical.lanes' not in main
|
||||
assert 'OPTICAL_MULTI' not in analyzer
|
||||
assert 'newFixedThreadPool' not in analyzer
|
||||
assert 'DEFAULT_CHUNK_SIZE: u16 = 450' in main
|
||||
assert 'source.text_frame(page_index)' in cache and 'render_qr_fitted' in cache
|
||||
assert 'QFT2:' in protocol and 'base45::encode' in protocol and 'EcLevel::L' in qr
|
||||
assert 'Base45.decode' in android_protocol and 'QFT2' in android_protocol
|
||||
assert 'assembler.acceptText(code.text)' in activity and 'acceptBinary' not in activity
|
||||
assert 'grayBuffer.capture(image, current)' in analyzer and 'fingerprint = text.hashCode()' in analyzer
|
||||
assert 'BB8' in base45 and 'UJCLQE7W581' in base45
|
||||
print('PASS single-channel guard: one large QFT2/Base45 QR, 450B chunks, no 2x2/4-lane path, Android locked-ROI text decode only')
|
||||
Reference in New Issue
Block a user