diff --git a/tools/fusion-input-receiver/.gitignore b/tools/fusion-input-receiver/.gitignore new file mode 100644 index 0000000..ba68527 --- /dev/null +++ b/tools/fusion-input-receiver/.gitignore @@ -0,0 +1,7 @@ +.venv/ +.build-cache/ +build/ +dist/ +__pycache__/ +artifacts/ +*.spec diff --git a/tools/fusion-input-receiver/build.ps1 b/tools/fusion-input-receiver/build.ps1 new file mode 100644 index 0000000..3442dad --- /dev/null +++ b/tools/fusion-input-receiver/build.ps1 @@ -0,0 +1,24 @@ +$ErrorActionPreference = 'Stop' +$taskRoot = $PSScriptRoot +$python = Join-Path $taskRoot '.venv\Scripts\python.exe' +if (!(Test-Path -LiteralPath $python)) { throw 'Create .venv and install requirements-dev.txt first.' } +$buildOriginalPath = $env:PATH +$buildOriginalCache = $env:PYINSTALLER_CONFIG_DIR +$basePython = & $python -c 'import sys; print(sys.base_prefix)' +# Do not accidentally bundle unrelated DLLs from other developer tools on PATH. +$env:PATH = @((Split-Path -Parent $python), $basePython, (Join-Path $basePython 'DLLs'), (Join-Path $env:SystemRoot 'System32'), $env:SystemRoot) -join ';' +$env:PYINSTALLER_CONFIG_DIR = Join-Path $taskRoot '.build-cache' +Push-Location $taskRoot +try { + & $python -m PyInstaller --noconfirm --clean --windowed --onedir --name FusionInputReceiver --exclude-module PySide6.QtWebEngineCore --exclude-module PySide6.QtWebEngineWidgets --exclude-module PySide6.QtQml --exclude-module PySide6.QtQuick --exclude-module tkinter --exclude-module matplotlib --exclude-module numpy --collect-submodules grpc --add-data 'protocol;protocol' main.py + if ($LASTEXITCODE -ne 0) { throw 'PyInstaller failed.' } + Copy-Item -LiteralPath (Join-Path $taskRoot '使用说明.txt') -Destination (Join-Path $taskRoot 'dist\FusionInputReceiver\使用说明.txt') -Force + Copy-Item -LiteralPath (Join-Path $taskRoot 'protocol') -Destination (Join-Path $taskRoot 'dist\FusionInputReceiver\protocol') -Recurse -Force + $archive = Join-Path $taskRoot 'dist\融合输入接收器_Windows_x64.zip' + Compress-Archive -LiteralPath (Join-Path $taskRoot 'dist\FusionInputReceiver') -DestinationPath $archive -Force + Get-Item -LiteralPath $archive | Select-Object FullName, Length +} finally { + Pop-Location + $env:PATH = $buildOriginalPath + $env:PYINSTALLER_CONFIG_DIR = $buildOriginalCache +} diff --git a/tools/fusion-input-receiver/fusion_input_pb2.py b/tools/fusion-input-receiver/fusion_input_pb2.py new file mode 100644 index 0000000..fc94ee9 --- /dev/null +++ b/tools/fusion-input-receiver/fusion_input_pb2.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: fusion_input.proto +# Protobuf Python Version: 7.35.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 7, + 35, + 1, + '', + 'fusion_input.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12\x66usion_input.proto\x12\x0extrh.fusion.v1\x1a\x1bgoogle/protobuf/empty.proto\"*\n\x0b\x46usionInput\x12\x0c\n\x04json\x18\x01 \x01(\t\x12\r\n\x05image\x18\x02 \x01(\x0c\x32S\n\x12\x46usionInputService\x12=\n\x04Push\x12\x1b.xtrh.fusion.v1.FusionInput\x1a\x16.google.protobuf.Empty(\x01\x62\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'fusion_input_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + DESCRIPTOR._loaded_options = None + _globals['_FUSIONINPUT']._serialized_start=67 + _globals['_FUSIONINPUT']._serialized_end=109 + _globals['_FUSIONINPUTSERVICE']._serialized_start=111 + _globals['_FUSIONINPUTSERVICE']._serialized_end=194 +# @@protoc_insertion_point(module_scope) diff --git a/tools/fusion-input-receiver/fusion_input_pb2_grpc.py b/tools/fusion-input-receiver/fusion_input_pb2_grpc.py new file mode 100644 index 0000000..92f1e5c --- /dev/null +++ b/tools/fusion-input-receiver/fusion_input_pb2_grpc.py @@ -0,0 +1,100 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc +import warnings + +import fusion_input_pb2 as fusion__input__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 + +GRPC_GENERATED_VERSION = '1.85.1' +GRPC_VERSION = grpc.__version__ +_version_not_supported = False + +try: + from grpc._utilities import first_version_is_lower + _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION) +except ImportError: + _version_not_supported = True + +if _version_not_supported: + raise RuntimeError( + f'The grpc package installed is at version {GRPC_VERSION},' + + ' but the generated code in fusion_input_pb2_grpc.py depends on' + + f' grpcio>={GRPC_GENERATED_VERSION}.' + + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}' + + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.' + ) + + +class FusionInputServiceStub: + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Push = channel.stream_unary( + '/xtrh.fusion.v1.FusionInputService/Push', + request_serializer=fusion__input__pb2.FusionInput.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + _registered_method=True) + + +class FusionInputServiceServicer: + """Missing associated documentation comment in .proto file.""" + + def Push(self, request_iterator, context): + """Each short stream contains one or more inputs. Empty is a transport receipt, + not a calibration/fusion result. Retries may repeat messageId values. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_FusionInputServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Push': grpc.stream_unary_rpc_method_handler( + servicer.Push, + request_deserializer=fusion__input__pb2.FusionInput.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'xtrh.fusion.v1.FusionInputService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + server.add_registered_method_handlers('xtrh.fusion.v1.FusionInputService', rpc_method_handlers) + + + # This class is part of an EXPERIMENTAL API. +class FusionInputService: + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def Push(request_iterator, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.stream_unary( + request_iterator, + target, + '/xtrh.fusion.v1.FusionInputService/Push', + fusion__input__pb2.FusionInput.SerializeToString, + google_dot_protobuf_dot_empty__pb2.Empty.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + _registered_method=True) diff --git a/tools/fusion-input-receiver/main.py b/tools/fusion-input-receiver/main.py new file mode 100644 index 0000000..f7cd2ef --- /dev/null +++ b/tools/fusion-input-receiver/main.py @@ -0,0 +1,46 @@ +"""Launch the native Qt desktop application.""" +import argparse +import logging +from logging.handlers import RotatingFileHandler +from pathlib import Path +import os +import sys + +from PySide6.QtCore import QTimer +from PySide6.QtWidgets import QApplication + +from window import MainWindow + + +def main(): + parser = argparse.ArgumentParser(description='Native gRPC image/data receiver') + parser.add_argument('--port', type=int, default=50051) + parser.add_argument('--status-file', help='Optional JSON diagnostics file (no business payload)') + parser.add_argument('--screenshot-after', type=float, help=argparse.SUPPRESS) + parser.add_argument('--screenshot-path', help=argparse.SUPPRESS) + parser.add_argument('--quit-after', type=float, help=argparse.SUPPRESS) + args = parser.parse_args() + if not 1024 <= args.port <= 65535: + parser.error('port must be between 1024 and 65535') + log_dir = Path(os.getenv('LOCALAPPDATA', Path.home()))/'FusionInputReceiver' + log_dir.mkdir(parents=True, exist_ok=True) + handler = RotatingFileHandler(log_dir/'receiver.log', maxBytes=1_000_000, backupCount=2, encoding='utf-8') + logging.basicConfig(level=logging.INFO, handlers=[handler], format='%(asctime)s %(levelname)s %(message)s') + def exception_hook(kind, value, traceback): + logging.error('Unhandled error', exc_info=(kind, value, traceback)) + sys.excepthook = exception_hook + app = QApplication(sys.argv[:1]) + app.setApplicationName('FusionInputReceiver') + app.setOrganizationName('LocalTools') + app.setStyle('Fusion') + window = MainWindow(args.port, args.status_file) + window.show() + if args.screenshot_after and args.screenshot_path: + QTimer.singleShot(int(args.screenshot_after*1000), lambda: window.grab().save(args.screenshot_path)) + if args.quit_after: + QTimer.singleShot(int(args.quit_after*1000), window.close) + return app.exec() + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/fusion-input-receiver/protocol/fusion_input.proto b/tools/fusion-input-receiver/protocol/fusion_input.proto new file mode 100644 index 0000000..a1796cb --- /dev/null +++ b/tools/fusion-input-receiver/protocol/fusion_input.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; +package xtrh.fusion.v1; +import "google/protobuf/empty.proto"; + +// json contains equipment/source/frame identities and the original measured values. +// image contains the original JPEG bytes for IMAGE messages; it is empty for DATA. +message FusionInput { + string json = 1; + bytes image = 2; +} + +service FusionInputService { + // Each short stream contains one or more inputs. Empty is a transport receipt, + // not a calibration/fusion result. Retries may repeat messageId values. + rpc Push(stream FusionInput) returns (google.protobuf.Empty); +} diff --git a/tools/fusion-input-receiver/protocol/本机融合输入接口.md b/tools/fusion-input-receiver/protocol/本机融合输入接口.md new file mode 100644 index 0000000..dc7c4ba --- /dev/null +++ b/tools/fusion-input-receiver/protocol/本机融合输入接口.md @@ -0,0 +1,102 @@ +# 本机融合输入接口 + +本接口用于试验记录、仿真和展示的数据交接。系统融合软件负责装备归属、分发和输入交付;外部进程负责自身处理。本次不接收融合结果,不实现图片删除回调。 + +## 接口约定 + +协议文件:`src/main/proto/fusion_input.proto`。 + +- 服务:`xtrh.fusion.v1.FusionInputService` +- 方法:`Push(stream FusionInput) returns (google.protobuf.Empty)` +- 每台执行节点只连接 `127.0.0.1:`,默认端口 `50051`。 +- `FusionInput.json` 为 UTF-8 JSON 文本;`FusionInput.image` 为原始 JPEG 二进制。DATA 消息的 image 为空。 +- 为兼顾实时发送、流量上限和失败重试,客户端复用 Channel,发送一个或多个消息后结束当前短流,不等待凑满批次。最多每批 32 条,总大小约 4 MiB;单张图片上限 2 MiB。 +- 服务端在读完本批后返回一个 Empty 和 OK 状态。它只表示本批 RPC 接收成功,不表示融合已经完成。客户端不读取算法输出。 +- 失败会重试当前批次,接收方须按 `messageId` 去重;不承诺跨进程重启、跨节点迁移的“恰好一次”。 + +数据 JSON 示例: + +```json +{ + "schemaVersion": 1, + "kind": "DATA", + "messageId": "data/packet-001/trial-001", + "trialId": "trial-001", + "equipmentId": "equipment-001", + "equipmentCode": "EQ-001", + "sourceEndpointId": "collector-connection-001", + "collectionWay": "CONTROL_TERMINAL", + "moduleNo": "04", + "moduleType": "04", + "packetId": "packet-001", + "frameId": "fedcba9876543210", + "sourceTime": 1793934000000, + "receivedTime": 1793934000050, + "upload": { + "mode": "FIXED_30", + "time": 1793934000033, + "reused": false, + "frameId": "fedcba9876543210" + }, + "data": { "values": { "example_position": 0, "example_attitude": 0 } } +} +``` + +IMAGE 消息携带相同的装备与来源标识、`frameId`、采样/上传时间,另有 `imageContentType=image/jpeg` 和 `imageBytes`;图片正文在 protobuf 的 image 字段中,不是 JSON Base64,也不传文件地址。示例中的参数名仅用于展示,实际参数沿用采集协议,包括位置、姿态、不同类别的试验事件及其类型和发生时间,不固定某一装备或某一种事件类型。 + +固定外加模块保留完整的已解码 sample,其中 `values` 是现有解析结果、`raw` 是原始模块字段;不在这层改坐标系、单位、姿态约定或补造事件。 + +## 关联与时间 + +沿用 2026-11-06 采集改动:`upload.frameId` 是 16 位小写十六进制字符串,和 JPG1 分片头、JPEG 的 `HD-UPLOAD: ` 注释保持一致。转发 JSON 同时提供顶层 frameId,保留 upload 原对象中的模式、时间和 reused 标记,不重新生成帧号,也不转成十进制。 + +同一个 `(equipmentId, sourceEndpointId, frameId)` 可关联图片和同一上传周期的数据。`sourceTime`、`receivedTime` 和 `upload.time` 分别保留原协议语义,不用时间接近程度猜测配对。重复使用旧采样值时保留 `upload.reused=true`;图片原始采样时间如已提供,保留在 `upload.sourceTime`。 + +归属以装备唯一为准,优先使用正在运行的试验绑定。同一模块被多个有效试验引用、且都指向同一装备时只转发一份,并在 `trialIds` 中保留全部关联试验;只有一个时同时提供 `trialId`,多个时 `trialId` 为 null,不臆造当前试验。多个候选装备仍视为歧义,不转发。执行节点的输入路由按装备保持一致。 + +原有 SOURCE 模式或旧设备没有 upload.frameId 时,DATA 的 frameId 为 null、pairingAvailable 为 false,仍发送真实数据。pairingAvailable 只表示存在关联标识,不表示另一条消息已经到达。没有装备绑定或存在歧义时不转发,状态计数会记录 unbound。 + +## 分发与内存 + +高清视频平台从已认证、已保存的数据接收入口发布逐条事件;事务回滚的数据不发布,不使用页面每两秒刷新的最新值代替事件流。 + +平台沿用签名 HTTP 通道把事件交给系统融合总控。总控按试验/装备选择有效执行节点,优先沿用该装备的活动任务;没有视频任务的数据装备也可分配给启用输入能力的节点。同一装备的数据和图像走同一节点,该节点最后调用自己的本机 gRPC。跨节点的内部 HTTP 图片正文采用有界 Base64;最终 gRPC 使用独立 bytes 字段。 + +图片直接到系统融合节点时,节点在完成认证、组装和 JPEG 校验后发布,使用平台同步的唯一装备绑定;绑定过期、撤销或图片早于新绑定时不猜归属。准备阶段可以接收图片,但未绑定到装备的图片仅供原有预览。 + +接收队列和预览缓存分别管理。gRPC 的发送队列在收到本批 RPC 成功状态后释放引用,外部进程管理自己的图片内存;算法释放内存不会删除页面预览。平台启用输入转发时,实时图片预览默认使用有界内存缓存,既有 HTTP 图片接口保持不变。系统融合节点继续保留现有近期帧缓存。 + +每个队列有 64 MiB 总预算和条数限制,满时报告拒绝/丢弃计数,原采集流程继续运行。重试期间数据保留在内存;本次没有持久化发件箱,进程退出或长时间拥塞可能造成未交付输入丢失。不能将 sent/rpcCompleted 解释为“算法已用完图片”。 + +## 启用配置 + +外部融合进程应先按 proto 实现接收端并在每台机器本机监听。以下开关默认关闭,修改源代码不会自动启用或部署。 + +每台系统融合主/从执行节点: + +```properties +fusion.input-grpc.enabled=true +fusion.input-grpc.port=50051 +fusion.input-grpc.timeout-ms=3000 +fusion.input-grpc.queue-capacity=2048 +fusion.input-grpc.max-buffer-bytes=67108864 +``` + +高清视频平台: + +```properties +app.fusion.input-enabled=true +app.image-udp.memory-only=true +``` + +沿用已有 `app.fusion.enabled`、总控地址及服务签名配置,不在本文件填写凭证。平台的 `memory-only` 缺省值随 input-enabled 开关;如需继续使用原本地预览文件,可明确配置 false,gRPC 仍直接传二进制。缓存不保证重启后还能查看旧帧,本次不清理以前留在磁盘上的文件。 + +主/从进程在不同物理机器时均用各自 50051;同机多进程联调须配置不同端口,避免实际指向同一个接收进程。 + +## 状态与验证 + +- 平台:`GET /api/field/fusion/input-status`,沿用登录与采集读取权限,只允许全量数据范围账号查看全局计数。 +- 执行节点:`GET /node/input/status`,沿用服务签名认证,包含排队、缓冲字节、RPC 完成、重试、拒绝及直传图片计数。 +- 这些状态不返回图像、业务数据、凭证或算法结果。 + +自动化测试包括实际 gRPC 二进制接收、固定帧号和 upload 元数据保持、错误后重试、队列满拒绝、两个执行节点各自调用本机接收端、装备分发、服务签名保护,以及平台逐条发布、事务回滚、装备绑定歧义、内存预览独立生命周期。隔离测试接收器不代表已与实际算法进程联调,也不代表真实多机或持续 30 fps 容量验收。 diff --git a/tools/fusion-input-receiver/receiver.py b/tools/fusion-input-receiver/receiver.py new file mode 100644 index 0000000..7eda483 --- /dev/null +++ b/tools/fusion-input-receiver/receiver.py @@ -0,0 +1,352 @@ +"""Bounded native gRPC receiver. No HTTP server, disk image queue or UI callbacks.""" +from __future__ import annotations + +from collections import OrderedDict, deque +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +import json +import re +import threading +import time + +import grpc +from google.protobuf.empty_pb2 import Empty +from PySide6.QtCore import QBuffer, QByteArray, QIODevice, QSize +from PySide6.QtGui import QImage, QImageReader + +import fusion_input_pb2_grpc + + +@dataclass(frozen=True) +class Message: + meta: dict + jpeg: bytes + seq: int + received_ns: int + received_wall_ms: float + json_bytes: int + + @property + def key(self): + return self.meta['equipmentId'], self.meta['sourceEndpointId'] + + +@dataclass +class Source: + key: tuple + label: str + latest_data: Message | None = None + latest_image: Message | None = None + data_count: int = 0 + image_count: int = 0 + last_ns: int = 0 + + +class Store: + MAX_SOURCES = 32 + MAX_IDS = 50000 + MAX_PAIRS = 512 + MAX_PAIR_BYTES = 16 * 1024 * 1024 + + def __init__(self): + self.lock = threading.RLock() + self.wake = threading.Event() + self.sources = OrderedDict() + self.ids = OrderedDict() + self.pairs = OrderedDict() + self.pair_bytes = 0 + self.selected = None + self.generation = 0 + self.sequence = 0 + self.counters = dict(received=0, data=0, images=0, duplicates=0, + invalid=0, batches=0, jpeg_bytes=0, decoded=0, + decode_errors=0, superseded=0, displayed=0, + evicted_sources=0) + self.events = deque(maxlen=80) + self.rate_samples = deque(maxlen=240) + self.latencies = deque(maxlen=240) + self.selected_started = 0 + self.display_size = None + self.started = time.time() + self.last_error = '' + + def error(self, text): + with self.lock: + self.last_error = text + self.events.append((time.time(), text)) + + def accept(self, request): + received_ns = time.perf_counter_ns() + received_wall_ms = time.time_ns() / 1e6 + encoded_len = len(request.json.encode('utf-8')) + if encoded_len > 256 * 1024: + raise ValueError('JSON exceeds 256 KiB') + try: + meta = json.loads(request.json, parse_constant=lambda v: (_ for _ in ()).throw(ValueError('Non-finite JSON'))) + except (json.JSONDecodeError, RecursionError) as exc: + raise ValueError('Invalid JSON object') from exc + if not isinstance(meta, dict) or meta.get('schemaVersion') != 1: + raise ValueError('schemaVersion must be 1') + for field in ('messageId', 'equipmentId', 'sourceEndpointId'): + value = meta.get(field) + if not isinstance(value, str) or not value.strip() or len(value) > 240 or '\x00' in value: + raise ValueError('Invalid ' + field) + kind = meta.get('kind') + if kind not in ('DATA', 'IMAGE'): + raise ValueError('kind must be DATA or IMAGE') + frame = meta.get('frameId') + if frame is not None and (not isinstance(frame, str) or not re.fullmatch('[0-9a-f]{16}', frame)): + raise ValueError('frameId must be 16 lowercase hexadecimal characters or null') + upload = meta.get('upload') + if upload is not None: + if not isinstance(upload, dict): + raise ValueError('upload must be an object') + if upload.get('frameId') is not None and upload['frameId'] != frame: + raise ValueError('Conflicting frame IDs') + jpeg = request.image + if kind == 'DATA': + if jpeg or not isinstance(meta.get('data'), dict): + raise ValueError('DATA requires a data object and empty image bytes') + elif not frame or len(jpeg) > 2 * 1024 * 1024 or len(jpeg) < 4 or not jpeg.startswith(b'\xff\xd8') or not jpeg.endswith(b'\xff\xd9'): + raise ValueError('IMAGE requires a frameId and a JPEG of at most 2 MiB') + with self.lock: + self.counters['received'] += 1 + identity = meta['messageId'] + if identity in self.ids: + self.ids.move_to_end(identity) + self.counters['duplicates'] += 1 + return False + self.ids[identity] = None + while len(self.ids) > self.MAX_IDS: + self.ids.popitem(last=False) + self.sequence += 1 + msg = Message(meta, jpeg, self.sequence, received_ns, received_wall_ms, encoded_len) + key = msg.key + if key not in self.sources: + if len(self.sources) >= self.MAX_SOURCES: + # Preserve the source on screen while evicting an inactive source. + oldest = next(k for k in self.sources if k != self.selected) + del self.sources[oldest] + self.counters['evicted_sources'] += 1 + for pair in list(self.pairs): + if pair[:2] == oldest: + self.pair_bytes -= self.pairs.pop(pair).json_bytes + self.sources[key] = Source(key, str(meta.get('equipmentCode') or key[0])) + if self.selected is None: + self.selected = key + self.generation += 1 + self.sources.move_to_end(key) + source = self.sources[key] + source.last_ns = received_ns + if kind == 'DATA': + source.latest_data = msg + source.data_count += 1 + self.counters['data'] += 1 + if frame: + pair = (*key, frame) + old = self.pairs.pop(pair, None) + self.pair_bytes -= old.json_bytes if old else 0 + self.pairs[pair] = msg + self.pair_bytes += encoded_len + while len(self.pairs) > self.MAX_PAIRS or self.pair_bytes > self.MAX_PAIR_BYTES: + _, old = self.pairs.popitem(last=False) + self.pair_bytes -= old.json_bytes + else: + if key == self.selected and source.latest_image and source.latest_image.seq > self.selected_started: + self.counters['superseded'] += 1 + source.latest_image = msg + source.image_count += 1 + self.counters['images'] += 1 + self.counters['jpeg_bytes'] += len(jpeg) + if key == self.selected: + self.wake.set() + return True + + def select(self, key): + with self.lock: + if key != self.selected and key in self.sources: + self.selected = key + self.generation += 1 + self.selected_started = 0 + self.wake.set() + + def set_display_size(self, width, height): + with self.lock: + size = (max(1, width), max(1, height)) + if size != self.display_size: + self.display_size = size + self.generation += 1 + self.wake.set() + + def next_image(self, last_token): + with self.lock: + source = self.sources.get(self.selected) + msg = source.latest_image if source else None + token = (self.generation, msg.seq) if msg else None + if not msg or token == last_token: + return None + self.selected_started = msg.seq + return token, msg + + def source_rows(self): + with self.lock: + return [(s.key, s.label, s.data_count, s.image_count, s.last_ns) for s in self.sources.values()] + + def data_for(self, image_message=None): + with self.lock: + source = self.sources.get(self.selected) + latest = source.latest_data if source else None + paired = None + if image_message and image_message.key == self.selected: + paired = self.pairs.get((*self.selected, image_message.meta.get('frameId'))) + return latest, paired + + def painted(self, msg, latency): + with self.lock: + self.counters['displayed'] += 1 + self.latencies.append(latency) + + def snapshot(self): + with self.lock: + now = time.perf_counter() + self.rate_samples.append((now, self.counters['data'], self.counters['images'], self.counters['jpeg_bytes'])) + while len(self.rate_samples) > 2 and self.rate_samples[1][0] < now - 2: + self.rate_samples.popleft() + first = self.rate_samples[0] + elapsed = max(now - first[0], .001) + latencies = sorted(self.latencies) + return dict(self.counters, source_count=len(self.sources), + data_rate=(self.counters['data'] - first[1]) / elapsed, + image_rate=(self.counters['images'] - first[2]) / elapsed, + bytes_rate=(self.counters['jpeg_bytes'] - first[3]) / elapsed, + local_display_ms=self.latencies[-1] if self.latencies else None, + local_display_p95_ms=latencies[int((len(latencies)-1)*.95)] if latencies else None, + cached_jpeg_bytes=sum(len(s.latest_image.jpeg) for s in self.sources.values() if s.latest_image), + pair_cache_bytes=self.pair_bytes, pair_cache_count=len(self.pairs), + id_cache_count=len(self.ids), last_error=self.last_error, + uptime_seconds=time.time()-self.started) + + +class Decoder(threading.Thread): + """One latest-only compressed mailbox and one latest-only decoded mailbox.""" + def __init__(self, store, on_ready=None): + super().__init__(name='jpeg-decoder', daemon=True) + self.store = store + self.on_ready = on_ready + self.closed = threading.Event() + self.ready_lock = threading.Lock() + self.ready = None + self.last_token = None + QImageReader.setAllocationLimit(80) + + def run(self): + while not self.closed.is_set(): + item = self.store.next_image(self.last_token) + if not item: + self.store.wake.wait(.5) + self.store.wake.clear() + continue + token, msg = item + self.last_token = token + start = time.perf_counter_ns() + buf = QBuffer() + buf.setData(QByteArray(msg.jpeg)) + buf.open(QIODevice.OpenModeFlag.ReadOnly) + reader = QImageReader(buf, b'JPEG') + size = reader.size() + if size.width() <= 0 or size.height() <= 0 or size.width()*size.height() > 16_777_216: + self._bad('JPEG 尺寸无效或超过 1600 万像素') + continue + source_size = (size.width(), size.height()) + with self.store.lock: + target = self.store.display_size + if target: + ratio = min(target[0]/size.width(), target[1]/size.height(), 1.0) + if ratio < 1: + # Let the JPEG codec use scaled IDCT instead of decoding invisible pixels. + reader.setScaledSize(QSize(max(1, int(size.width()*ratio)), max(1, int(size.height()*ratio)))) + frame = reader.read() + if frame.isNull(): + self._bad('JPEG 解码失败:' + reader.errorString()) + continue + decode_ms = (time.perf_counter_ns() - start)/1e6 + with self.store.lock: + if token[0] != self.store.generation: + continue + self.store.counters['decoded'] += 1 + with self.ready_lock: + notify = self.ready is None + if self.ready: + self.store.counters['superseded'] += 1 + self.ready = (token, msg, frame, decode_ms, source_size) + if notify and self.on_ready: + self.on_ready() + + def _bad(self, message): + with self.store.lock: + self.store.counters['decode_errors'] += 1 + self.store.error(message) + + def take(self): + with self.ready_lock: + result, self.ready = self.ready, None + return result + + def close(self): + self.closed.set() + self.store.wake.set() + self.join(2) + + +class InputService(fusion_input_pb2_grpc.FusionInputServiceServicer): + def __init__(self, store): + self.store = store + + def Push(self, request_iterator, context): + # Receive immediately. Reply only when the client completes its short stream. + # Partial streams may be retried; IDs already consumed are deduplicated. + for request in request_iterator: + try: + self.store.accept(request) + except (ValueError, TypeError, RecursionError) as exc: + with self.store.lock: + self.store.counters['invalid'] += 1 + self.store.error(str(exc)) + context.abort(grpc.StatusCode.INVALID_ARGUMENT, str(exc)) + with self.store.lock: + self.store.counters['batches'] += 1 + return Empty() + + +class Receiver: + def __init__(self, store): + self.store = store + self.server = None + self.pool = None + self.port = None + + def start(self, port): + if self.server: + return self.port + pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix='grpc-input') + server = grpc.server(pool, maximum_concurrent_rpcs=16, + options=[('grpc.max_receive_message_length', 4*1024*1024), + ('grpc.so_reuseport', 0)]) + fusion_input_pb2_grpc.add_FusionInputServiceServicer_to_server(InputService(self.store), server) + try: + actual = server.add_insecure_port(f'127.0.0.1:{port}') + if not actual: + raise RuntimeError('端口绑定失败') + server.start() + except Exception: + server.stop(0) + pool.shutdown(wait=False, cancel_futures=True) + raise + self.pool, self.server, self.port = pool, server, actual + return actual + + def stop(self): + if self.server: + self.server.stop(.5).wait(timeout=1.5) + self.pool.shutdown(wait=False, cancel_futures=True) + self.server, self.pool = None, None diff --git a/tools/fusion-input-receiver/requirements-dev.txt b/tools/fusion-input-receiver/requirements-dev.txt new file mode 100644 index 0000000..4423488 --- /dev/null +++ b/tools/fusion-input-receiver/requirements-dev.txt @@ -0,0 +1,4 @@ +-r requirements.txt +grpcio-tools==1.85.1 +pyinstaller==6.20.0 +setuptools==80.9.0 diff --git a/tools/fusion-input-receiver/requirements.txt b/tools/fusion-input-receiver/requirements.txt new file mode 100644 index 0000000..efb47a0 --- /dev/null +++ b/tools/fusion-input-receiver/requirements.txt @@ -0,0 +1,3 @@ +grpcio==1.85.1 +protobuf==7.36.2 +PySide6==6.11.1 diff --git a/tools/fusion-input-receiver/tests/check_deployed.py b/tools/fusion-input-receiver/tests/check_deployed.py new file mode 100644 index 0000000..a76748a --- /dev/null +++ b/tools/fusion-input-receiver/tests/check_deployed.py @@ -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)) diff --git a/tools/fusion-input-receiver/tests/check_package.py b/tools/fusion-input-receiver/tests/check_package.py new file mode 100644 index 0000000..8914c80 --- /dev/null +++ b/tools/fusion-input-receiver/tests/check_package.py @@ -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()) diff --git a/tools/fusion-input-receiver/tests/check_window.py b/tools/fusion-input-receiver/tests/check_window.py new file mode 100644 index 0000000..3c25547 --- /dev/null +++ b/tools/fusion-input-receiver/tests/check_window.py @@ -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()) diff --git a/tools/fusion-input-receiver/tests/test_receiver.py b/tools/fusion-input-receiver/tests/test_receiver.py new file mode 100644 index 0000000..3129e11 --- /dev/null +++ b/tools/fusion-input-receiver/tests/test_receiver.py @@ -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()= 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) diff --git a/tools/fusion-input-receiver/window.py b/tools/fusion-input-receiver/window.py new file mode 100644 index 0000000..05619ec --- /dev/null +++ b/tools/fusion-input-receiver/window.py @@ -0,0 +1,468 @@ +from __future__ import annotations + +import json +import time +from datetime import datetime +from pathlib import Path + +from PySide6.QtCore import Qt, QTimer, QRectF, Signal +from PySide6.QtGui import QColor, QFont, QPainter, QPen, QShortcut, QKeySequence +from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, + QHBoxLayout, QLabel, QPushButton, QSpinBox, QSplitter, QFrame, QListWidget, + QListWidgetItem, QTabWidget, QPlainTextEdit, QTreeWidget, QTreeWidgetItem, + QComboBox, QHeaderView) + +from receiver import Store, Decoder, Receiver + + +STYLE = ''' +QMainWindow, QWidget { background: #10151e; color: #e3eaf4; font-family: "Microsoft YaHei UI"; font-size: 12px; } +QFrame#panel { background: #171e2a; border: 1px solid #2a3547; border-radius: 9px; } +QLabel { background: transparent; } +QLabel#title { font-size: 22px; font-weight: 600; } +QLabel#muted { color: #8f9fb7; } +QLabel#section { font-size: 14px; font-weight: 600; color: #eef5ff; } +QLabel#metric { font-family: "Consolas"; font-size: 24px; font-weight: 600; color: #75e0c3; } +QPushButton { background: #233047; border: 1px solid #354864; border-radius: 5px; padding: 7px 13px; } +QPushButton:hover { background: #304561; } +QPushButton:checked { background: #68512b; } +QPushButton#primary { background: #157e68; border: 1px solid #279a81; color: white; } +QPushButton:disabled { color: #647086; } +QSpinBox, QComboBox { background: #1b2636; border: 1px solid #354864; border-radius: 4px; padding: 6px; } +QListWidget, QTreeWidget, QPlainTextEdit { background: #131b27; border: none; } +QListWidget::item { padding: 12px 8px; border-bottom: 1px solid #253044; } +QListWidget::item:selected { background: #204b4b; color: #93f3d9; } +QTreeWidget::item { padding-top: 5px; padding-bottom: 5px; } +QHeaderView::section { background: #202c3d; color: #a5b6ce; padding: 7px; border: none; } +QTabWidget::pane { border: 1px solid #2a3547; } +QTabBar::tab { background: #172131; padding: 9px 13px; color: #94a7c1; } +QTabBar::tab:selected { color: #7ce2c7; background: #22364a; } +QSplitter::handle { background: #263348; } +QScrollBar:vertical { background: #152030; width: 9px; } +QScrollBar::handle:vertical { background: #42546d; border-radius: 4px; min-height: 25px; } +''' + + +def label(text='', name=None): + item = QLabel(text) + item.setTextFormat(Qt.TextFormat.PlainText) + if name: + item.setObjectName(name) + return item + + +def timestamp(value): + if isinstance(value, (int, float)): + try: + return datetime.fromtimestamp(value/1000).strftime('%H:%M:%S.%f')[:-3] + except (ValueError, OSError, OverflowError): + pass + return '—' + + +class VideoCanvas(QWidget): + def __init__(self, store): + super().__init__() + self.store = store + self.frame = None + self.message = None + self.decode_ms = None + self.source_size = None + self.low_latency = True + self.painted_seq = 0 + self.empty_text = '等待 JPEG 画面' + self.setMinimumSize(320, 240) + self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent) + + def clear(self): + self.frame = self.message = None + self.update() + + def present(self, image, msg, decode_ms, source_size): + self.frame, self.message, self.decode_ms = image, msg, decode_ms + self.source_size = source_size + self.update() + + def resizeEvent(self, event): + self.update_decode_size() + super().resizeEvent(event) + + def update_decode_size(self): + ratio = self.devicePixelRatioF() + width, height = round(self.width()*ratio), round(self.height()*ratio) + if self.low_latency: + # Half-resolution JPEG IDCT for 1080p keeps high-DPI screens from + # forcing full-frame decode work in the lowest-latency preview mode. + scale = min(960/max(1, width), 540/max(1, height), 1.0) + width, height = round(width*scale), round(height*scale) + self.store.set_display_size(width, height) + + def set_quality(self, index): + self.low_latency = index == 0 + self.update_decode_size() + + def paintEvent(self, event): + painter = QPainter(self) + painter.fillRect(self.rect(), QColor('#090e16')) + if self.frame is None: + painter.setPen(QColor('#526780')) + painter.setFont(QFont('Microsoft YaHei UI', 16)) + painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, self.empty_text) + return + width, height = self.frame.width(), self.frame.height() + ratio = min(self.width()/width, self.height()/height) + target = QRectF((self.width()-width*ratio)/2, (self.height()-height*ratio)/2, width*ratio, height*ratio) + # Nearest/fast native paint avoids smooth scaling on every frame. + painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, False) + painter.drawImage(target, self.frame) + if self.message.seq != self.painted_seq: + self.painted_seq = self.message.seq + self.store.painted(self.message, (time.perf_counter_ns()-self.message.received_ns)/1e6) + + +class MainWindow(QMainWindow): + frame_ready = Signal() + + def __init__(self, port=50051, status_file=None): + super().__init__() + self.store = Store() + self.decoder = Decoder(self.store, self.frame_ready.emit) + self.receiver = Receiver(self.store) + self.status_file = Path(status_file) if status_file else None + self.last_status_write = 0 + self.source_keys = [] + self.last_tree_token = None + self.last_raw_token = None + self.paused = False + self.setWindowTitle('融合输入接收器 · gRPC 实时画面与数据') + self.resize(1480, 940) + self.setMinimumSize(1000, 700) + self.setStyleSheet(STYLE) + self.build_ui(port) + # One queued notification per occupied decoded mailbox, never a per-frame UI backlog. + self.frame_ready.connect(self.render_latest, Qt.ConnectionType.QueuedConnection) + self.decoder.start() + self.info_timer = QTimer(self) + self.info_timer.timeout.connect(self.refresh_info) + self.info_timer.start(250) + self.fullscreen_shortcut = QShortcut(QKeySequence('F11'), self) + self.fullscreen_shortcut.activated.connect(self.toggle_fullscreen) + self.escape_shortcut = QShortcut(QKeySequence('Escape'), self) + self.escape_shortcut.activated.connect(lambda: self.showNormal() if self.isFullScreen() else None) + self.start_receiver() + + def build_ui(self, port): + root = QWidget() + outer = QVBoxLayout(root) + outer.setContentsMargins(22, 18, 22, 14) + outer.setSpacing(14) + self.setCentralWidget(root) + top = QHBoxLayout() + titles = QVBoxLayout() + titles.addWidget(label('融合输入接收器', 'title')) + titles.addWidget(label('原生桌面 / JPEG 实时画面 / 装备数据', 'muted')) + top.addLayout(titles) + top.addStretch() + self.connection = label('启动中') + top.addWidget(self.connection) + top.addSpacing(12) + top.addWidget(label('本机端口', 'muted')) + self.port = QSpinBox() + self.port.setRange(1024, 65535) + self.port.setValue(port) + self.port.setFixedWidth(96) + top.addWidget(self.port) + self.start_button = QPushButton('停止接收') + self.start_button.setObjectName('primary') + self.start_button.clicked.connect(self.toggle_receiver) + top.addWidget(self.start_button) + outer.addLayout(top) + + metrics = QHBoxLayout() + metrics.setSpacing(12) + self.metrics = {} + for key, title, hint in [('images', '图像接收', '帧 / 秒'), + ('data', '数据接收', '条 / 秒'), + ('latency', '本机显示耗时', '接收 → Qt 绘制 · 毫秒'), + ('total', '已接收消息', '去重后的数据与图像')]: + card = QFrame() + card.setObjectName('panel') + box = QVBoxLayout(card) + box.setContentsMargins(16, 10, 16, 10) + heading = QHBoxLayout() + heading.addWidget(label(title, 'muted')) + heading.addStretch() + heading.addWidget(label(hint, 'muted')) + box.addLayout(heading) + value = label('—', 'metric') + self.metrics[key] = value + box.addWidget(value) + metrics.addWidget(card) + outer.addLayout(metrics) + + split = QSplitter(Qt.Orientation.Horizontal) + split.setChildrenCollapsible(False) + source_panel = QFrame() + source_panel.setObjectName('panel') + source_layout = QVBoxLayout(source_panel) + source_layout.setContentsMargins(9, 12, 9, 9) + source_layout.addWidget(label('装备 / 数据来源', 'section')) + self.sources = QListWidget() + self.sources.setMinimumWidth(165) + self.sources.currentItemChanged.connect(self.select_source) + source_layout.addWidget(self.sources) + source_layout.addWidget(label('点击来源切换画面和数据', 'muted')) + split.addWidget(source_panel) + + video_panel = QFrame() + video_panel.setObjectName('panel') + video_layout = QVBoxLayout(video_panel) + video_layout.setContentsMargins(12, 12, 12, 12) + video_head = QHBoxLayout() + video_head.addWidget(label('实时画面', 'section')) + video_head.addStretch() + self.quality = QComboBox() + self.quality.addItems(['低延时优先', '清晰度优先']) + self.quality.setToolTip('低延时:预览解码最高 960×540;清晰度:按窗口实际像素解码。原始 JPEG 保持不变。') + video_head.addWidget(self.quality) + self.pause_button = QPushButton('暂停画面') + self.pause_button.setCheckable(True) + self.pause_button.toggled.connect(self.pause_video) + video_head.addWidget(self.pause_button) + fullscreen = QPushButton('全屏 F11') + fullscreen.clicked.connect(self.toggle_fullscreen) + video_head.addWidget(fullscreen) + video_layout.addLayout(video_head) + self.canvas = VideoCanvas(self.store) + self.quality.currentIndexChanged.connect(self.canvas.set_quality) + video_layout.addWidget(self.canvas, 1) + self.frame_line = label('帧号 — 分辨率 —', 'muted') + self.frame_line.setWordWrap(True) + video_layout.addWidget(self.frame_line) + self.timing_line = label('接收后立即解码;显示跟不上时跳过旧画面。', 'muted') + self.timing_line.setWordWrap(True) + video_layout.addWidget(self.timing_line) + split.addWidget(video_panel) + + data_panel = QFrame() + data_panel.setObjectName('panel') + data_layout = QVBoxLayout(data_panel) + data_layout.setContentsMargins(12, 12, 12, 12) + data_head = QHBoxLayout() + data_head.addWidget(label('接收数据', 'section')) + data_head.addStretch() + self.data_mode = QComboBox() + self.data_mode.addItems(['最新数据', '当前画面对应数据']) + self.data_mode.currentIndexChanged.connect(self.refresh_info) + data_head.addWidget(self.data_mode) + data_layout.addLayout(data_head) + self.data_line = label('等待数据', 'muted') + self.data_line.setWordWrap(True) + data_layout.addWidget(self.data_line) + self.pair_line = label('尚无画面可关联', 'muted') + self.pair_line.setWordWrap(True) + data_layout.addWidget(self.pair_line) + self.tabs = QTabWidget() + self.tree = QTreeWidget() + self.tree.setHeaderLabels(['字段', '接收到的值']) + self.tree.setRootIsDecorated(False) + self.tree.setAlternatingRowColors(False) + self.tree.header().setSectionResizeMode(0, QHeaderView.ResizeMode.Interactive) + self.tree.header().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch) + self.tree.setColumnWidth(0, 190) + self.tabs.addTab(self.tree, '数据字段') + self.raw = QPlainTextEdit() + self.raw.setReadOnly(True) + self.raw.setFont(QFont('Consolas', 10)) + self.raw.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap) + self.tabs.addTab(self.raw, '原始 JSON') + self.image_meta = QPlainTextEdit() + self.image_meta.setReadOnly(True) + self.image_meta.setFont(QFont('Consolas', 10)) + self.tabs.addTab(self.image_meta, '画面元数据') + self.tabs.currentChanged.connect(self.refresh_info) + data_layout.addWidget(self.tabs, 1) + data_layout.addWidget(label('完整保留原字段、单位和试验标识', 'muted')) + split.addWidget(data_panel) + split.setSizes([200, 700, 510]) + split.setStretchFactor(0, 0) + split.setStretchFactor(1, 3) + split.setStretchFactor(2, 2) + outer.addWidget(split, 1) + self.footer = label('等待系统融合软件连接到 127.0.0.1:50051', 'muted') + self.footer.setWordWrap(True) + outer.addWidget(self.footer) + self.error_line = label('') + self.error_line.setStyleSheet('color: #ffbb81;') + self.error_line.setWordWrap(True) + self.error_line.hide() + outer.addWidget(self.error_line) + + def start_receiver(self): + try: + port = self.receiver.start(self.port.value()) + self.connection.setText(f'● 正在监听 127.0.0.1:{port}') + self.connection.setStyleSheet('color: #75e0c3;') + self.start_button.setText('停止接收') + self.port.setEnabled(False) + except Exception as exc: + self.store.error(f'监听失败(端口可能已占用):{exc}') + self.connection.setText('● 未启动') + self.connection.setStyleSheet('color: #ffbb81;') + self.start_button.setText('开始接收') + + def toggle_receiver(self): + if self.receiver.server: + self.receiver.stop() + self.connection.setText('● 已停止接收') + self.connection.setStyleSheet('color: #ffbb81;') + self.start_button.setText('开始接收') + self.port.setEnabled(True) + else: + self.start_receiver() + + def pause_video(self, paused): + self.paused = paused + self.pause_button.setText('恢复最新画面' if paused else '暂停画面') + if not paused: + self.render_latest() + + def toggle_fullscreen(self): + self.showNormal() if self.isFullScreen() else self.showFullScreen() + + def select_source(self, item, previous): + if item: + self.store.select(item.data(Qt.ItemDataRole.UserRole)) + self.canvas.clear() + self.last_tree_token = self.last_raw_token = None + self.refresh_info() + + def render_latest(self): + if self.paused: + return + ready = self.decoder.take() + if ready: + token, msg, image, decode_ms, source_size = ready + with self.store.lock: + if token[0] != self.store.generation: + return + self.canvas.present(image, msg, decode_ms, source_size) + + def refresh_info(self, *_): + rows = self.store.source_rows() + keys = sorted(row[0] for row in rows) + if keys != self.source_keys: + self.source_keys = keys + self.sources.blockSignals(True) + self.sources.clear() + for key in keys: + item = QListWidgetItem() + item.setData(Qt.ItemDataRole.UserRole, key) + self.sources.addItem(item) + if key == self.store.selected: + self.sources.setCurrentItem(item) + self.sources.blockSignals(False) + by_key = {r[0]: r for r in rows} + for i, key in enumerate(self.source_keys): + _, title, data_count, image_count, last_ns = by_key[key] + item = self.sources.item(i) + item.setText(f'{title}\n数据 {data_count:,} · 图像 {image_count:,}') + item.setToolTip(f'装备:{key[0]}\n来源:{key[1]}') + + stats = self.store.snapshot() + self.metrics['images'].setText(f"{stats['image_rate']:.1f}") + self.metrics['data'].setText(f"{stats['data_rate']:.1f}") + self.metrics['latency'].setText(f"{stats['local_display_ms']:.1f}" if stats['local_display_ms'] is not None else '—') + self.metrics['total'].setText(f"{stats['data']+stats['images']:,}") + msg = self.canvas.message + if msg: + width, height = self.canvas.source_size + self.frame_line.setText(f"帧号 {msg.meta.get('frameId', '—')} 原图 {width} × {height}") + age = (time.perf_counter_ns()-msg.received_ns)/1e9 + state = '画面已暂停' if self.paused else ('画面暂无更新' if age > 3 else '实时') + self.timing_line.setText(f'{state} · JPEG 解码 {self.canvas.decode_ms:.1f} ms · 最近画面 {age:.1f} 秒前收到') + else: + self.frame_line.setText('帧号 — 分辨率 —') + self.timing_line.setText('等待当前来源的 JPEG;收到后立即显示最新画面。') + + latest, paired = self.store.data_for(msg) + chosen = paired if self.data_mode.currentIndex() == 1 else latest + if chosen: + trials = chosen.meta.get('trialIds') or [chosen.meta.get('trialId')] + self.data_line.setText(f"数据帧号 {chosen.meta.get('frameId') or '无关联标识'}\n采样 {timestamp(chosen.meta.get('sourceTime'))} 收到 {timestamp(chosen.received_wall_ms)}") + self.data_line.setToolTip('关联试验:' + ', '.join(str(t) for t in trials if t)) + else: + self.data_line.setText('等待当前画面的同帧数据' if self.data_mode.currentIndex() == 1 else '等待当前来源的数据') + if not msg: + pair_text = '尚无画面可关联' + elif paired: + pair_text = '当前画面:已找到相同装备、来源和帧号的数据' + if chosen and chosen.meta.get('frameId') != msg.meta.get('frameId'): + pair_text += ';下方显示最新数据' + else: + pair_text = '当前画面:缓存中尚无同帧数据' + self.pair_line.setText(pair_text) + if self.tabs.currentIndex() == 0: + token = chosen.seq if chosen else -1 + if token != self.last_tree_token: + self.last_tree_token = token + self.tree.setUpdatesEnabled(False) + self.tree.clear() + if chosen: + rows_out = [] + self.flatten(chosen.meta['data'], '', rows_out) + for field, value in rows_out[:400]: + item = QTreeWidgetItem([field, value]) + item.setToolTip(0, field) + item.setToolTip(1, value) + self.tree.addTopLevelItem(item) + if len(rows_out) > 400: + self.tree.addTopLevelItem(QTreeWidgetItem(['…', '更多字段请查看原始 JSON'])) + self.tree.setUpdatesEnabled(True) + elif self.tabs.currentIndex() == 1: + token = chosen.seq if chosen else -1 + if token != self.last_raw_token: + self.last_raw_token = token + self.raw.setPlainText(json.dumps(chosen.meta, ensure_ascii=False, indent=2) if chosen else '等待数据') + else: + text = json.dumps(msg.meta, ensure_ascii=False, indent=2) if msg else '等待画面' + if self.image_meta.toPlainText() != text: + self.image_meta.setPlainText(text) + self.footer.setText(f"来源 {stats['source_count']} · 批次 {stats['batches']:,} · 重复 {stats['duplicates']:,} · 跳过旧画面 {stats['superseded']:,} · 已绘制 {stats['displayed']:,} · JPEG 缓存 {stats['cached_jpeg_bytes']/1048576:.1f} MiB | 显示耗时不包含上游采集与传输") + self.error_line.setVisible(bool(stats['last_error'])) + self.error_line.setText('最近错误:' + stats['last_error']) + if self.status_file and time.monotonic()-self.last_status_write >= 1: + self.last_status_write = time.monotonic() + report = dict(stats, listening=bool(self.receiver.server), port=self.receiver.port, + checked_at=datetime.now().astimezone().isoformat(), + selected_source=self.store.selected, + displayed_frame_id=msg.meta.get('frameId') if msg else None, + displayed_size=self.canvas.source_size if msg else None, + decoded_size=[self.canvas.frame.width(), self.canvas.frame.height()] if msg else None, + display_quality='low_latency' if self.canvas.low_latency else 'clarity') + try: + self.status_file.parent.mkdir(parents=True, exist_ok=True) + temp = self.status_file.with_suffix('.tmp') + temp.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') + temp.replace(self.status_file) + except OSError as exc: + self.store.error('状态文件写入失败:' + str(exc)) + + @staticmethod + def flatten(obj, prefix, rows): + if len(rows) > 400: + return + if isinstance(obj, dict) and obj: + for k, value in obj.items(): + MainWindow.flatten(value, f'{prefix}.{k}' if prefix else k, rows) + if len(rows) > 400: + break + else: + rows.append((prefix or 'data', json.dumps(obj, ensure_ascii=False) if not isinstance(obj, str) else obj)) + + def closeEvent(self, event): + self.info_timer.stop() + self.receiver.stop() + self.decoder.close() + self.refresh_info() + event.accept() diff --git a/tools/fusion-input-receiver/使用说明.txt b/tools/fusion-input-receiver/使用说明.txt new file mode 100644 index 0000000..2d82291 --- /dev/null +++ b/tools/fusion-input-receiver/使用说明.txt @@ -0,0 +1,71 @@ +融合输入接收器(Windows 10/11 x64 / Qt 原生桌面) + +启动 +解压完整目录,双击 FusionInputReceiver.exe。不要单独移动 exe,_internal 目录是运行依赖。 +已打包版本不需要另装 Python,也不需要浏览器、Node.js 或网络服务。 +程序默认立即监听 127.0.0.1:50051;请在系统融合执行节点所在的同一台机器上运行。 +启动后系统融合软件会自动连接,之前尚未发送成功的内存队列也会重试发送。 +关闭窗口即停止接收。不要与其他实际融合程序同时占用 50051。 + +查看 +左侧按装备和数据来源分组,点击可切换。 +中间显示最新 JPEG 原始画面,等比例缩放、不裁剪。F11 全屏,Esc 退出全屏。 +默认“低延时优先”:显示预览解码最高 960×540,优先流畅和响应;需要查看更细节时切换“清晰度优先”。 +“清晰度优先”按窗口实际像素(包括屏幕缩放)解码,最高不超过原图分辨率;两档都保留原始 JPEG。 +“暂停画面”仅冻结显示,继续接收;恢复时直接显示最新画面。 +右侧“最新数据”显示最近收到的数据;“当前画面对应数据”只显示缓存中装备、来源、frameId 均相同的数据。 +数据字段页展示 data 内字段,原始 JSON 页保留完整元数据、trialIds、upload、raw 等。 +没有 frameId 的旧设备数据仍能展示,但不会被猜测为与某画面配对。 +数据页面每 250 ms 更新,画面由解码完成事件立即驱动,不等待数据页刷新。 + +低延时设计 +gRPC 接收、JPEG 解码和 Qt 绘制分别运行。 +当前选中来源只保留一个最新待解码画面和一个最新待显示画面;不会顺序播放历史帧。 +JPEG 直接从 protobuf bytes 在内存中解码,不经 Base64、磁盘或视频转码。 +图片不做固定时长缓冲,不等数据配对才显示,不等待整批接收完成才开始解码。 +Qt 使用快速等比例绘制,只有一个待处理画面通知,避免 UI 事件排队。 +JPEG 按当前画质模式和窗口显示尺寸解码,缩小时减少无效像素处理;调整窗口或画质时自动重新解码最新 JPEG。 +界面帧号旁显示的是原图分辨率,原始 JPEG bytes 保持不变。 +未选中的来源只保留最新压缩 JPEG,切换时再解码。 +显示端跳过旧画面属于预览策略,接收计数与成功批次仍按实际收到的消息计算。 + +计时口径 +“本机显示耗时”是本软件接收到该条消息至 Qt paintEvent 绘制提交完成的时间。 +它不含采集设备、上游缓存、上游传输、显示器刷新与像素响应时间。 +JPEG 解码耗时单独显示。无法根据这些数值推断完整端到端延时。 +当前没有新帧时界面保留最后一帧,并标记“画面暂无更新”及最后接收时间。 + +协议 +服务 xtrh.fusion.v1.FusionInputService +方法 Push(stream FusionInput) returns (google.protobuf.Empty) +FusionInput.json 为 UTF-8 JSON;FusionInput.image 为原始 JPEG bytes。 +DATA 必须带 data 对象且 image 为空;IMAGE 必须有合法 frameId 和 JPEG。 +短流结束后返回一个 Empty 和 OK,只表示接收完成,不代表任何实际融合算法已经执行。 +本软件用途是接收与显示,不包含实际融合算法,也不回传算法结果。 +重试按 messageId 去重。去重缓存为最近 50000 个标识,重启后清空,不承诺跨重启恰好一次。 +完整接口文档和 proto 随包放在 protocol 目录。 + +内存边界 +最多保留 32 个装备/来源组合,每个组合只缓存最新数据和最新 JPEG。 +超过来源数上限时回收最久未活动的非选中来源,当前选中来源保留。 +同帧数据关联缓存最多 512 条且 JSON 总长度最多 16 MiB;更早帧可能无法再查询配对。 +每个 JSON 上限 256 KiB,JPEG 上限 2 MiB,解码画面不超过 16777216 像素。 +内存缓存不是全量采集档案,退出后不保存数据或图片。 + +排查 +显示“监听失败”:检查是否有其他接收/融合进程占用了该端口;不会自动结束其他软件。 +只有数据没有画面:表示该来源尚未收到 IMAGE 消息,需要检查系统融合前面的图像接收和装备绑定。 +来源列表为空:等待系统融合实际调用;本软件不会自动生成演示数据。 +显示“缓存中尚无同帧数据”:没有收到该帧的 DATA,或者该帧已超出有限缓存;不会用邻近时间冒充配对。 +日志位于 %LOCALAPPDATA%\FusionInputReceiver\receiver.log,仅记录程序异常,不落盘业务画面。 + +可选启动参数 +FusionInputReceiver.exe --port 50052 +FusionInputReceiver.exe --status-file E:\wr\receiver-status.json +状态文件只输出接收计数、绘制计时、当前来源/帧号和错误信息,不输出数据正文或图像。 + +从源码运行 +Python 3.11 x64;创建 .venv,pip install -r requirements.txt,然后 python main.py。 +重新生成协议:python -m grpc_tools.protoc -I protocol --python_out=. --grpc_python_out=. protocol/fusion_input.proto +打包:安装 requirements-dev.txt 后执行 powershell -ExecutionPolicy Bypass -File build.ps1。 +测试:python tests/test_receiver.py 和 python tests/check_window.py(随机本机端口,模拟输入,不操作已部署的系统融合服务)。 diff --git a/tools/fusion-input-receiver/启动接收器.cmd b/tools/fusion-input-receiver/启动接收器.cmd new file mode 100644 index 0000000..3deb368 --- /dev/null +++ b/tools/fusion-input-receiver/启动接收器.cmd @@ -0,0 +1,2 @@ +@echo off +start "" "%~dp0dist\FusionInputReceiver\FusionInputReceiver.exe"