新增原生 gRPC 画面与数据接收器

This commit is contained in:
2026-11-09 16:34:22 +08:00
parent be3239026a
commit bf84214534
17 changed files with 1672 additions and 0 deletions
@@ -0,0 +1,30 @@
"""Read the deployed coordinator status using its existing service signature."""
from pathlib import Path
import hashlib
import hmac
import json
import time
import urllib.request
import uuid
def status():
config = Path('E:/Codex/xtrh/runtime/coordinator/config/cluster.local.properties')
key = next(line.split('=',1)[1].strip() for line in config.read_text(encoding='utf-8-sig').splitlines()
if line.startswith('fusion.token=')).encode()
path = '/node/input/status'
nonce, stamp = str(uuid.uuid4()), str(time.time_ns()//1000000)
sign = lambda value: hmac.new(key, value.encode(), 'sha256').hexdigest()
signature = sign('\n'.join(['request','GET',path,stamp,nonce,hashlib.sha256(b'').hexdigest()]))
request = urllib.request.Request('http://127.0.0.1:18100'+path,
headers={'X-Xtrh-Time':stamp,'X-Xtrh-Nonce':nonce,'X-Xtrh-Signature':signature})
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(request,timeout=5) as response:
raw = response.read()
expected = sign('\n'.join(['response',nonce,str(response.status),hashlib.sha256(raw).hexdigest()]))
assert hmac.compare_digest(expected,response.headers.get('X-Xtrh-Response-Signature',''))
return json.loads(raw)
if __name__ == '__main__':
print(json.dumps(status(),ensure_ascii=True,indent=2))
@@ -0,0 +1,78 @@
"""Smoke check the distributed EXE using the native Windows Qt platform."""
import os
os.environ['QT_QPA_PLATFORM'] = 'offscreen'
import json
from pathlib import Path
import socket
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import grpc
from PySide6.QtGui import QFontDatabase
from PySide6.QtWidgets import QApplication
from check_window import make_jpeg
import fusion_input_pb2 as pb
import fusion_input_pb2_grpc as rpc
def main():
app = QApplication([])
for font in ['msyh.ttc', 'consola.ttf']:
QFontDatabase.addApplicationFont('C:/Windows/Fonts/'+font)
image = make_jpeg()
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
folder = ROOT/'artifacts'
status_path = folder/'packaged-status.json'
shot_path = folder/'packaged-native-window.png'
child_env = os.environ.copy()
child_env.pop('QT_QPA_PLATFORM', None)
child_env.pop('QT_PLUGIN_PATH', None)
child_env.pop('QT_QPA_PLATFORM_PLUGIN_PATH', None)
command = [str(ROOT/'dist/FusionInputReceiver/FusionInputReceiver.exe'), '--port', str(port),
'--status-file', str(status_path), '--screenshot-after', '6.5',
'--screenshot-path', str(shot_path), '--quit-after', '8']
process = subprocess.Popen(command, env=child_env)
try:
with grpc.insecure_channel(f'127.0.0.1:{port}') as channel:
grpc.channel_ready_future(channel).result(timeout=12)
stub = rpc.FusionInputServiceStub(channel)
start = time.perf_counter()
for i in range(300):
time.sleep(max(0, start+i/60-time.perf_counter()))
now = time.time_ns()//1000000
meta = dict(schemaVersion=1, equipmentId='package-check', equipmentCode='独立软件验证',
sourceEndpointId='isolated-test-source', frameId=f'{i:016x}',
trialId='package-test', trialIds=['package-test'], sourceTime=now,
receivedTime=now, upload=dict(frameId=f'{i:016x}', time=now, reused=False))
data = dict(meta, kind='DATA', messageId=f'data/{i}', data={'values':{
'sampleIndex':i, 'temperature':23.5, 'status':'模拟测试 / 非现场数据'}})
picture = dict(meta, kind='IMAGE', messageId=f'image/{i}', imageBytes=len(image), imageContentType='image/jpeg')
stub.Push(iter([pb.FusionInput(json=json.dumps(data,ensure_ascii=False)),
pb.FusionInput(json=json.dumps(picture,ensure_ascii=False), image=image)]), timeout=3)
assert process.wait(timeout=15) == 0, 'Executable exited abnormally'
status = json.loads(status_path.read_text(encoding='utf-8'))
assert status['data'] == status['images'] == 300, status
assert status['displayed'] >= 200, status
assert status['decode_errors'] == status['invalid'] == 0, status
assert status['displayed_frame_id'] == f'{299:016x}', status
assert status['decoded_size'][0] <= 960 and status['decoded_size'][1] <= 540, status
assert status['display_quality'] == 'low_latency', status
assert shot_path.is_file()
result = dict(passed=True, executable=str(command[0]), synthetic=True,
native_windows_platform=True, test_fps=60, test_resolution=[1920,1080], **status)
(folder/'packaged-check-result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(result,ensure_ascii=True,indent=2))
finally:
if process.poll() is None:
process.terminate()
process.wait(timeout=5)
return 0
if __name__ == '__main__':
sys.exit(main())
@@ -0,0 +1,124 @@
"""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())
@@ -0,0 +1,206 @@
import os
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
import json
from pathlib import Path
import sys
import socket
import time
import unittest
from concurrent.futures import ThreadPoolExecutor
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import grpc
from PySide6.QtCore import QBuffer, QIODevice, Qt
from PySide6.QtGui import QImage, QColor
from PySide6.QtWidgets import QApplication
import fusion_input_pb2 as pb
import fusion_input_pb2_grpc as rpc
from receiver import Store, Receiver, Decoder
from window import MainWindow
APP = QApplication.instance() or QApplication([])
def jpeg(width=320, height=180):
image = QImage(width, height, QImage.Format.Format_RGB32)
image.fill(QColor('#218c79'))
buf = QBuffer()
buf.open(QIODevice.OpenModeFlag.WriteOnly)
assert image.save(buf, 'JPEG', 85)
return bytes(buf.data())
def message(number=1, kind='DATA', equipment='EQ-01', source='source-01', frame=True, image=None):
frame_id = f'{number:016x}' if frame else None
meta = dict(schemaVersion=1, kind=kind, messageId=f'{kind}/{equipment}/{source}/{number}',
equipmentId=equipment, equipmentCode=equipment, sourceEndpointId=source,
trialId=None, trialIds=['试验甲', '试验乙'], frameId=frame_id,
pairingAvailable=frame, sourceTime=1794190000000,
receivedTime=1794190000010,
upload=dict(frameId=frame_id, reused=True, time=1794190000020))
if kind == 'DATA':
meta['data'] = {'values': {'经度': 116.3, '状态': '运行', 'zero': 0, 'false': False},
'raw': {'原始': '保持原样'}}
else:
image = image if image is not None else jpeg()
meta.update(imageContentType='image/jpeg', imageBytes=len(image))
return pb.FusionInput(json=json.dumps(meta, ensure_ascii=False), image=image or b'')
class ReceiverTests(unittest.TestCase):
def setUp(self):
self.store = Store()
self.receiver = Receiver(self.store)
self.port = self.receiver.start(0)
self.channel = grpc.insecure_channel(f'127.0.0.1:{self.port}')
grpc.channel_ready_future(self.channel).result(timeout=5)
self.stub = rpc.FusionInputServiceStub(self.channel)
def tearDown(self):
self.channel.close()
self.receiver.stop()
def test_real_grpc_contract_and_binary(self):
data, image = message(), message(kind='IMAGE')
response = self.stub.Push(iter([data, image]), timeout=3)
self.assertEqual(response.SerializeToString(), b'')
source = self.store.sources[('EQ-01', 'source-01')]
self.assertEqual(source.latest_image.jpeg, image.image)
self.assertEqual(source.latest_data.meta, json.loads(data.json))
latest, paired = self.store.data_for(source.latest_image)
self.assertIs(latest, paired)
self.assertEqual(self.store.snapshot()['batches'], 1)
def test_retry_deduplicates_partial_stream(self):
good = message()
with self.assertRaises(grpc.RpcError) as err:
self.stub.Push(iter([good, pb.FusionInput(json='{bad')]), timeout=3)
self.assertEqual(err.exception.code(), grpc.StatusCode.INVALID_ARGUMENT)
self.stub.Push(iter([good, message(2)]), timeout=3)
self.assertEqual(self.store.snapshot()['data'], 2)
self.assertEqual(self.store.snapshot()['duplicates'], 1)
def test_legacy_data_without_frame(self):
self.stub.Push(iter([message(frame=False)]), timeout=3)
self.assertEqual(self.store.snapshot()['data'], 1)
self.assertEqual(len(self.store.pairs), 0)
def test_pair_does_not_cross_equipment_or_source(self):
self.stub.Push(iter([message(), message(kind='IMAGE', source='another'),
message(kind='IMAGE', equipment='another')]), timeout=3)
self.store.select(('EQ-01', 'another'))
image = self.store.sources[self.store.selected].latest_image
self.assertEqual(self.store.data_for(image), (None, None))
self.stub.Push(iter([message(source='another')]), timeout=3)
self.assertIsNotNone(self.store.data_for(image)[1])
def test_concurrent_duplicates(self):
with ThreadPoolExecutor(max_workers=8) as pool:
list(pool.map(lambda _: self.stub.Push(iter([message()]), timeout=4), range(20)))
stats = self.store.snapshot()
self.assertEqual(stats['data'], 1)
self.assertEqual(stats['duplicates'], 19)
def test_latest_frame_and_bounded_storage(self):
image = jpeg()
self.stub.Push((message(i, 'IMAGE', image=image) for i in range(150)), timeout=5)
source = self.store.sources[('EQ-01', 'source-01')]
self.assertEqual(source.latest_image.meta['frameId'], f'{149:016x}')
self.assertEqual(self.store.snapshot()['cached_jpeg_bytes'], len(image))
self.assertEqual(self.store.snapshot()['superseded'], 149)
self.store.MAX_PAIRS = 5
self.store.MAX_IDS = 10
self.stub.Push((message(i) for i in range(1000, 1020)), timeout=4)
self.assertLessEqual(len(self.store.pairs), 5)
self.assertLessEqual(len(self.store.ids), 10)
def test_pair_memory_budget_and_source_limit(self):
self.store.MAX_PAIR_BYTES = 600
self.store.MAX_SOURCES = 3
self.stub.Push((message(i, equipment=f'EQ-{i}') for i in range(8)), timeout=3)
self.assertEqual(len(self.store.sources), 3)
self.assertLessEqual(self.store.pair_bytes, 600)
self.assertIn(('EQ-0', 'source-01'), self.store.sources)
def test_decoder_produces_native_image(self):
decoder = Decoder(self.store)
decoder.start()
try:
self.stub.Push(iter([message(kind='IMAGE', image=jpeg(1920, 1080))]), timeout=3)
ready = None
end = time.monotonic()+3
while time.monotonic()<end and ready is None:
ready = decoder.take()
time.sleep(.005)
self.assertIsNotNone(ready)
self.assertEqual((ready[2].width(), ready[2].height()), (1920, 1080))
self.assertGreater(ready[3], 0)
finally:
decoder.close()
def test_corrupt_jpeg_reports_decode_failure(self):
decoder = Decoder(self.store)
decoder.start()
try:
self.stub.Push(iter([message(kind='IMAGE', image=b'\xff\xd8broken\xff\xd9')]), timeout=3)
end = time.monotonic()+2
while time.monotonic()<end and not self.store.snapshot()['decode_errors']:
time.sleep(.01)
self.assertEqual(self.store.snapshot()['decode_errors'], 1)
self.assertIsNone(decoder.take())
finally:
decoder.close()
def test_listener_restart_recovers(self):
self.stub.Push(iter([message()]), timeout=3)
self.receiver.stop()
self.receiver.start(self.port)
self.stub.Push(iter([message(), message(2)]), timeout=5, wait_for_ready=True)
self.assertEqual(self.store.snapshot()['data'], 2)
self.assertEqual(self.store.snapshot()['duplicates'], 1)
def test_invalid_input_status(self):
for raw in ['[]', '{"schemaVersion":2}', '{"schemaVersion":1,"kind":"DATA"}']:
with self.assertRaises(grpc.RpcError) as err:
self.stub.Push(iter([pb.FusionInput(json=raw)]), timeout=2)
self.assertEqual(err.exception.code(), grpc.StatusCode.INVALID_ARGUMENT)
def test_native_pause_resume_and_source_switch(self):
with socket.socket() as reserve:
reserve.bind(('127.0.0.1', 0))
port = reserve.getsockname()[1]
window = MainWindow(port)
window.show()
def until(predicate):
end = time.monotonic()+3
while time.monotonic()<end:
APP.processEvents()
if predicate(): return
time.sleep(.005)
self.fail('Native UI condition timed out')
try:
with grpc.insecure_channel(f'127.0.0.1:{port}') as channel:
stub = rpc.FusionInputServiceStub(channel)
stub.Push(iter([message(1, 'IMAGE'), message(1)]), timeout=3)
until(lambda: window.canvas.message is not None)
original = window.canvas.message
window.pause_button.setChecked(True)
stub.Push(iter([message(2, 'IMAGE'), message(3, 'IMAGE')]), timeout=3)
until(lambda: window.store.snapshot()['decoded'] >= 2)
self.assertIs(window.canvas.message, original)
window.pause_button.setChecked(False)
until(lambda: window.canvas.message.meta['frameId'] == f'{3:016x}')
stub.Push(iter([message(4, 'IMAGE', source='other')]), timeout=3)
window.refresh_info()
item = next(window.sources.item(i) for i in range(window.sources.count())
if window.sources.item(i).data(Qt.ItemDataRole.UserRole)[1] == 'other')
window.sources.setCurrentItem(item)
until(lambda: window.canvas.message and window.canvas.message.key == ('EQ-01','other'))
self.assertEqual(window.store.selected, ('EQ-01','other'))
finally:
window.close()
if __name__ == '__main__':
unittest.main(verbosity=2)