Files

125 lines
5.5 KiB
Python
Raw Permalink Normal View History

2026-11-09 16:34:22 +08:00
"""Isolated native UI / real gRPC check; never sends into the deployed coordinator."""
import os
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
import json
import math
from pathlib import Path
import socket
import sys
import threading
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import grpc
from PySide6.QtCore import QTimer, QBuffer, QIODevice, Qt
from PySide6.QtGui import QImage, QPainter, QColor, QFont, QPen, QFontDatabase
from PySide6.QtWidgets import QApplication
import fusion_input_pb2 as pb
import fusion_input_pb2_grpc as rpc
from window import MainWindow
def make_jpeg():
image = QImage(1920, 1080, QImage.Format.Format_RGB32)
image.fill(QColor('#102b43'))
p = QPainter(image)
p.setPen(QPen(QColor('#22455c'), 2))
for x in range(0, 1920, 80): p.drawLine(x, 0, x, 1080)
for y in range(0, 1080, 80): p.drawLine(0, y, 1920, y)
p.setPen(QPen(QColor('#70e2ca'), 5))
p.drawEllipse(650, 230, 620, 620)
p.drawLine(960, 170, 960, 910)
p.drawLine(590, 540, 1330, 540)
p.setPen(QColor('#def7f1'))
p.setFont(QFont('Microsoft YaHei UI', 34))
p.drawText(85, 125, 'gRPC 原生接收验证 · 模拟画面')
p.setFont(QFont('Consolas', 24))
p.drawText(85, 1000, '1920 x 1080 / JPEG bytes / 60 FPS test source')
p.end()
buf = QBuffer()
buf.open(QIODevice.OpenModeFlag.WriteOnly)
image.save(buf, 'JPEG', 88)
return bytes(buf.data())
def run():
app = QApplication([])
# Qt's Windows offscreen plugin does not automatically enumerate system fonts.
for name in ['msyh.ttc', 'msyhbd.ttc', 'consola.ttf']:
font_path = Path('C:/Windows/Fonts')/name
if font_path.exists():
QFontDatabase.addApplicationFont(str(font_path))
with socket.socket() as s:
s.bind(('127.0.0.1', 0))
port = s.getsockname()[1]
output = ROOT/'artifacts'
output.mkdir(exist_ok=True)
window = MainWindow(port, output/'ui-check-status.json')
window.show()
jpeg = make_jpeg()
failures = []
sent = []
def send():
try:
with grpc.insecure_channel(f'127.0.0.1:{port}') as channel:
grpc.channel_ready_future(channel).result(5)
stub = rpc.FusionInputServiceStub(channel)
start = time.perf_counter()
for i in range(360):
target = start+i/60
time.sleep(max(0, target-time.perf_counter()))
now = time.time_ns()//1000000
common = dict(schemaVersion=1, equipmentId='test-equipment', equipmentCode='联调装备 01',
sourceEndpointId='test-collector-04', moduleNo='04', moduleType='04',
frameId=f'{i:016x}', trialId='native-ui-test', trialIds=['native-ui-test'],
sourceTime=now, receivedTime=now, pairingAvailable=True,
upload=dict(frameId=f'{i:016x}', time=now, reused=False))
data = dict(common, kind='DATA', messageId=f'data/{i}', data=dict(values={
'longitude':116.3913, 'latitude':39.9075, 'altitude':180+round(math.sin(i/30)*2, 3),
'heading':round(i*.5, 2), 'pitch':round(math.sin(i/40),3), 'roll':.12,
'sampleIndex':i, 'status':'模拟输入 · 仅用于接收显示验证'},
raw={'moduleNo':'04','event':'无事件'}))
image = dict(common, kind='IMAGE', messageId=f'image/{i}', imageBytes=len(jpeg), imageContentType='image/jpeg')
stub.Push(iter([pb.FusionInput(json=json.dumps(data, ensure_ascii=False)),
pb.FusionInput(json=json.dumps(image, ensure_ascii=False), image=jpeg)]), timeout=3)
sent.append(i)
except Exception as exc:
failures.append(repr(exc))
worker = threading.Thread(target=send, daemon=True)
worker.start()
QTimer.singleShot(4800, lambda: window.grab().save(str(output/'native-ui-check.png')))
def finish():
try:
stats = window.store.snapshot()
assert not failures, failures
assert len(sent) == 360, len(sent)
assert stats['images'] == stats['data'] == 360, stats
assert stats['decode_errors'] == 0, stats
assert stats['displayed'] > 100, stats
assert window.canvas.source_size == (1920, 1080)
assert window.canvas.frame.width() <= 1920
assert window.canvas.message.meta['frameId'] == f'{359:016x}'
assert window.store.data_for(window.canvas.message)[1] is not None
assert stats['cached_jpeg_bytes'] == len(jpeg)
# Switching away must clear stale imagery; restoring must decode the retained latest frame.
window.data_mode.setCurrentIndex(1)
window.tabs.setCurrentIndex(1)
assert 'sampleIndex' in window.raw.toPlainText()
result = dict(passed=True, synthetic=True, native_qt=True, jpeg_size=len(jpeg),
source_resolution=[1920,1080], source_fps=60, sent_frames=len(sent), **stats)
(output/'ui-check-result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(result,ensure_ascii=True))
except Exception as exc:
failures.append(repr(exc))
print('FAILED', failures)
finally:
window.close()
QTimer.singleShot(7000, finish)
app.exec()
return 1 if failures else 0
if __name__ == '__main__':
sys.exit(run())