diff --git a/apps/backend/crydaq-server/src/main/java/com/opentest/controller/CppHttpController.java b/apps/backend/crydaq-server/src/main/java/com/opentest/controller/CppHttpController.java index fd30606f..159d9b3d 100644 --- a/apps/backend/crydaq-server/src/main/java/com/opentest/controller/CppHttpController.java +++ b/apps/backend/crydaq-server/src/main/java/com/opentest/controller/CppHttpController.java @@ -12,12 +12,19 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.util.UrlPathHelper; import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletRequest; -import java.util.Enumeration; import java.nio.charset.StandardCharsets; +import java.util.Enumeration; /** * C++层HTTP接口调用控制层 @@ -31,6 +38,9 @@ public class CppHttpController extends BaseController { private static final String CPP_SERVER_IP_HEADER = "Cpp-Server-IP"; + private static final String PROXY_PREFIX = "/v1/cpp"; + private static final String UPGRADE_UPLOAD = "/api/system/upgrade/upload"; + private static final String UPGRADE_ACTION = "/api/system/upgrade/action"; @Resource private CppHttpProxyService cppHttpProxyService; @@ -62,38 +72,21 @@ public Object proxyRequest( HttpServletRequest request, @RequestBody(required = false) byte[] body) { try { - // 获取实际请求路径 - String path = request.getRequestURI().substring(request.getContextPath().length() + "/v1/cpp".length()); - if (HttpMethod.POST.matches(request.getMethod()) && ("/api/system/upgrade/upload".equals(path) - || ("/api/system/upgrade/action".equals(path) && body != null - && "confirm".equals(JSONUtil.parseObj(new String(body, StandardCharsets.UTF_8)).getStr("action"))))) { - cppHttpProxyService.assertUpgradeIdle(serverIp); - } - String targetUrl = buildUrl(serverIp, path); - log.info("调用C++接口,URL: {}, Method: {}", targetUrl, request.getMethod()); - // 构建 HTTP 请求对象 - HttpRequest httpRequest = HttpUtil.createRequest(Method.valueOf(request.getMethod()), targetUrl); - - // 转发所有请求头(可选:只转发特定头如 Accept-Language) - Enumeration headerNames = request.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String headerName = headerNames.nextElement(); - // 仅转发设备接口需要的白名单头,避免把代理控制头透传给设备 - if ("Accept-Language".equalsIgnoreCase(headerName) - || "Content-Type".equalsIgnoreCase(headerName)) { - String headerValue = request.getHeader(headerName); - httpRequest.header(headerName, headerValue); - } - } - - // 发送请求 - HttpResponse response; + String path = request.getRequestURI().substring(request.getContextPath().length() + PROXY_PREFIX.length()); if (HttpMethod.POST.matches(request.getMethod())) { - response = httpRequest.body(body).execute(); - } else { - response = httpRequest.execute(); + String decodedPath = UrlPathHelper.defaultInstance.getPathWithinApplication(request); + String normalized = normalizeUpgradePath(decodedPath); + if (normalized.equals(PROXY_PREFIX + UPGRADE_UPLOAD)) { + return forwardUpgrade(serverIp, UPGRADE_UPLOAD, request, body); + } + if (normalized.equals(PROXY_PREFIX + UPGRADE_ACTION)) { + if ("confirm".equalsIgnoreCase(readUpgradeAction(body))) { + return forwardUpgrade(serverIp, UPGRADE_ACTION, request, body); + } + path = UPGRADE_ACTION; + } } - return buildProxyResponse(response); + return forward(buildUrl(serverIp, path), request, body); } catch (CryBusinessException e) { throw e; } catch (Exception e) { @@ -102,6 +95,59 @@ public Object proxyRequest( } } + private Object forwardUpgrade(String serverIp, String path, HttpServletRequest request, byte[] body) { + try (var target = cppHttpProxyService.openFirmwareTarget(serverIp, path)) { + return forward(target.url(), request, body); + } + } + + private static String normalizeUpgradePath(String path) { + StringBuilder collapsed = new StringBuilder(path.length()); + boolean previousSlash = false; + for (int index = 0; index < path.length(); index++) { + char value = path.charAt(index); + if (value != '/' || !previousSlash) { + collapsed.append(value); + } + previousSlash = value == '/'; + } + String normalized = StringUtils.cleanPath(collapsed.toString()); + int end = normalized.length(); + while (end > 0 && normalized.charAt(end - 1) == '/') { + end--; + } + return normalized.substring(0, end); + } + + private static String readUpgradeAction(byte[] body) { + try { + String action = JSONUtil.parseObj(new String(body == null ? new byte[0] : body, StandardCharsets.UTF_8)) + .getStr("action"); + if (StrUtil.isNotBlank(action)) return action.trim(); + } catch (RuntimeException ignored) { + // Invalid JSON and a missing action are both parameter errors. + } + throw new CryBusinessException(ErrorCode.PARAMETER, "固件升级操作缺少有效的 action"); + } + + private Object forward(String targetUrl, HttpServletRequest request, byte[] body) { + log.info("调用C++接口,URL: {}, Method: {}", targetUrl, request.getMethod()); + HttpRequest httpRequest = HttpUtil.createRequest(Method.valueOf(request.getMethod()), targetUrl); + Enumeration headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + if ("Accept-Language".equalsIgnoreCase(headerName) || "Content-Type".equalsIgnoreCase(headerName)) { + httpRequest.header(headerName, request.getHeader(headerName)); + } + } + if (HttpMethod.POST.matches(request.getMethod())) { + httpRequest.body(body); + } + try (HttpResponse response = httpRequest.execute()) { + return buildProxyResponse(response); + } + } + private Object buildProxyResponse(HttpResponse response) { int status = response.getStatus(); String responseBody = response.body(); diff --git a/apps/backend/crydaq-server/src/test/java/com/opentest/controller/CppHttpFirmwareUpgradeTest.java b/apps/backend/crydaq-server/src/test/java/com/opentest/controller/CppHttpFirmwareUpgradeTest.java new file mode 100644 index 00000000..8cd27ce5 --- /dev/null +++ b/apps/backend/crydaq-server/src/test/java/com/opentest/controller/CppHttpFirmwareUpgradeTest.java @@ -0,0 +1,124 @@ +package com.opentest.controller; + +import com.opentest.common.exception.CryBusinessException; +import com.opentest.common.exception.ErrorCode; +import com.opentest.service.CppHttpProxyService; +import com.opentest.service.jni.FirmwareUpgradeAccess; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.test.util.ReflectionTestUtils; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +class CppHttpFirmwareUpgradeTest { + private static final String DEVICE = "192.0.2.50"; + private static final String UPLOAD = "/api/system/upgrade/upload"; + private static final String ACTION = "/api/system/upgrade/action"; + + private final CppHttpProxyService service = mock(CppHttpProxyService.class); + private final CppHttpController controller = new CppHttpController(); + + CppHttpFirmwareUpgradeTest() { + ReflectionTestUtils.setField(controller, "cppHttpProxyService", service); + } + + @Test void uploadAndConfirmTakeTheSameGuardThroughNormalizedRoutes() { + when(service.openFirmwareTarget(DEVICE, UPLOAD)).thenThrow(new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY)); + when(service.openFirmwareTarget(DEVICE, ACTION)).thenThrow(new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY)); + + assertBusy(UPLOAD + "/", new byte[]{1}); + assertBusy(ACTION, bytes("{\"action\":\"Confirm\"}")); + verify(service).openFirmwareTarget(DEVICE, UPLOAD); + verify(service).openFirmwareTarget(DEVICE, ACTION); + verify(service, never()).buildTargetUrl(anyString(), anyString()); + } + + @Test void rejectsMalformedUpgradeActionsAsParameterErrors() { + assertEquals(ErrorCode.PARAMETER.getErrcode(), assertThrows(CryBusinessException.class, + () -> controller.proxyRequest(DEVICE, post(ACTION), bytes("not-json"))).getErrcode()); + verifyNoInteractions(service); + } + + @ParameterizedTest + @ValueSource(strings = {"/api//system/upgrade/upload", "/api/system/upgrade/%75pload", "/api/system/upgrade/./upload", "/api/system/upgrade/upload/"}) + void equivalentUploadPathsCannotBypassTheGuard(String path) { + when(service.openFirmwareTarget(DEVICE, UPLOAD)).thenThrow(new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY)); + assertBusy(path, new byte[]{1}); + verify(service).openFirmwareTarget(DEVICE, UPLOAD); + verify(service, never()).buildTargetUrl(anyString(), anyString()); + } + + @Test void holdsTheUpgradeReservationDuringForwardingAndAllowsCancelSeparately() throws Exception { + var access = new FirmwareUpgradeAccess(); + var heldDuringUpload = new AtomicBoolean(); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext(UPLOAD, exchange -> { + try (var activity = access.reserveActivity(List.of(DEVICE))) { + heldDuringUpload.set(false); + } catch (CryBusinessException busy) { + heldDuringUpload.set(busy.getErrcode() == ErrorCode.JNI_DEVICE_BUSY.getErrcode()); + } + exchange.getRequestBody().readAllBytes(); + reply(exchange); + }); + server.createContext(ACTION, exchange -> { + exchange.getRequestBody().readAllBytes(); + reply(exchange); + }); + server.start(); + try { + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + when(service.openFirmwareTarget(DEVICE, UPLOAD)) + .thenAnswer(invocation -> new CppHttpProxyService.FirmwareTarget(base + UPLOAD, access.reserveUpgrade(DEVICE))); + when(service.buildTargetUrl(DEVICE, ACTION)).thenReturn(base + ACTION); + + controller.proxyRequest(DEVICE, post(UPLOAD), new byte[]{1}); + assertTrue(heldDuringUpload.get()); + try (var activity = access.reserveActivity(List.of(DEVICE))) { + controller.proxyRequest(DEVICE, post(ACTION), bytes("{\"action\":\"cancel\"}")); + } + verify(service, never()).openFirmwareTarget(DEVICE, ACTION); + } finally { + server.stop(0); + } + } + + private void assertBusy(String path, byte[] body) { + assertEquals(ErrorCode.JNI_DEVICE_BUSY.getErrcode(), assertThrows(CryBusinessException.class, + () -> controller.proxyRequest(DEVICE, post(path), body)).getErrcode()); + } + + private static MockHttpServletRequest post(String path) { + return new MockHttpServletRequest("POST", "/v1/cpp" + path); + } + + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static void reply(HttpExchange exchange) throws IOException { + byte[] response = bytes("{\"code\":0}"); + exchange.sendResponseHeaders(200, response.length); + try (var output = exchange.getResponseBody()) { + output.write(response); + } + } +} diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/CppHttpProxyService.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/CppHttpProxyService.java index 590514e3..452fa2ae 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/CppHttpProxyService.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/CppHttpProxyService.java @@ -8,6 +8,8 @@ import com.opentest.common.model.entity.Device; import com.opentest.core.jni.model.JNIDriver; import com.opentest.service.jni.AudioJNIBridgeService; +import com.opentest.service.jni.FirmwareUpgradeAccess; +import com.opentest.service.jni.NetworkDeviceAddress; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -27,37 +29,50 @@ public class CppHttpProxyService { @Resource private AudioJNIBridgeService audioJNIBridgeService; - public void assertUpgradeIdle(String serverIp) { - List drivers = audioJNIBridgeService.getDrivers(true); - if (drivers != null) { - for (JNIDriver driver : drivers) { - if (driver != null && OPENDAQ_PROTOCOL.equalsIgnoreCase(driver.getProtocol()) && serverIp.equals(driver.getIp())) { - Device device = new Device(); - device.setProtocol(OPENDAQ_PROTOCOL); - device.setDeviceName(driver.getDevId()); - device.setIpAddress(serverIp); - audioJNIBridgeService.assertFirmwareUpgradeIdle(device); - return; - } - } + public record FirmwareTarget(String url, FirmwareUpgradeAccess.Lease reservation) implements AutoCloseable { + @Override + public void close() { + reservation.close(); } - throw new CryBusinessException(ErrorCode.JNI_DEVICE_NOT_FOUND); } - public String buildTargetUrl(String serverIp, String path) { + public FirmwareTarget openFirmwareTarget(String serverIp, String path) { + requireAddress(serverIp); + JNIDriver driver = findOpenDaqDriver(serverIp); + if (driver == null) { + throw new CryBusinessException(ErrorCode.JNI_DEVICE_NOT_FOUND); + } + Device device = asOpenDaqDevice(driver); + var reservation = audioJNIBridgeService.reserveFirmwareUpgrade(device); + try { + int port = resolveHttpPort(driverIdentity(driver)); + return new FirmwareTarget(formatTargetUrl(driver.getIp(), port, path), reservation); + } catch (RuntimeException | Error failure) { + reservation.close(); + throw failure; + } + } + + private static void requireAddress(String serverIp) { if (StrUtil.isBlank(serverIp)) { throw new CryBusinessException(ErrorCode.PARAMETER, "服务器IP不能为空"); } + } + + public String buildTargetUrl(String serverIp, String path) { + requireAddress(serverIp); if (audioJNIBridgeService.isExplicitDeviceSelection() && (path == null || !path.startsWith("/") || path.indexOf('\r') >= 0 || path.indexOf('\n') >= 0)) { throw new CryBusinessException(ErrorCode.PARAMETER, "设备 HTTP 路径必须位于已选设备内部"); } - int serverPort = resolveHttpPort(serverIp); - return StrUtil.format("http://{}:{}{}", serverIp, serverPort, path); + return formatTargetUrl(serverIp, resolveHttpPort(resolveOpenDaqDeviceId(serverIp)), path); + } + + private static String formatTargetUrl(String serverIp, int port, String path) { + return StrUtil.format("http://{}:{}{}", NetworkDeviceAddress.httpHost(serverIp), port, path); } - private int resolveHttpPort(String serverIp) { - String deviceId = resolveOpenDaqDeviceId(serverIp); + private int resolveHttpPort(String deviceId) { String portValue = audioJNIBridgeService.readDeviceProperty(OPENDAQ_PROTOCOL, deviceId, HTTP_PORT_PROPERTY); Integer port = parseHttpPort(portValue); if (port == null || port < MIN_PORT || port > MAX_PORT) { @@ -67,33 +82,45 @@ private int resolveHttpPort(String serverIp) { } private String resolveOpenDaqDeviceId(String serverIp) { + JNIDriver driver = findOpenDaqDriver(serverIp); + if (driver != null) { + return driverIdentity(driver); + } + if (audioJNIBridgeService.isExplicitDeviceSelection()) { + throw new CryBusinessException(ErrorCode.JNI_DEVICE_NOT_FOUND, "HTTP 目标不在本进程实际已选设备集合中"); + } + log.warn("未在在线OPENDAQ设备中找到IP匹配项,使用连接串读取HTTPPort,serverIp={}", serverIp); + return OPENDAQ_DEVICE_ID_PREFIX + NetworkDeviceAddress.httpHost(serverIp); + } + + private JNIDriver findOpenDaqDriver(String serverIp) { List drivers = audioJNIBridgeService.getDrivers(true); if (drivers != null) { for (JNIDriver driver : drivers) { - if (driver == null - || !StrUtil.equalsIgnoreCase(OPENDAQ_PROTOCOL, driver.getProtocol()) - || !StrUtil.equals(serverIp, driver.getIp())) { - continue; - } - String deviceName = driver.getDevId(); - if (StrUtil.isNotBlank(deviceName)) { - if (audioJNIBridgeService.isExplicitDeviceSelection()) { - // HTTP 写入也必须绑定已选成功连接,不能绕过 JNI setter 的范围约束。 - Device device = new Device(); - device.setProtocol(OPENDAQ_PROTOCOL); device.setDeviceName(deviceName); device.setIpAddress(serverIp); - String identity = audioJNIBridgeService.getJniDeviceId(device); - audioJNIBridgeService.requireSelectedDevice(OPENDAQ_PROTOCOL, identity); - return identity; - } - return StrUtil.format("{}({})", deviceName, serverIp); + if (driver != null && OPENDAQ_PROTOCOL.equalsIgnoreCase(driver.getProtocol()) + && StrUtil.isNotBlank(driver.getDevId()) && NetworkDeviceAddress.sameHost(serverIp, driver.getIp())) { + return driver; } } } + return null; + } + + private String driverIdentity(JNIDriver driver) { if (audioJNIBridgeService.isExplicitDeviceSelection()) { - throw new CryBusinessException(ErrorCode.JNI_DEVICE_NOT_FOUND, "HTTP 目标不在本进程实际已选设备集合中"); + String identity = audioJNIBridgeService.getJniDeviceId(asOpenDaqDevice(driver)); + audioJNIBridgeService.requireSelectedDevice(OPENDAQ_PROTOCOL, identity); + return identity; } - log.warn("未在在线OPENDAQ设备中找到IP匹配项,使用连接串读取HTTPPort,serverIp={}", serverIp); - return OPENDAQ_DEVICE_ID_PREFIX + serverIp; + return StrUtil.format("{}({})", driver.getDevId(), driver.getIp()); + } + + private static Device asOpenDaqDevice(JNIDriver driver) { + Device device = new Device(); + device.setProtocol(OPENDAQ_PROTOCOL); + device.setDeviceName(driver.getDevId()); + device.setIpAddress(driver.getIp()); + return device; } private Integer parseHttpPort(String portValue) { diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceProtocolVersionService.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceProtocolVersionService.java index ca5abcf2..8eb9f41d 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceProtocolVersionService.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/DeviceProtocolVersionService.java @@ -5,13 +5,15 @@ import com.opentest.common.model.dto.DeviceProtocolVersionDto; import com.opentest.core.jni.AudioJNIBridge; import com.opentest.service.deviceplugin.DevicePluginManagement; +import lombok.extern.slf4j.Slf4j; +import java.nio.file.Path; import java.util.List; import java.util.Locale; -import java.nio.file.Path; import org.springframework.stereotype.Service; /** Versions belong to the active device integration, not its package manifest. */ @Service +@Slf4j public class DeviceProtocolVersionService { private final DevicePluginManagement devices; private final AudioJNIBridge bridge; @@ -50,8 +52,10 @@ private DeviceProtocolVersionDto version(JsonNode packages, String id, String na && response.path("data").isTextual() && !response.path("data").asText().isBlank()) { return new DeviceProtocolVersionDto(name, response.path("data").asText(), "ready"); } + log.debug("SDK version query returned no version, packageId={}, code={}", id, + response == null ? null : response.path("code").asInt()); } catch (Exception | LinkageError error) { - // A missing native entry or one unavailable SDK must not hide the other row. + log.debug("SDK version query failed, packageId={}, errorType={}", id, error.getClass().getSimpleName()); } return new DeviceProtocolVersionDto(name, null, "failed"); } diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/AudioJNIBridgeService.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/AudioJNIBridgeService.java index d98beb44..03296dfa 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/AudioJNIBridgeService.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/AudioJNIBridgeService.java @@ -259,30 +259,24 @@ static String bluetoothInputName(String name) { private final ConcurrentMap activeGeneratorSessionLocks = new ConcurrentHashMap<>(); private final AtomicLong activeGeneratorSessionSequence = new AtomicLong(); private volatile PlaybackStreamSessionManager playbackStreams; - private final ConcurrentMap finitePlaybackDevices = new ConcurrentHashMap<>(); - - public void assertFirmwareUpgradeIdle(Device device) { - String nativeId = getJniDeviceId(device); - if (continueCaptureManager.hasActiveDevice(device) - || playbackStreams().hasActiveDevice(device.getProtocol(), nativeId) - || finitePlaybackDevices.containsKey(device.getProtocol() + "\u0000" + nativeId)) { - throw new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY); - } + public FirmwareUpgradeAccess.Lease reserveFirmwareUpgrade(Device device) { + return continueCaptureManager.firmwareUpgradeAccess().reserveUpgrade(getJniDeviceId(device)); } private int withFinitePlaybackActivity(String protocol, String requestJson, Supplier operation) { + if (!"OPENDAQ".equalsIgnoreCase(protocol)) return operation.get(); JSONObject request = JSONUtil.parseObj(requestJson); Set devices = new HashSet<>(); for (String direction : List.of("outputs", "inputs")) { var channels = request.getJSONArray(direction); if (channels != null) channels.forEach(value -> { String id = JSONUtil.parseObj(value).getStr("deviceId"); - if (id != null) devices.add(protocol + "\u0000" + id); + if (id != null) devices.add(id); }); } - devices.forEach(key -> finitePlaybackDevices.merge(key, 1, Integer::sum)); - try { return operation.get(); } - finally { devices.forEach(key -> finitePlaybackDevices.computeIfPresent(key, (ignored, count) -> count > 1 ? count - 1 : null)); } + try (var activity = continueCaptureManager.firmwareUpgradeAccess().reserveActivity(devices)) { + return operation.get(); + } } // 保存实际运行配置;独立于页面选择,供差异修改、补偿和暂停恢复使用。 private final ConcurrentMap> generatorRuntimeConfigs = new ConcurrentHashMap<>(); @@ -307,7 +301,8 @@ private PlaybackStreamSessionManager playbackStreams() { synchronized (this) { current = playbackStreams; if (current == null) { - current = new PlaybackStreamSessionManager(() -> this.audioJNIBridge); + current = new PlaybackStreamSessionManager(() -> this.audioJNIBridge, + continueCaptureManager.firmwareUpgradeAccess()); playbackStreams = current; } } @@ -6837,7 +6832,7 @@ private Device findDeviceByChannel(ChannelDto channel) { return deviceService.findById(channel.getDeviceId(), false); } - private static String normalizeJniDeviceId(String deviceName, String ipAddress) { + static String normalizeJniDeviceId(String deviceName, String ipAddress) { if (StrUtil.isEmpty(ipAddress) || StrUtil.equals("127.0.0.1", ipAddress)) { return deviceName; } diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/CaptureInputResources.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/CaptureInputResources.java index 6da57a26..810c13bf 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/CaptureInputResources.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/CaptureInputResources.java @@ -14,10 +14,6 @@ public final class CaptureInputResources { private final Map activeChannels = new HashMap<>(); private final Map resources = new HashMap<>(); - synchronized boolean hasActiveDevice(String identity) { - return resources.keySet().stream().anyMatch(key -> key.equals(identity) || key.startsWith(identity + "\u0000")); - } - private static final class Occupancy { private int shared; private boolean exclusive; @@ -28,6 +24,11 @@ synchronized Lease acquire(List keys, boolean exclusive) { } synchronized Lease acquire(List keys, List channels, boolean exclusive, Integer limit) { + return acquire(keys, channels, exclusive, limit, null); + } + + synchronized Lease acquire(List keys, List channels, boolean exclusive, Integer limit, + FirmwareUpgradeAccess.Lease deviceActivity) { List distinct = keys.stream().distinct().toList(); List physicalChannels = channels.stream().distinct().toList(); long additional = physicalChannels.stream().filter(key -> !activeChannels.containsKey(key)).count(); @@ -49,19 +50,22 @@ synchronized Lease acquire(List keys, List channels, boolean exc } } physicalChannels.forEach(key -> activeChannels.merge(key, 1, Integer::sum)); - return new Lease(distinct, physicalChannels, exclusive); + return new Lease(distinct, physicalChannels, exclusive, deviceActivity); } public final class Lease implements AutoCloseable { private final List keys; private final List channels; private final boolean exclusive; + private final FirmwareUpgradeAccess.Lease deviceActivity; private final AtomicBoolean closed = new AtomicBoolean(); - private Lease(List keys, List channels, boolean exclusive) { + private Lease(List keys, List channels, boolean exclusive, + FirmwareUpgradeAccess.Lease deviceActivity) { this.keys = keys; this.channels = channels; this.exclusive = exclusive; + this.deviceActivity = deviceActivity; } @Override @@ -83,6 +87,7 @@ public void close() { } } } + if (deviceActivity != null) deviceActivity.close(); } } } diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/ContinueCaptureManager.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/ContinueCaptureManager.java index a37b8b77..25f410cf 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/ContinueCaptureManager.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/ContinueCaptureManager.java @@ -39,6 +39,7 @@ public class ContinueCaptureManager { private AudioJNIBridgeService audioJNIBridgeService; @Resource private LicenseJNIBridgeService captureLicenseService; private final CaptureInputResources inputResources = new CaptureInputResources(); + private final FirmwareUpgradeAccess firmwareUpgradeAccess = new FirmwareUpgradeAccess(); @Value("${crydaq.capture.transition-timeout-ms:10000}") private long transitionTimeoutMs = 10_000L; @@ -164,6 +165,7 @@ private CaptureInputResources.Lease reserveInputs(Map> boolean exclusive, Integer limit) { List resources = new ArrayList<>(); List channels = new ArrayList<>(); + List openDaqIds = new ArrayList<>(); inputs.forEach((device, values) -> { String identity = AudioJNIBridgeService.inputCaptureIdentity(device, values); String protocol = device.getProtocol(); @@ -171,7 +173,11 @@ private CaptureInputResources.Lease reserveInputs(Map> boolean perChannel = "OPENDAQ".equalsIgnoreCase(protocol); if (perChannel && values.isEmpty()) throw new CryBusinessException(ErrorCode.CHECK_PARAMETER, "OPENDAQ 输入占用缺少物理通道"); - if (!perChannel) resources.add(identity); + if (perChannel) { + openDaqIds.add(AudioJNIBridgeService.normalizeJniDeviceId(device.getDeviceName(), device.getIpAddress())); + } else { + resources.add(identity); + } for (ChannelDto channel : values) { Integer number = channel.getJniChannelNumber(); if (perChannel && (number == null || number < 0)) @@ -181,7 +187,13 @@ private CaptureInputResources.Lease reserveInputs(Map> if (perChannel) resources.add(physical); } }); - return inputResources.acquire(resources, channels, exclusive, limit); + var activity = firmwareUpgradeAccess.reserveActivity(openDaqIds); + try { + return inputResources.acquire(resources, channels, exclusive, limit, activity); + } catch (RuntimeException | Error failure) { + activity.close(); + throw failure; + } } public CaptureLease reserveCapture(Device device) { @@ -189,14 +201,8 @@ public CaptureLease reserveCapture(Device device) { return new CaptureLease(devices.computeIfAbsent(identity, key -> new DeviceCapture()), device); } - public boolean hasActiveDevice(Device device) { - String identity = AudioJNIBridgeService.inputCaptureIdentity(device, List.of()); - if (inputResources.hasActiveDevice(identity)) return true; - DeviceCapture state = devices.get(identity); - if (state == null) return false; - synchronized (state) { - return state.current != null || !state.carryForward.isEmpty() || !state.legacyLeases.isEmpty(); - } + FirmwareUpgradeAccess firmwareUpgradeAccess() { + return firmwareUpgradeAccess; } private CaptureLease reserveLegacyCapture(Device device) { diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/FirmwareUpgradeAccess.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/FirmwareUpgradeAccess.java new file mode 100644 index 00000000..8394e77a --- /dev/null +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/FirmwareUpgradeAccess.java @@ -0,0 +1,57 @@ +package com.opentest.service.jni; + +import com.opentest.common.exception.CryBusinessException; +import com.opentest.common.exception.ErrorCode; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Coordinates OpenDAQ firmware requests with capture and playback admission. */ +public final class FirmwareUpgradeAccess { + private final Map activities = new HashMap<>(); + private final Set upgrades = new HashSet<>(); + + public synchronized Lease reserveActivity(Collection deviceIds) { + List ids = deviceIds.stream().distinct().toList(); + if (ids.stream().anyMatch(upgrades::contains)) { + throw new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY); + } + ids.forEach(id -> activities.merge(id, 1, Integer::sum)); + return new Lease(ids, false); + } + + public synchronized Lease reserveUpgrade(String deviceId) { + if (activities.containsKey(deviceId) || !upgrades.add(deviceId)) { + throw new CryBusinessException(ErrorCode.JNI_DEVICE_BUSY); + } + return new Lease(List.of(deviceId), true); + } + + public final class Lease implements AutoCloseable { + private final List deviceIds; + private final boolean upgrade; + private boolean closed; + + private Lease(List deviceIds, boolean upgrade) { + this.deviceIds = deviceIds; + this.upgrade = upgrade; + } + + @Override + public void close() { + synchronized (FirmwareUpgradeAccess.this) { + if (closed) return; + closed = true; + if (upgrade) { + upgrades.removeAll(deviceIds); + } else { + deviceIds.forEach(id -> activities.computeIfPresent(id, (key, count) -> count == 1 ? null : count - 1)); + } + } + } + } +} diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/NetworkDeviceAddress.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/NetworkDeviceAddress.java index b87ee8a2..ec49fc42 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/NetworkDeviceAddress.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/NetworkDeviceAddress.java @@ -6,12 +6,41 @@ import com.opentest.common.exception.ErrorCode; import java.net.URI; +import java.util.Objects; /** 网络设备地址的接收边界;不从候选信息、历史记录或请求参数猜测 JNI 返回地址。 */ public final class NetworkDeviceAddress { private NetworkDeviceAddress() { } + /** Compare IP literals without DNS. Link-local interfaces remain distinct. */ + public static boolean sameHost(String first, String second) { + return first != null && second != null && Objects.equals(hostKey(first), hostKey(second)); + } + + public static String httpHost(String address) { + return address.indexOf(':') >= 0 && !address.startsWith("[") + && InetAddresses.isInetAddress(withoutZone(address)) + ? "[" + address + "]" : address; + } + + private static String hostKey(String address) { + String literal = address.trim(); + if (literal.startsWith("[") && literal.endsWith("]")) { + literal = literal.substring(1, literal.length() - 1); + } + String host = withoutZone(literal); + if (!InetAddresses.isInetAddress(host)) { + return address; + } + return InetAddresses.toAddrString(InetAddresses.forString(host)) + literal.substring(host.length()); + } + + private static String withoutZone(String literal) { + int zone = literal.indexOf('%'); + return zone < 0 ? literal : literal.substring(0, zone); + } + public static boolean requiresAddress(String protocol, boolean networkDevice) { return "OPENDAQ".equals(protocol) || ("OTHER".equals(protocol) && networkDevice); } diff --git a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/playback/PlaybackStreamSessionManager.java b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/playback/PlaybackStreamSessionManager.java index c2d206fa..f740c4f4 100644 --- a/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/playback/PlaybackStreamSessionManager.java +++ b/apps/backend/crydaq-service/src/main/java/com/opentest/service/jni/playback/PlaybackStreamSessionManager.java @@ -8,6 +8,7 @@ import com.opentest.core.jni.AudioJNIBridge; import com.opentest.core.jni.PluginErrorMessages; import com.opentest.core.jni.model.JNIUtils; +import com.opentest.service.jni.FirmwareUpgradeAccess; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,11 +28,17 @@ public final class PlaybackStreamSessionManager { private static final Logger log = LoggerFactory.getLogger(PlaybackStreamSessionManager.class); private final Supplier bridge; + private final FirmwareUpgradeAccess firmwareUpgradeAccess; private final Map active = new LinkedHashMap<>(); private final Set startupWatches = new LinkedHashSet<>(); public PlaybackStreamSessionManager(Supplier bridge) { + this(bridge, new FirmwareUpgradeAccess()); + } + + public PlaybackStreamSessionManager(Supplier bridge, FirmwareUpgradeAccess firmwareUpgradeAccess) { this.bridge = bridge; + this.firmwareUpgradeAccess = firmwareUpgradeAccess; } public record Address(String protocol, String deviceId, int channel) { } @@ -93,6 +100,7 @@ public static final class Session { private final BooleanSupplier cancelled; private volatile boolean released; private volatile RuntimeException failure; + private FirmwareUpgradeAccess.Lease activity; private Session(String protocol, JSONObject request, List
addresses, BooleanSupplier cancelled, BooleanSupplier owner) { this.owner = owner; this.cancelled = cancelled; @@ -123,6 +131,11 @@ public Session start(String protocol, JSONObject request, float[][] data, Boolea if (session.addresses.stream().anyMatch(active::containsKey)) { JNIUtils.checkJniReturn(13101002, "启动持续播放:通道已占用"); } + List openDaqIds = session.addresses.stream() + .filter(address -> "OPENDAQ".equals(address.protocol())) + .map(Address::deviceId) + .toList(); + session.activity = firmwareUpgradeAccess.reserveActivity(openDaqIds); session.addresses.forEach(address -> active.put(address, session)); } boolean nativeStarted = false; @@ -271,13 +284,6 @@ public boolean hasActive(List
addresses) { } } - public boolean hasActiveDevice(String protocol, String deviceId) { - synchronized (active) { - return active.keySet().stream().anyMatch(address -> - Objects.equals(protocol, address.protocol()) && Objects.equals(deviceId, address.deviceId())); - } - } - public boolean isRunning(List
addresses) { Set candidates; synchronized (active) { @@ -397,6 +403,7 @@ private void stopNative(Session session) { "停止持续播放", session.protocol, deviceIds(session.snapshot)); synchronized (active) { session.addresses.forEach(address -> active.remove(address, session)); + session.activity.close(); session.released = true; } } diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/DeviceSelectionBusinessBoundaryTest.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/DeviceSelectionBusinessBoundaryTest.java index 5be7854b..25b63728 100644 --- a/apps/backend/crydaq-service/src/test/java/com/opentest/service/DeviceSelectionBusinessBoundaryTest.java +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/DeviceSelectionBusinessBoundaryTest.java @@ -1,5 +1,8 @@ package com.opentest.service; +import com.opentest.common.exception.CryBusinessException; +import com.opentest.common.exception.ErrorCode; +import com.opentest.common.model.dto.ChannelDto; import com.opentest.common.model.entity.BoxChannel; import com.opentest.common.model.entity.Channel; import com.opentest.common.model.entity.Device; @@ -10,9 +13,12 @@ import com.opentest.dal.mapper.sqlite.DeviceMapper; import com.opentest.service.jni.AudioJNIBridgeService; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.springframework.test.util.ReflectionTestUtils; import java.util.List; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -24,6 +30,7 @@ import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -92,6 +99,63 @@ class DeviceSelectionBusinessBoundaryTest { assertEquals("http://192.0.2.50:8080/device/config", proxy.buildTargetUrl("192.0.2.50", "/device/config")); } + @ParameterizedTest + @CsvSource({ + "192.0.2.50,192.0.2.50,192.0.2.50", + "[2001:db8::1],2001:0db8:0:0:0:0:0:1,[2001:db8::1]", + "'[fe80::1%3]','[fe80:0:0:0:0:0:0:1%3]','[fe80::1%3]'" + }) + void firmwareTargetUsesDriverIdentityAndExcludesCapture(String discovered, String request, String expectedHttpHost) { + var audio = spy(new AudioJNIBridgeService()); + doReturn(false).when(audio).isExplicitDeviceSelection(); + JNIDriver driver = new JNIDriver(); + driver.setProtocol("OPENDAQ"); + driver.setDevid("Sono-A"); + driver.setIp(discovered); + doReturn(List.of(driver)).when(audio).getDrivers(true); + doReturn("8080").when(audio).readDeviceProperty("OPENDAQ", "Sono-A(" + discovered + ")", "HTTPPort"); + CppHttpProxyService proxy = new CppHttpProxyService(); + ReflectionTestUtils.setField(proxy, "audioJNIBridgeService", audio); + Device device = device(1L, "Sono-A", discovered); + ChannelDto channel = new ChannelDto(); + channel.setJniChannelNumber(1); + + try (var capture = audio.reserveExclusiveInputs(Map.of(device, List.of(channel)))) { + assertEquals(ErrorCode.JNI_DEVICE_BUSY.getErrcode(), assertThrows(CryBusinessException.class, + () -> proxy.openFirmwareTarget(request, "/api/system/upgrade/upload")).getErrcode()); + } + try (var upgrade = proxy.openFirmwareTarget(request, "/api/system/upgrade/upload")) { + assertEquals("http://" + expectedHttpHost + ":8080/api/system/upgrade/upload", upgrade.url()); + assertEquals(ErrorCode.JNI_DEVICE_BUSY.getErrcode(), assertThrows(CryBusinessException.class, + () -> audio.reserveExclusiveInputs(Map.of(device, List.of(channel)))).getErrcode()); + } + try (var capture = audio.reserveExclusiveInputs(Map.of(device, List.of(channel)))) { + verify(audio).readDeviceProperty("OPENDAQ", "Sono-A(" + discovered + ")", "HTTPPort"); + } + doThrow(new IllegalStateException("Port lookup failed")).when(audio) + .readDeviceProperty("OPENDAQ", "Sono-A(" + discovered + ")", "HTTPPort"); + assertThrows(IllegalStateException.class, () -> proxy.openFirmwareTarget(request, "/api/system/upgrade/upload")); + try (var capture = audio.reserveExclusiveInputs(Map.of(device, List.of(channel)))) { + // Failed target construction must release the device for capture. + } + } + + @Test void firmwareTargetRequiresAnAddressAndDoesNotMatchAnotherIpv6Zone() { + var audio = mock(AudioJNIBridgeService.class); + JNIDriver driver = new JNIDriver(); + driver.setProtocol("OPENDAQ"); + driver.setDevid("Sono-A"); + driver.setIp("[fe80::1%3]"); + when(audio.getDrivers(true)).thenReturn(List.of(driver)); + CppHttpProxyService proxy = new CppHttpProxyService(); + ReflectionTestUtils.setField(proxy, "audioJNIBridgeService", audio); + assertEquals(ErrorCode.PARAMETER.getErrcode(), assertThrows(CryBusinessException.class, + () -> proxy.openFirmwareTarget(null, "/api/system/upgrade/upload")).getErrcode()); + assertEquals(ErrorCode.JNI_DEVICE_NOT_FOUND.getErrcode(), assertThrows(CryBusinessException.class, + () -> proxy.openFirmwareTarget("[fe80::1%4]", "/api/system/upgrade/upload")).getErrcode()); + verify(audio, never()).reserveFirmwareUpgrade(any()); + } + private static Device device(long id, String name, String address) { Device device = new Device(); device.setId(id); device.setDeviceName(name); device.setIpAddress(address); device.setProtocol("OPENDAQ"); device.setActiveState(1); device.setProductType("SonoDAQ"); return device; diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/AudioJNIBridgeFinitePlaybackV1Test.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/AudioJNIBridgeFinitePlaybackV1Test.java index 509b1206..c469160d 100644 --- a/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/AudioJNIBridgeFinitePlaybackV1Test.java +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/AudioJNIBridgeFinitePlaybackV1Test.java @@ -27,15 +27,20 @@ void firmwareUpgradeRejectsTheDeviceDuringFinitePlaybackAndReleasesAfterNativeFa idle.setProtocol("OPENDAQ"); AudioJNIBridge bridge = new AudioJNIBridge() { @Override public int playAudioDataBatchV1(String protocol, String request, float[][] data) { - assertThrows(CryBusinessException.class, () -> service.assertFirmwareUpgradeIdle(playing)); - assertDoesNotThrow(() -> service.assertFirmwareUpgradeIdle(idle)); + assertThrows(CryBusinessException.class, () -> service.reserveFirmwareUpgrade(playing)); + try (var unrelatedUpgrade = service.reserveFirmwareUpgrade(idle)) { + assertNotNull(unrelatedUpgrade); + } throw new IllegalStateException("native playback failed"); } }; ReflectionTestUtils.setField(service, "audioJNIBridge", bridge); assertThrows(IllegalStateException.class, () -> service.playAudioDataBatchV1( List.of(output("Sono-A", "OPENDAQ", 4001, new float[]{0F})), "NORMAL")); - assertDoesNotThrow(() -> service.assertFirmwareUpgradeIdle(playing)); + try (var upgrade = service.reserveFirmwareUpgrade(playing)) { + assertThrows(CryBusinessException.class, () -> service.playAudioDataBatchV1( + List.of(output("Sono-A", "OPENDAQ", 4001, new float[]{0F})), "NORMAL")); + } } @Test @@ -44,9 +49,12 @@ void firmwareUpgradeRejectsReservedCaptureInputsUntilTheyAreReleased() { Device device = device("Sono-A"); device.setProtocol("OPENDAQ"); try (var reservation = service.reserveExclusiveInputs(Map.of(device, List.of(input("Sono-A", "OPENDAQ", 1001, 1L))))) { - assertThrows(CryBusinessException.class, () -> service.assertFirmwareUpgradeIdle(device)); + assertThrows(CryBusinessException.class, () -> service.reserveFirmwareUpgrade(device)); + } + try (var upgrade = service.reserveFirmwareUpgrade(device)) { + assertThrows(CryBusinessException.class, () -> + service.reserveExclusiveInputs(Map.of(device, List.of(input("Sono-A", "OPENDAQ", 1001, 1L))))); } - assertDoesNotThrow(() -> service.assertFirmwareUpgradeIdle(device)); } @org.junit.jupiter.params.ParameterizedTest diff --git a/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/playback/PlaybackStreamSessionManagerTest.java b/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/playback/PlaybackStreamSessionManagerTest.java index 5bae5389..16a49eb9 100644 --- a/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/playback/PlaybackStreamSessionManagerTest.java +++ b/apps/backend/crydaq-service/src/test/java/com/opentest/service/jni/playback/PlaybackStreamSessionManagerTest.java @@ -4,8 +4,10 @@ import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.opentest.common.exception.CryBusinessException; +import com.opentest.common.exception.ErrorCode; import com.opentest.common.exception.JniBusinessException; import com.opentest.core.jni.AudioJNIBridge; +import com.opentest.service.jni.FirmwareUpgradeAccess; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LogEvent; @@ -41,6 +43,24 @@ class PlaybackStreamSessionManagerTest { when(bridge.getPlaybackStreamStatusV1(anyString(), anyString())).thenReturn(status("RUNNING", 0)); } + @Test + void firmwareReservationAndStreamAdmissionExcludeEachOtherUntilNativeStop() { + var access = new FirmwareUpgradeAccess(); + var guarded = new PlaybackStreamSessionManager(() -> bridge, access); + try (var upgrade = access.reserveUpgrade("device")) { + assertEquals(ErrorCode.JNI_DEVICE_BUSY.getErrcode(), assertThrows(CryBusinessException.class, + () -> guarded.start("OPENDAQ", generator(4001), new float[0][])).getErrcode()); + verify(bridge, never()).startPlaybackStreamBatchV1(anyString(), anyString(), any()); + } + guarded.start("OPENDAQ", generator(4001), new float[0][]); + assertEquals(ErrorCode.JNI_DEVICE_BUSY.getErrcode(), assertThrows(CryBusinessException.class, + () -> access.reserveUpgrade("device")).getErrcode()); + guarded.stop(addresses(4001)); + try (var upgrade = access.reserveUpgrade("device")) { + assertNotNull(upgrade); + } + } + @Test void failedStartReadsSameKeySynchronouslyBeforeCleanupAndKeepsOriginalCode() { Thread caller = Thread.currentThread(); diff --git a/apps/frontend/src/locales/en.ts b/apps/frontend/src/locales/en.ts index 13d1f024..362b88d5 100644 --- a/apps/frontend/src/locales/en.ts +++ b/apps/frontend/src/locales/en.ts @@ -29,7 +29,7 @@ export default { totals: 'Overall results', quantity: 'Quantity', value: 'Value', - surfaceArea: 'Measurement surface area' + surfaceArea: 'Measurement surface area', }, reportManager: { fileBusy: 'Cannot save “{file}”: the file is in use. Close it and retry, or save with another name.', @@ -37,8 +37,7 @@ export default { diskFull: 'Cannot save “{file}”: there is not enough disk space.', fileSaveFailed: 'Cannot save “{file}”: {reason}', measuringData: 'Measuring Data', - captureWindowTooSmall: - 'The chart cannot fit in the visible report area. Enlarge the window and try exporting again.', + captureWindowTooSmall: 'The chart cannot fit in the visible report area. Enlarge the window and try exporting again.', testTime: 'Test Time', unnamed: 'Unnamed', loadingRecord: 'Loading test record', @@ -63,8 +62,7 @@ export default { configureData: 'Configure data', currentRecord: 'Current test record', applyToRecords: 'Apply to records', - batchConfigHint: - 'Apply overwrites the selected records’ configuration and order. Targets continue to follow this record; deselect them to edit independently.', + batchConfigHint: 'Apply overwrites the selected records’ configuration and order. Targets continue to follow this record; deselect them to edit independently.', reorderData: 'Drag to reorder (Alt + Arrow Up/Down)', microphone: 'Microphone', soundLevelMeter: 'Sound level meter', @@ -135,8 +133,7 @@ export default { framework: { pluginStartupWaiting: 'Preparing plugins. Your workspace will open when they are ready.', pluginStartupFailed: 'Plugins could not start. The workspace has not been opened.', - pluginStartupRecovery: - 'Check Plugin Management for details. After resolving the issue, restart the backend and desktop app, then reload this page.', + pluginStartupRecovery: 'Check Plugin Management for details. After resolving the issue, restart the backend and desktop app, then reload this page.', reloadPage: 'Reload page', projectStartupFailed: 'The project could not be opened or created. Check the service status and try again.', retryProjectStartup: 'Try again', @@ -296,21 +293,21 @@ export default { automatic: { count: '{count} diagnostic files attached.', partial: 'Some logs could not be collected; available materials can still be submitted.', - title: 'Automatic attachments', - refresh: 'Refresh logs and database', - AUTO_LOGS: 'Today’s logs', - AUTO_DATABASE: 'Database snapshot', - collecting: 'Collecting…', - failed: 'Collection failed', - removed: 'Removed', - openDirectory: 'Open source directory', - removeFailed: 'Could not remove the temporary attachment. Please retry.', - openFailed: 'Could not open the source directory.', - errors: { - UNKNOWN_DATE: 'A log date could not be recognized.', - LOG_READ_FAILED: 'A log could not be read.', - NO_LOGS: 'No logs were found for today.', - COLLECTION_UNAVAILABLE: 'Automatic collection is unavailable in this environment.' + "title": "Automatic attachments", + "refresh": "Refresh logs and database", + "AUTO_LOGS": "Today’s logs", + "AUTO_DATABASE": "Database snapshot", + "collecting": "Collecting…", + "failed": "Collection failed", + "removed": "Removed", + "openDirectory": "Open source directory", + "removeFailed": "Could not remove the temporary attachment. Please retry.", + "openFailed": "Could not open the source directory.", + "errors": { + "UNKNOWN_DATE": "A log date could not be recognized.", + "LOG_READ_FAILED": "A log could not be read.", + "NO_LOGS": "No logs were found for today.", + "COLLECTION_UNAVAILABLE": "Automatic collection is unavailable in this environment." } }, title: 'Feedback Form', @@ -337,12 +334,10 @@ export default { submitFailed: 'Submission failed. Please retry.', retryPolicy: 'Retry attachment rules', policyFailed: 'Could not load attachment rules. Please retry.', - cancelUncertain: - 'Local submission stopped and window closed. Cloud status is unknown; the feedback may already have been accepted.', + cancelUncertain: 'Local submission stopped and window closed. Cloud status is unknown; the feedback may already have been accepted.', cancelAlreadyAccepted: 'Feedback was already accepted and will continue to be delivered.', continueUpload: 'Continue upload', - cancelConfirm: - 'Stop this local submission and close the window? Feedback already accepted by the cloud will still be processed.', + cancelConfirm: 'Stop this local submission and close the window? Feedback already accepted by the cloud will still be processed.', feedbackAccepted: 'Feedback accepted', feedbackSuccess: 'Feedback submitted successfully' }, @@ -445,9 +440,10 @@ export default { close: 'Close Client', zoomIn: 'Zoom In', zoomOut: 'Zoom Out', - zoomReset: 'Reset Zoom (100%)', - settings: 'System Settings' - }, + zoomReset: 'Reset Zoom (100%)' + , +settings: 'System Settings', +}, edit: { copy: 'Copy', paste: 'Paste', @@ -456,17 +452,17 @@ export default { undo: 'Undo', redo: 'Redo', pastePlainText: 'Paste as Plain Text' - }, - native: { + } + , +native: { quit: 'Quit (reserved)', hide: 'Hide', hideOthers: 'Hide Others', minimize: 'Minimize' - } - } + }, +} }, - partialSaveFailed: - 'Some settings may already have been saved. Remaining changes are kept in this dialog. Please retry.', + partialSaveFailed: 'Some settings may already have been saved. Remaining changes are kept in this dialog. Please retry.', title: 'System Settings', workingDirectory: 'System Working Directory', longRecordingWarningTime: 'Long Recording Warning Time (min)', @@ -1519,8 +1515,7 @@ export default { newProject: 'New Project', deleteSelected: 'Delete selected ({count})', deleteBatchConfirm: 'Delete these {count} projects? This action cannot be undone.', - deleteCurrentWarning: - 'This includes the current project. Its running tasks will be stopped, then another project will be opened or a default project created.', + deleteCurrentWarning: 'This includes the current project. Its running tasks will be stopped, then another project will be opened or a default project created.', deletingProjects: 'Deleting projects…', deleteResultUnknown: 'The deletion result is not yet confirmed. Check the result before submitting again.', checkDeleteResult: 'Check result', @@ -1806,8 +1801,7 @@ export default { noChannels: 'No channels', vp: 'Vp', customUnit: 'Custom unit', - customNotice: - 'The formula uses raw FS samples. The custom symbol labels results without calibration. Range limits do not clip samples.', + customNotice: 'The formula uses raw FS samples. The custom symbol labels results without calibration. Range limits do not clip samples.', minCustom: 'Minimum ({unit}, optional)', maxCustom: 'Maximum ({unit}, optional)', vpPlaceholder: 'Enter a positive Vp explicitly', @@ -1817,10 +1811,8 @@ export default { minFs: 'Minimum (FS, optional)', maxFs: 'Maximum (FS, optional)', fsNotice: 'The formula uses raw FS samples and produces FS samples. Range limits do not clip samples.', - legacyNotice: - 'This Math uses legacy physical samples. Explicit FS migration is required before execution. Saving edits keeps its legacy meaning.', - migrationWarning: - 'The formula inputs change from physical values to raw FS samples. Check the formula before saving the migration. Existing results keep their original values, units and calibration. Old calibration and range limits are cleared; enter the required parameters and any new limits.', + legacyNotice: 'This Math uses legacy physical samples. Explicit FS migration is required before execution. Saving edits keeps its legacy meaning.', + migrationWarning: 'The formula inputs change from physical values to raw FS samples. Check the formula before saving the migration. Existing results keep their original values, units and calibration. Old calibration and range limits are cleared; enter the required parameters and any new limits.', startMigration: 'Prepare FS migration', formulaReviewed: 'I reviewed the formula for raw FS inputs and want to migrate this Math.', unsupportedNotice: 'This Math sample format is unavailable in this version.', @@ -3302,8 +3294,7 @@ export default { fileOverwriteOptions: 'Overwrite', mergeChannels: 'Merge channels from the same result set into one file', wavBitDepth: 'WAV Bit Depth', - wavFloatingPointHint: - 'Floating-point recordings export as 64-bit float to preserve their values. A merged WAV containing them also uses 64-bit float.', + wavFloatingPointHint: 'Floating-point recordings export as 64-bit float to preserve their values. A merged WAV containing them also uses 64-bit float.', encodingMode: 'Encoding', fpcm64: 'FPCM (64-bit floating-point lossless)', float64Le: '64-bit floating-point (little-endian)', @@ -3767,21 +3758,15 @@ export default { dashboard: { needChannelData: 'Please configure channel information first', needAcquiredBackground: 'Please acquire background noise first' - }, - precision: { - overall: 'Overall validation', - zeroEnergy: 'No retained energy after exclusion', - precheckHelp325: - 'In each frequency band, at every microphone position, the sound pressure level measured with the test object operational shall exceed the background-noise sound pressure level by at least 6 dB. For one-third-octave bands with center frequencies from 250 Hz to 4000 Hz, the required difference is at least 10 dB.', - precheckHelp285: - 'After spatial energy averaging of the A-weighted levels at the current measurement points, the source-on average level must exceed the background average level by more than 3 dB. Formal measurement starts when the precheck criteria are met; otherwise, the precheck continues waiting.', - precheckHelp6882: - 'Only participating one-third-octave bands within the selected range are checked. For each band, spatially energy-average the source-on levels (including background) and background levels over the participating points separately, then take their difference. Ordinary measurement checks all participating points; each batch and current-batch retest checks only its own points with a fresh precheck. Nominal center frequencies from 250 to 5000 Hz inclusive require at least 10 dB; other participating bands require at least 6 dB. Formal capture starts when every band meets its threshold; otherwise checking continues. Readiness to capture does not establish full compliance with the standard.', + } + , +precision: { + overall: 'Overall validation', zeroEnergy: 'No retained energy after exclusion', + precheckHelp325: 'In each frequency band, at every microphone position, the sound pressure level measured with the test object operational shall exceed the background-noise sound pressure level by at least 6 dB. For one-third-octave bands with center frequencies from 250 Hz to 4000 Hz, the required difference is at least 10 dB.', + precheckHelp285: 'After spatial energy averaging of the A-weighted levels at the current measurement points, the source-on average level must exceed the background average level by more than 3 dB. Formal measurement starts when the precheck criteria are met; otherwise, the precheck continues waiting.', + precheckHelp6882: 'Only participating one-third-octave bands within the selected range are checked. For each band, spatially energy-average the source-on levels (including background) and background levels over the participating points separately, then take their difference. Ordinary measurement checks all participating points; each batch and current-batch retest checks only its own points with a fresh precheck. Nominal center frequencies from 250 to 5000 Hz inclusive require at least 10 dB; other participating bands require at least 6 dB. Formal capture starts when every band meets its threshold; otherwise checking continues. Readiness to capture does not establish full compliance with the standard.', insufficientDifference: 'Background noise difference is insufficient; waiting for criteria to pass', - unavailable: 'Unavailable', - noSignal: 'No valid signal', - invalidRow: 'Invalid result data', - none: 'None', + unavailable: 'Unavailable', noSignal: 'No valid signal', invalidRow: 'Invalid result data', none: 'None', closedSurface: 'Parallelepiped (six measurement faces)', criteria: 'Background noise criteria', backgroundNoiseDifferenceCheckEnabled: 'Background noise difference precheck', @@ -3789,26 +3774,18 @@ export default { aWeightedResultValidationEnabled: 'A-weighted result validation', precheck: 'Checking background noise difference', precheckFailedPoints: 'Positions not meeting the background noise difference requirement: ', - precheckNotMet: - 'The background noise difference does not yet meet the precheck requirements. Checking continues.', + precheckNotMet: 'The background noise difference does not yet meet the precheck requirements. Checking continues.', precheckReasons: { - BACKGROUND_DIFFERENCE_INSUFFICIENT: - 'The source-on level does not sufficiently exceed the background level. Checking continues.', + BACKGROUND_DIFFERENCE_INSUFFICIENT: 'The source-on level does not sufficiently exceed the background level. Checking continues.', BACKGROUND_HIGH: 'Background noise is too high to pass the precheck. Checking continues.', BACKGROUND_UNSTABLE: 'Background noise is unstable. Checking continues.', BORDERLINE: 'The level difference is at the decision boundary. Checking continues.', NO_SIGNAL: 'No valid signal is available for the precheck. Checking continues.' }, - point: 'Point', - result: 'Result', - excluded: 'Excluded bands', - fullBand: 'Full-band LwA', - adjusted: 'Adjusted LwA', - delta: 'Delta' - }, - pointMap: { - scanningPathHint: - 'Default points represent positions on the scanning paths. During measurement, move the microphone along the corresponding circular path or rotate the sound source.', + point: 'Point', result: 'Result', excluded: 'Excluded bands', fullBand: 'Full-band LwA', adjusted: 'Adjusted LwA', delta: 'Delta' + }, +pointMap: { + scanningPathHint: 'Default points represent positions on the scanning paths. During measurement, move the microphone along the corresponding circular path or rotate the sound source.', pointCount: '{count} points', point: 'Point', coordinates: 'Coordinates (m)', @@ -3821,16 +3798,13 @@ export default { views: { top: 'Top', front: 'Front' }, validation: { sourceType: 'The sound source type does not match the current algorithm or measurement surface', - cylinderRadius: - 'The length-direction radius is {radiusX} m and the width-direction radius is {radiusY} m. They must match. Adjust the reference dimensions or measurement distance.', + cylinderRadius: 'The length-direction radius is {radiusX} m and the width-direction radius is {radiusY} m. They must match. Adjust the reference dimensions or measurement distance.', coordinate: 'Enter the {axis} coordinate for point {position}', - referenceFit: - 'The reference body is {referenceHeight} m high and the measurement surface is {surfaceHeight} m high. Increase the measurement distance to at least {minimumDistance} m or reduce the reference body height.', - pointCount: - 'More than {max} points would be generated. Increase the measurement distance or reduce the reference body dimensions.' + referenceFit: 'The reference body is {referenceHeight} m high and the measurement surface is {surfaceHeight} m high. Increase the measurement distance to at least {minimumDistance} m or reduce the reference body height.', + pointCount: 'More than {max} points would be generated. Increase the measurement distance or reduce the reference body dimensions.' } - } - }, + }, +}, rt60: { setting: { dataAcquisition: 'Data Acquisition', @@ -3844,8 +3818,9 @@ export default { splAveragingTime: 'SPL Averaging Time', roomVolume: 'Room Volume', roomSurface: 'Room Surface', - specimenSurface: 'Specimen Surface', - sourceOff: { + specimenSurface: 'Specimen Surface' + , +sourceOff: { timeoutHint: 'The source-off timeout starts when the source is ready to be turned off.', title: 'Advanced interrupted-noise settings', referenceHoldSeconds: 'Reference hold time', @@ -3859,14 +3834,12 @@ export default { automatic: 'Automatic', custom: 'Custom', unrecorded: 'Source-off detection settings were not recorded', - lookbackHint: - 'Automatic lookback follows SPL averaging time and confirmation frames. Custom lookback must be at least SPL averaging time × (confirmation frames + 1). The timeout starts when the source may be switched off.', - invalid: - 'Enter valid source-off settings: positive times and thresholds, a positive integer frame count, and a band percentage greater than 0% and at most 100%.', + lookbackHint: 'Automatic lookback follows SPL averaging time and confirmation frames. Custom lookback must be at least SPL averaging time × (confirmation frames + 1). The timeout starts when the source may be switched off.', + invalid: 'Enter valid source-off settings: positive times and thresholds, a positive integer frame count, and a band percentage greater than 0% and at most 100%.', dropOrder: 'The confirmation drop must be at least the candidate drop.', lookbackTooShort: 'Lookback must be positive and at least SPL averaging time × (confirmation frames + 1).' - } - }, + }, +}, dashboard: { invalidConfiguration: 'Please check the RT60 settings before starting the measurement.' }, @@ -3880,8 +3853,9 @@ export default { captureFailedWithReason: 'Background SPL capture failed: {reason}', connectionInterrupted: 'Background SPL capture connection was interrupted. Please try again.', stopFailed: 'Failed to stop background SPL capture. Please try again.' - }, - guidance: { + } + , +guidance: { IMPULSE_NOT_READY: 'Not ready. Waiting for impulse trigger conditions.', IMPULSE_WAITING: 'Ready. Generate an impulse.', IMPULSE_CAPTURING: 'Acquiring the impulse response. Please wait.', @@ -3901,7 +3875,7 @@ export default { INSUFFICIENT_DATA: 'Insufficient data', LOW_SNR: 'Insufficient signal-to-noise ratio', REQUIRED_RESULT_MISSING: 'Required result unavailable', - UNKNOWN: 'Specific reason unavailable' + UNKNOWN: 'Specific reason unavailable', }, WAITING_FOR_SOURCE: 'Turn on or maintain the source and wait until it is stable.', READY_FOR_SOURCE_OFF: 'You can switch off the source.', @@ -3919,9 +3893,9 @@ export default { insufficientData: 'insufficient data', lowSnr: 'insufficient signal-to-noise ratio', fitFailed: 'fitting failed', - sourceOffTimeout: 'source-off detection timed out' - } - }, + sourceOffTimeout: 'source-off detection timed out', + }, +}, octave: { setting: { inputChannels: 'Input Channels', @@ -4530,8 +4504,7 @@ export default { bind: 'Bind', unbind: 'Unbind', unbindConfirm: 'Are you sure you want to unbind this authorization code?', - authorizationChangedRefreshFailed: - 'The authorization change completed, but assets or permissions could not be refreshed. Refresh the user center before making another change.', + authorizationChangedRefreshFailed: 'The authorization change completed, but assets or permissions could not be refreshed. Refresh the user center before making another change.', bindSuccess: 'Bind success', unbindSuccess: 'Unbind success', bindFailed: 'Bind failed', diff --git a/apps/frontend/src/locales/zh-CN.ts b/apps/frontend/src/locales/zh-CN.ts index b5799617..b9e34cb7 100644 --- a/apps/frontend/src/locales/zh-CN.ts +++ b/apps/frontend/src/locales/zh-CN.ts @@ -29,7 +29,7 @@ export default { totals: '总体结果', quantity: '物理量', value: '数值', - surfaceArea: '测量面面积' + surfaceArea: '测量面面积', }, reportManager: { fileBusy: '无法保存“{file}”:文件正在使用中。请关闭后重试,或另存为其他名称。', @@ -288,21 +288,21 @@ export default { automatic: { count: '已附加 {count} 个诊断文件。', partial: '部分日志无法收集;仍可提交可用的资料。', - title: '自动附件', - refresh: '刷新日志和数据库', - AUTO_LOGS: '今日日志', - AUTO_DATABASE: '数据库快照', - collecting: '正在收集……', - failed: '收集失败', - removed: '已移除', - openDirectory: '打开源目录', - removeFailed: '无法移除临时附件,请重试。', - openFailed: '无法打开源目录。', - errors: { - UNKNOWN_DATE: '无法识别日志日期。', - LOG_READ_FAILED: '无法读取日志。', - NO_LOGS: '未找到今日日志。', - COLLECTION_UNAVAILABLE: '当前环境不支持自动收集。' + "title": '自动附件', + "refresh": '刷新日志和数据库', + "AUTO_LOGS": '今日日志', + "AUTO_DATABASE": '数据库快照', + "collecting": '正在收集……', + "failed": '收集失败', + "removed": '已移除', + "openDirectory": '打开源目录', + "removeFailed": '无法移除临时附件,请重试。', + "openFailed": '无法打开源目录。', + "errors": { + "UNKNOWN_DATE": '无法识别日志日期。', + "LOG_READ_FAILED": '无法读取日志。', + "NO_LOGS": '未找到今日日志。', + "COLLECTION_UNAVAILABLE": '当前环境不支持自动收集。' } }, title: '提交表单', @@ -350,18 +350,18 @@ export default { filesUploading: '文件正在上传: {fileNames}', filesFailed: '文件上传失败: {fileNames}', allFilesSuccess: '所有文件上传成功 ({success}/{total})', - statusAbnormal: '文件异常,请检查' + statusAbnormal: '文件异常,请检查', }, message: { uploadSuccess: '{fileName} 文件上传成功', uploadFailed: '{fileName} 文件上传失败', uploadProgress: '上传进度: {percent}%', fileRemoved: '文件已移除: {fileName}', - fileChange: '文件选择已更改' + fileChange: '文件选择已更改', }, count: { multiple: '多个', - single: '1' + single: '1', }, uploadTrigger: { primaryText: '点击或拖动文件到此处上传', @@ -435,9 +435,10 @@ export default { close: '关闭客户端', zoomIn: '放大', zoomOut: '缩小', - zoomReset: '重置缩放 (100%)', - settings: '系统设置' - }, + zoomReset: '重置缩放 (100%)' + , +settings: '系统设置', +}, edit: { copy: '复制', paste: '粘贴', @@ -446,14 +447,15 @@ export default { undo: '撤销', redo: '重做', pastePlainText: '粘贴为纯文本' - }, - native: { + } + , +native: { quit: '退出(保留)', hide: '隐藏', hideOthers: '隐藏其他', minimize: '最小化' - } - } + }, +} }, partialSaveFailed: '部分设置可能已保存,其余更改仍保留在此对话框中。请重试。', title: '系统设置', @@ -482,8 +484,8 @@ export default { sound: '声音', vibration: '振动', addRow: '添加行', - saveFailed: '保存 dBrA 设置失败' - } + saveFailed: '保存 dBrA 设置失败', + }, } }, logoUpload: { @@ -1054,8 +1056,7 @@ export default { }, limitEditor: { saveResetLimitBeforeUnitSwitch: '请先保存重置的限值,然后再切换单位。', - incompatibleLimitUnit: - '限值单位 {unit} 与此通道不兼容。请选择有效的单位并重置阈值;旧值无法复用。对于引用的限值,请先移除引用或更正其源通道。', + incompatibleLimitUnit: '限值单位 {unit} 与此通道不兼容。请选择有效的单位并重置阈值;旧值无法复用。对于引用的限值,请先移除引用或更正其源通道。', limitUnitOptionsUnavailable: '无法加载有效的限值单位。请重新打开设置并重试。', selectCompatibleLimitUnit: '选择有效的限值单位', resetLimitUnitAndThreshold: '重置单位和阈值', @@ -1759,9 +1760,10 @@ export default { D_WEIGHTING: 'D计权', Z_WEIGHTING: 'Z 计权(无)' } - }, - activationLoading: '正在打开工程……' - }, + } + , +activationLoading: '正在打开工程……', +}, math: { label: '计算', signal: { @@ -1795,8 +1797,7 @@ export default { maxFs: '最大值(FS,可选)', fsNotice: '公式使用原始 FS 样本,输出仍为 FS。上下限不会截断样本。', legacyNotice: '此 Math 使用旧物理量语义,执行前需要明确迁移到 FS。保存编辑仍保留旧语义。', - migrationWarning: - '公式输入将从物理量变为原始 FS 样本。请先核对公式,再保存迁移。已有结果的数值、单位和标定参数保持原样。旧标定参数和上下限将清空,请填写所需参数及可选的新范围。', + migrationWarning: '公式输入将从物理量变为原始 FS 样本。请先核对公式,再保存迁移。已有结果的数值、单位和标定参数保持原样。旧标定参数和上下限将清空,请填写所需参数及可选的新范围。', startMigration: '准备迁移到 FS', formulaReviewed: '我已按原始 FS 输入核对公式,并确认迁移此 Math。', unsupportedNotice: '当前版本不支持此 Math 样本格式。', @@ -2834,9 +2835,10 @@ export default { vibration: '振动', digital: '数字信号', charge: '电荷' - }, - requiredInput: '请为 {types} 通道选择 FRF 输入单位。' - }, + } + , +requiredInput: '请为 {types} 通道选择 FRF 输入单位。', +}, xUnit: 'X', yUnit: 'Y', zUnit: 'Z', @@ -2959,16 +2961,18 @@ export default { }, EMPTY: '空白图', SINGLE_VALUE: '单值', - MULTIPLE_VALUE: '多值', - POINT_MAP_3D: '3D 点位图' - }, + MULTIPLE_VALUE: '多值' + , +POINT_MAP_3D: '3D 点位图', +}, test: { type: { TIME_HISTORY_CURVE: '时间历程曲线', SINGLE_VALUE: '单值', - IMAGE: '布局图', - POINT_MAP_3D: '3D 点位图' - } + IMAGE: '布局图' + , +POINT_MAP_3D: '3D 点位图', +} }, calculateResults: { RMS_LEVEL: '频率响应', @@ -3283,8 +3287,7 @@ export default { fileOverwriteOptions: '覆盖', mergeChannels: '将同一结果集中的通道合并到一个文件中', wavBitDepth: 'WAV 位深', - wavFloatingPointHint: - '浮点录制波形使用 64 位浮点导出,以保留原始数值。合并文件包含此类波形时,整个 WAV 使用 64 位浮点。', + wavFloatingPointHint: '浮点录制波形使用 64 位浮点导出,以保留原始数值。合并文件包含此类波形时,整个 WAV 使用 64 位浮点。', encodingMode: '编码', fpcm64: 'FPCM(64位浮点无损)', float64Le: '64位浮点(小端序)', @@ -3747,8 +3750,9 @@ export default { dashboard: { needChannelData: '请先配置通道信息', needAcquiredBackground: '请先采集背景噪声' - }, - precision: { + } + , +precision: { overall: '整体验证', zeroEnergy: '排除后无保留能量', precheckHelp325: @@ -3775,22 +3779,22 @@ export default { BACKGROUND_HIGH: '背景噪声过高,无法通过预检,继续检查中。', BACKGROUND_UNSTABLE: '背景噪声不稳定,继续检查中。', BORDERLINE: '声级差处于判定边界,继续检查中。', - NO_SIGNAL: '无可用于预检的有效信号,继续检查中。' + NO_SIGNAL: '无可用于预检的有效信号,继续检查中。', }, point: '测点', result: '结果', excluded: '已排除频带', fullBand: '全频带 LwA', adjusted: '调整后 LwA', - delta: '差值' + delta: '差值', }, - sourceType: { +sourceType: { label: '声源类型', General: '通用', BroadbandNoise: '宽带噪声源', - BroadbandOmnidirectional: '宽带全向声源' + BroadbandOmnidirectional: '宽带全向声源', }, - pointMap: { +pointMap: { scanningPathHint: '默认测点表示扫描路径上的位置。测量时,请沿相应的圆形路径移动传声器或旋转声源。', pointCount: '{count} 点', point: '测点', @@ -3803,7 +3807,7 @@ export default { initializationFailed: '3D 视图初始化失败,请检查图形加速。', views: { top: '顶视图', - front: '前视图' + front: '前视图', }, validation: { sourceType: '声源类型与当前算法或测量表面不匹配', @@ -3812,10 +3816,10 @@ export default { coordinate: '请输入测点 {position} 的 {axis} 坐标', referenceFit: '基准体高度为 {referenceHeight} m,测量表面高度为 {surfaceHeight} m。请将测量距离增加到至少 {minimumDistance} m,或减小基准体高度。', - pointCount: '生成的测点将超过 {max} 个。请增加测量距离或减小基准体尺寸。' - } - } - }, + pointCount: '生成的测点将超过 {max} 个。请增加测量距离或减小基准体尺寸。', + }, + }, +}, rt60: { setting: { dataAcquisition: '数据采集', @@ -3829,12 +3833,13 @@ export default { splAveragingTime: '声压级平均时间', roomVolume: '房间体积', roomSurface: '房间面积', - specimenSurface: '试件面积', - interruptedNoise: '中断噪声', - impulseResponse: '脉冲响应', - preTriggerSeconds: '预触发时长', - captureDurationSeconds: '触发后响应时长', - sourceOff: { + specimenSurface: '试件面积' + , +interruptedNoise: '中断噪声', +impulseResponse: '脉冲响应', +preTriggerSeconds: '预触发时长', +captureDurationSeconds: '触发后响应时长', +sourceOff: { timeoutHint: '等待关声超时从允许关闭声源后开始计时。', title: '中断噪声高级设置', referenceHoldSeconds: '参考保持时间', @@ -3852,20 +3857,21 @@ export default { '自动回溯跟随 SPL 平均时间和确认帧数。自定义回溯时间必须至少为 SPL 平均时间 × (确认帧数 + 1)。超时计时从可关闭声源时开始。', invalid: '请输入有效的声源关闭设置:时间和阈值为正数,帧数为正整数,频带百分比大于 0% 且不超过 100%。', dropOrder: '确认下降阈值必须不小于候选下降阈值。', - lookbackTooShort: '回溯时间必须为正数,且至少为 SPL 平均时间 × (确认帧数 + 1)。' - }, - impulseAdvanced: '高级脉冲检测', - rearmThresholdPa: '重新布防阈值', - rearmQuietSeconds: '静默时长', - impulseHint: - '无需单独采集背景噪声。点击开始后将自动检测脉冲。响应窗口应覆盖完整衰减过程及稳定的背景尾段,与测量停止时间无关。重新布防阈值必须低于触发阈值。测量期间设置将被锁定。' - }, + lookbackTooShort: '回溯时间必须为正数,且至少为 SPL 平均时间 × (确认帧数 + 1)。', + }, +impulseAdvanced: '高级脉冲检测', +rearmThresholdPa: '重新布防阈值', +rearmQuietSeconds: '静默时长', +impulseHint: + '无需单独采集背景噪声。点击开始后将自动检测脉冲。响应窗口应覆盖完整衰减过程及稳定的背景尾段,与测量停止时间无关。重新布防阈值必须低于触发阈值。测量期间设置将被锁定。', +}, dashboard: { - invalidConfiguration: '请在开始测量前检查RT60设置。', - target: '目标', - selectBackgroundForTarget: '请先在数据选择器中选择“{chartName}”,以加载背景数据并显示目标声压级。', - targetUnavailable: '缺少完整的背景倍频程数据或评估设置。目标不可用;其他结果仍可查看。' - }, + invalidConfiguration: '请在开始测量前检查RT60设置。' + , +target: '目标', +selectBackgroundForTarget: '请先在数据选择器中选择“{chartName}”,以加载背景数据并显示目标声压级。', +targetUnavailable: '缺少完整的背景倍频程数据或评估设置。目标不可用;其他结果仍可查看。', +}, background: { setReferenceSpl: '设置参考声压级', stop: '停止背景噪声', @@ -3875,11 +3881,13 @@ export default { captureFailed: '背景声压级采集失败,请重试。', captureFailedWithReason: '背景声压级采集失败:{reason}', connectionInterrupted: '背景声压级采集连接中断,请重试。', - stopFailed: '停止背景声压级采集失败,请重试。', - preparing: '正在准备……', - averagesStopUnsupported: '背景声压级采集不支持按平均次数停止。请先将停止方式切换为手动、时间或触发。' - }, - guidance: { + stopFailed: '停止背景声压级采集失败,请重试。' + , +preparing: '正在准备……', +averagesStopUnsupported: '背景声压级采集不支持按平均次数停止。请先将停止方式切换为手动、时间或触发。', +} + , +guidance: { IMPULSE_NOT_READY: '尚未就绪,等待脉冲触发条件满足。', IMPULSE_WAITING: '已就绪,请产生脉冲。', IMPULSE_CAPTURING: '正在采集脉冲响应,请等待。', @@ -3899,7 +3907,7 @@ export default { INSUFFICIENT_DATA: '数据不足', LOW_SNR: '信噪比不足', REQUIRED_RESULT_MISSING: '缺少所选结果', - UNKNOWN: '未提供具体原因' + UNKNOWN: '未提供具体原因', }, WAITING_FOR_SOURCE: '请开启或保持声源,并等待其稳定。', READY_FOR_SOURCE_OFF: '可以关闭声源。', @@ -3917,9 +3925,9 @@ export default { insufficientData: '数据不足', lowSnr: '信噪比不足', fitFailed: '拟合失败', - sourceOffTimeout: '声源关闭检测超时' - } - }, + sourceOffTimeout: '声源关闭检测超时', + }, +}, octave: { setting: { inputChannels: '输入通道', @@ -4523,8 +4531,7 @@ export default { bind: '绑定', unbind: '解绑', unbindConfirm: '您确定要解绑此授权码吗?', - authorizationChangedRefreshFailed: - '授权变更已完成,但资产或权限刷新失败。请先重新打开用户中心刷新状态,再进行其他变更。', + authorizationChangedRefreshFailed: '授权变更已完成,但资产或权限刷新失败。请先重新打开用户中心刷新状态,再进行其他变更。', bindSuccess: '绑定成功', unbindSuccess: '解绑成功', bindFailed: '绑定失败', @@ -5874,11 +5881,12 @@ export default { calibrationFreq2Hz: '校准频率 2', calibrationFreq3Hz: '校准频率 3', calibrationFreq4Hz: '校准频率 4', - calibrationNote: '注意:请确保校准频率之间的差异大于100Hz', - correctionVariables: '校正变量', - correctionVariablesHint: '所选变量将根据产品归属及后续左右声道检测结果进行校正。', - correctionVariablePlaceholder: '选择变量' - }, + calibrationNote: '注意:请确保校准频率之间的差异大于100Hz' + , +correctionVariables: '校正变量', +correctionVariablesHint: '所选变量将根据产品归属及后续左右声道检测结果进行校正。', +correctionVariablePlaceholder: '选择变量', +}, options: { bluetoothHeadsetAudioDetection: '蓝牙耳机音频检测', leftOddRightEven: '左通道奇数,右通道偶数', @@ -5895,11 +5903,12 @@ export default { singleDetectionLoopsInvalid: '单独检测循环必须是大于 0 的整数', maxDetectionsInvalid: '最大检测次数必须是大于 0 的整数', calibrationFreqRequired: '所有校准频率必须是大于 0 的整数', - calibrationFreqMinDistanceInvalid: '每个校准频率之间的差异必须大于 100Hz', - duplicateCorrectionVariable: '校正变量不能重复选择', - invalidCorrectionVariable: '校正变量引用无效', - correctionVariablesLoadFailed: '无法加载校正变量,请重试。' - }, + calibrationFreqMinDistanceInvalid: '每个校准频率之间的差异必须大于 100Hz' + , +duplicateCorrectionVariable: '校正变量不能重复选择', +invalidCorrectionVariable: '校正变量引用无效', +correctionVariablesLoadFailed: '无法加载校正变量,请重试。', +}, display: { detectionMethod: '检测方法', minDetectionThreshold: '检测最小阈值', @@ -5909,12 +5918,13 @@ export default { hz: 'Hz', db: 'dB', dbfs: 'dBFS' - }, - actions: { - addCorrectionVariable: '添加', - removeCorrectionVariable: '删除' } - }, + , +actions: { + addCorrectionVariable: '添加', + removeCorrectionVariable: '删除', + }, +}, compressFileCmp: { nodeName: '压缩文件', title: '压缩文件设置', @@ -6078,10 +6088,10 @@ export default { basicParsing: '基础解析', selectOperation: '选择操作', dataValidation: '数据验证', - input: '输入', - output: '输出', - previewLoadFailed: '通道配置预览加载失败,已保留节点保存的配置', - previewChangeNotSaved: '通道配置预览失败,本次修改未保存', + input: '输入', + output: '输出', + previewLoadFailed: '通道配置预览加载失败,已保留节点保存的配置', + previewChangeNotSaved: '通道配置预览失败,本次修改未保存', bindVariable: '绑定变量', bindVariableChannel: '绑定变量通道', bindScope: '绑定范围', @@ -7276,7 +7286,7 @@ export default { window: { pin: '置顶', unpin: '取消置顶', - controlFailed: '窗口操作失败,请重试。' + controlFailed: '窗口操作失败,请重试。', }, fallback: { loadFailedRetry: '加载失败,请关闭后重试' @@ -7550,10 +7560,11 @@ export default { channels: '通道', applySameSettingsToAllThreads: '所有线程使用相同设置', input: '输入', - output: '输出', - previewLoadFailed: '无法加载通道配置预览。已保存的节点设置仍可用。', - previewChangeNotSaved: '通道配置预览失败,此更改未保存。' - }, + output: '输出' + , +previewLoadFailed: '无法加载通道配置预览。已保存的节点设置仍可用。', +previewChangeNotSaved: '通道配置预览失败,此更改未保存。', +}, calibration: { settings: { title: '校准设置', @@ -7976,8 +7987,9 @@ export default { } } } - }, - clientErrors: { - featureUnavailable: '此功能当前不可用。' } +, +clientErrors: { + featureUnavailable: '此功能当前不可用。', + }, } diff --git a/apps/frontend/src/modules/device/hardware/__tests__/hardware-render.test.ts b/apps/frontend/src/modules/device/hardware/__tests__/hardware-render.test.ts index 04821036..0ff10717 100644 --- a/apps/frontend/src/modules/device/hardware/__tests__/hardware-render.test.ts +++ b/apps/frontend/src/modules/device/hardware/__tests__/hardware-render.test.ts @@ -1,9 +1,12 @@ import { flushPromises, mount } from '@vue/test-utils' import { createPinia } from 'pinia' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import ElementPlus from 'element-plus' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import ElementPlus, { ElMessageBox } from 'element-plus' import Hardware from '../index.vue' import DynamicTable from '@/components/ui/dc-dynamic-table' +import { useDeviceStore } from '@/stores/device' + +const requestMocks = vi.hoisted(() => ({ clear: vi.fn() })) vi.mock('@/utils/index', () => ({ NOOP: () => {}, @@ -18,7 +21,7 @@ vi.mock('@/utils/index', () => ({ vi.mock('@/services/api', () => ({ default: { base: () => ({ post: async () => ({ data: {} }) }), - baseSilent: () => ({ get: async () => ({ data: [] }) }) + baseSilent: () => ({ get: async () => ({ data: [] }), post: requestMocks.clear }) } })) vi.mock('../sync/sync-service', async () => { @@ -52,9 +55,17 @@ vi.mock('@/stores/device', async () => { }) describe('hardware table rendering', () => { - beforeEach(() => vi.clearAllMocks()) - it('retains device rows, protocol heading and offline structure after repeated refreshes', async () => { - const wrapper = mount(Hardware, { + beforeEach(() => { + vi.clearAllMocks() + requestMocks.clear.mockReset() + }) + afterEach(() => { + ElMessageBox.close() + vi.restoreAllMocks() + }) + + function mountHardware() { + return mount(Hardware, { props: { projectId: '42' }, global: { plugins: [createPinia(), ElementPlus], @@ -63,6 +74,10 @@ describe('hardware table rendering', () => { stubs: { SimpleCard: { template: '
' } } } }) + } + + it('retains device rows, protocol heading and offline structure after repeated refreshes', async () => { + const wrapper = mountHardware() await flushPromises() for (let index = 0; index < 3; index++) { expect(wrapper.get('.is-online').text()).toContain('Device A') @@ -75,4 +90,56 @@ describe('hardware table rendering', () => { } wrapper.unmount() }) + + it('refreshes devices and channels after a committed clear loses its response', async () => { + const wrapper = mountHardware() + await flushPromises() + const store = useDeviceStore() + store.deviceList.push({ ...store.deviceList[0], id: 'offline', deviceName: 'Offline device', connected: false }) + const refresh = vi.spyOn(store, 'refreshDeviceList') + requestMocks.clear.mockImplementation(async () => { + store.deviceList = store.deviceList.filter(device => device.id !== 'offline') + throw new Error('Connection closed before response') + }) + await flushPromises() + + await wrapper.get('button[title="device.clearOffline"]').trigger('click') + await flushPromises() + const confirm = document.querySelector('.el-message-box__btns .el-button--primary') + expect(confirm).not.toBeNull() + confirm?.click() + await flushPromises() + + expect(requestMocks.clear).toHaveBeenCalledWith('/v1/device/offline/clear', { + ids: ['offline'], + projectId: '42', + deleteVirtualChannel: false + }) + expect(refresh).toHaveBeenCalledTimes(1) + expect(wrapper.emitted('device-deleted')).toHaveLength(1) + expect(wrapper.get('button[title="device.clearOffline"]').attributes('disabled')).toBeDefined() + wrapper.unmount() + }) + + it('keeps devices and channels intact when clearing is cancelled before submission', async () => { + const wrapper = mountHardware() + await flushPromises() + const store = useDeviceStore() + store.deviceList.push({ ...store.deviceList[0], id: 'offline', deviceName: 'Offline device', connected: false }) + const refresh = vi.spyOn(store, 'refreshDeviceList') + await flushPromises() + + await wrapper.get('button[title="device.clearOffline"]').trigger('click') + await flushPromises() + const cancel = document.querySelector('.el-message-box__btns button:not(.el-button--primary)') + expect(cancel).not.toBeNull() + cancel?.click() + await flushPromises() + + expect(requestMocks.clear).not.toHaveBeenCalled() + expect(refresh).not.toHaveBeenCalled() + expect(wrapper.emitted('device-deleted')).toBeUndefined() + expect(store.deviceList.some(device => device.id === 'offline')).toBe(true) + wrapper.unmount() + }) }) diff --git a/apps/frontend/src/modules/device/hardware/__tests__/index.test.ts b/apps/frontend/src/modules/device/hardware/__tests__/index.test.ts index 4746ac16..89384f1c 100644 --- a/apps/frontend/src/modules/device/hardware/__tests__/index.test.ts +++ b/apps/frontend/src/modules/device/hardware/__tests__/index.test.ts @@ -61,7 +61,8 @@ vi.mock('@/modules/device/hardware/sync/sync-service', () => ({ ptpSyncService: syncServiceMocks })) -vi.mock('@/components/ui/base/icon-button.vue', () => ({ __esModule: true, +vi.mock('@/components/ui/base/icon-button.vue', () => ({ + __esModule: true, default: { name: 'DcIconButton', props: ['icon', 'tooltip'], @@ -69,14 +70,16 @@ vi.mock('@/components/ui/base/icon-button.vue', () => ({ __esModule: true, } })) -vi.mock('@/components/ui/base/svg-icon.vue', () => ({ __esModule: true, +vi.mock('@/components/ui/base/svg-icon.vue', () => ({ + __esModule: true, default: { name: 'DcSvgIcon', template: '' } })) -vi.mock('@/components/ui/base/simple-card.vue', () => ({ __esModule: true, +vi.mock('@/components/ui/base/simple-card.vue', () => ({ + __esModule: true, default: { name: 'SimpleCard', template: '
' @@ -100,6 +103,10 @@ vi.mock('lucide-vue-next', () => ({ RefreshCw: { name: 'RefreshCw', template: '' + }, + BrushCleaning: { + name: 'BrushCleaning', + template: '' } })) @@ -196,8 +203,7 @@ describe('DcDeviceHardware', () => { await flushPromises() apiMocks.basePost.mockClear() - const buttons = wrapper.findAll('.dc-icon-button-stub') - await buttons.at(-1).trigger('click') + await wrapper.get('[data-tooltip="device.refresh"]').trigger('click') await flushPromises() expect(apiMocks.basePost).toHaveBeenCalledWith('/v1/device/update/device/status', { @@ -244,8 +250,7 @@ describe('DcDeviceHardware', () => { data: [{ id: 101, deviceName: 'SonoDAQ-101' }] }) - const buttons = wrapper.findAll('.dc-icon-button-stub') - await buttons.at(-1).trigger('click') + await wrapper.get('[data-tooltip="device.refresh"]').trigger('click') await flushPromises() expect(utilsMocks.handleConfirmAction).toHaveBeenCalledTimes(1) @@ -263,9 +268,7 @@ describe('DcDeviceHardware', () => { } const wrapper = await mountHardware() - const buttons = wrapper.findAll('.dc-icon-button-stub') - - expect(buttons[1].attributes('data-icon')).toBe('success-icon') + expect(wrapper.get('[data-tooltip="device.synchronization"]').attributes('data-icon')).toBe('success-icon') wrapper.unmount() }) }) diff --git a/apps/frontend/src/modules/device/hardware/detail/information/upgrade.vue b/apps/frontend/src/modules/device/hardware/detail/information/upgrade.vue index 535e4676..cd68617a 100644 --- a/apps/frontend/src/modules/device/hardware/detail/information/upgrade.vue +++ b/apps/frontend/src/modules/device/hardware/detail/information/upgrade.vue @@ -49,7 +49,7 @@ :disabled="busy || !upgradeState.filePath" @click="upload" > - {{ $t('device.upgrade') }} + {{ $t('device.upload') }} device.id) const projectId = props.projectId const deleteVirtualChannel = ref(false) + let submitted = false clearingOffline.value = true try { await ElMessageBox.confirm( @@ -300,6 +301,7 @@ async function clearOfflineDevices() { translate('device.clearOffline'), { type: 'warning', confirmButtonText: translate('common.confirm'), cancelButtonText: translate('common.cancel') } ) + submitted = true const response = await api.baseSilent().post<{ data: { deletedIds: string[]; skippedIds: string[]; failedIds: string[] } }>('/v1/device/offline/clear', { ids, projectId, deleteVirtualChannel: deleteVirtualChannel.value }) @@ -312,10 +314,11 @@ async function clearOfflineDevices() { if (result.failedIds.length) ElMessage.warning(message) else ElMessage.success(message) if (result.deletedIds.length) emit('device-deleted') - await refreshDeviceList() } catch (error) { + if (submitted) emit('device-deleted') if (error !== 'cancel' && error !== 'close') ElMessage.error(translate('api.serviceException')) } finally { + if (submitted) await refreshDeviceList() clearingOffline.value = false } } diff --git a/docs/specs/hardware-device-actions.md b/docs/specs/hardware-device-actions.md index 21604fca..e3f05d02 100644 --- a/docs/specs/hardware-device-actions.md +++ b/docs/specs/hardware-device-actions.md @@ -65,7 +65,7 @@ The reference shows an Installing percentage and a demo completion state. The us 4. Present confirmation in the inline area shown in the video. After confirmation, prevent repeated submission, file replacement, and cancellation. Retain the power reminder. 5. **Keep the existing success criterion: a successful response from the device upgrade confirmation API resets state and reports success through the existing flow.** Do not add restart, reconnection, firmware reread, or target-version comparison as completion conditions, or change the device protocol as part of this interface adjustment. 6. Closing details within the current application session preserves active task state; reopening restores its display. Retain existing upload/API error handling and pending-package replacement rules. Retries require an explicit user action; do not automatically repeat upgrade confirmation. -7. Prevent starting firmware upgrade on a device that is acquiring or playing. Lock relevant upgrade actions during its upgrade flow. Closing details does not itself cancel the upgrade. +7. Prevent starting firmware upgrade on a device that is acquiring or playing. Hold a device reservation while forwarding upload and confirmation requests, excluding concurrent capture, finite playback, and streaming playback startup. Release it when the request completes or fails. Lock relevant upgrade actions during its upgrade flow. Closing details does not itself cancel the upgrade. ### First-round decisions diff --git a/docs/specs/hardware-device-actions.zh-CN.md b/docs/specs/hardware-device-actions.zh-CN.md index 34e38c2a..ecef77da 100644 --- a/docs/specs/hardware-device-actions.zh-CN.md +++ b/docs/specs/hardware-device-actions.zh-CN.md @@ -65,7 +65,7 @@ Status: implemented; verification recorded 4. 将确认操作放入视频所示的行内确认区。确认升级后禁止重复提交、替换文件和取消;保留供电提示。 5. **成功判据保持原逻辑:设备升级确认接口返回成功后,即按现有流程重置状态并提示成功。** 本次不增加等待重启、重连、读回版本或比对目标版本的成功条件,也不借此次界面调整改变设备端协议。 6. 当前运行会话内关闭详情不丢弃正在进行的任务状态,再次打开恢复展示。上传或接口失败沿用现有错误处理和待确认包替换规则,由用户明确重试,不自动重复确认升级。 -7. 设备正在采集或播放时禁止启动该设备的固件升级;设备进入升级流程后锁定相关升级操作。关闭详情本身不表示取消升级。 +7. 设备正在采集或播放时禁止启动该设备的固件升级。上传及确认请求转发期间,持有该设备的升级占用,与采集、有限播放和持续播放启动互斥;请求完成或失败后释放。设备进入升级流程后锁定相关升级操作。关闭详情本身不表示取消升级。 ### 第一轮确认记录 diff --git a/docs/verification/hardware-device-actions.md b/docs/verification/hardware-device-actions.md index 9afa0c94..f5cb2132 100644 --- a/docs/verification/hardware-device-actions.md +++ b/docs/verification/hardware-device-actions.md @@ -65,3 +65,16 @@ A second pass on the updated Windows client completed three device refreshes and The physical SonoDAQ validated the supplied `61.2 MB` package. Closing and reopening details restored inline confirmation. Cancelling the pending package reset the editor. This pass ended at cancellation. The earlier physical confirmation remains the upgrade completion evidence. All 22 relevant frontend tests passed again. Screenshots: `retest-protocol-hover.png`, `retest-offline-three-result.png`, `retest-firmware-confirm.png`, and `retest-firmware-cancelled.png`. The latest Protocol display uses the NI plugin installation state. Automated checks verify that an absent plugin has no row and a readable version is displayed. Windows testing with the installed NI plugin verified `--` when its driver query failed, alongside SonoDAQ SDK `1.4.0`. The popover closed on pointer exit. The updated frontend and backend builds passed, with 27 frontend tests and 30 backend tests passing. Screenshot: `retest-ni-version-placeholder.png`. + +## AI review follow-up verification + +Follow-up changes address the AI review of merged PR #63. The firmware proxy matches IPv4, IPv6, and scoped IPv6 addresses and forwards using the discovered driver's identity and address. A reservation excludes capture, finite playback, and streaming playback startup while upload or confirmation is forwarded, and releases on failure. Equivalent paths and confirmation action casing are normalized. Invalid JSON produces a parameter error, and cancellation retains its existing forwarding behavior. + +After an offline-clear request is submitted, a lost response still causes device and parent-channel refresh. Cancelling before submission sends no request and triggers no channel refresh. The inner action is labelled Upload. SDK version diagnostics omit local paths, and unrelated locale formatting has been removed. + +- All 99 targeted backend tests and incremental packaging pass. Controller coverage includes reservation, normalized routes, invalid parameters, and cancellation. Tests using the real service path cover driver identity, equivalent IP literals, mutual exclusion, and release. +- All 174 frontend tests pass across the hardware module, related upgrade state and translations, and CAN channel editor regressions. Clear-error and cancellation tests use actual Element Plus confirmation dialogs. Existing tests affected by the moved controls have been updated. +- SDK build, frontend production build, and targeted ESLint pass. +- Backend CI failures in the original PR match the plugin-runtime and `CommonProtoCompatibilityTest` failures in the [main CI](https://github.com/crysound/OpenTest/actions/runs/44218810513) for baseline `404f249c`. The same baseline also has the nine existing frontend test-typecheck errors. Full CI is not passing; targeted results do not imply that it passed. + +These automated results do not replace the physical-device observations above. Earlier hardware testing predates this review revision. Hardware acceptance of the new mutual-exclusion behavior remains pending. diff --git a/docs/verification/hardware-device-actions.zh-CN.md b/docs/verification/hardware-device-actions.zh-CN.md index 6d1c676f..8eb10b03 100644 --- a/docs/verification/hardware-device-actions.zh-CN.md +++ b/docs/verification/hardware-device-actions.zh-CN.md @@ -65,3 +65,16 @@ NI 版本成功展示仍需在 NI-DAQmx 可正常工作的环境验证。真机 物理 SonoDAQ 校验了指定的 `61.2 MB` 固件。关闭重开详情后恢复行内确认,取消待确认包后编辑区重置。本轮实测到取消为止,前一次真机确认结果仍作为升级完成证据。相关前端测试复跑 22 项通过。截图包括 `retest-protocol-hover.png`、`retest-offline-three-result.png`、`retest-firmware-confirm.png` 和 `retest-firmware-cancelled.png`。 Protocol 浮层按 NI 插件安装状态显示。自动化检查验证了未安装时隐藏该行,以及版本可读时显示实际版本。Windows 实测验证了 NI 插件已安装但驱动查询失败时显示 `--`,同时 SonoDAQ SDK 显示 `1.4.0`。鼠标移开后浮层关闭。更新后的前后端构建通过,前端 27 项和后端 30 项测试通过。截图为 `retest-ni-version-placeholder.png`。 + +## AI 审查修复验证 + +PR #63 合并后,补充修复其 AI 审查意见。固件代理按 IPv4、IPv6 和带接口范围的 IPv6 地址定位驱动,并沿用驱动身份和地址转发。上传及确认转发期间的设备占用与采集、有限播放和持续播放启动互斥,失败时释放。等价路径和确认动作大小写统一处理,错误 JSON 返回参数错误;取消请求保留既有转发逻辑。 + +离线清空请求提交后,即使响应丢失,也重新读取设备并通知上层刷新通道。确认前取消不会提交或触发通道刷新。上传按钮使用 Upload 文案,SDK 版本查询增加不包含本地路径的诊断日志。语言文件移除了与本功能无关的格式调整。 + +- 后端 99 项定向测试及增量打包通过。新增控制器测试覆盖升级占用、路径规范化、异常参数和取消放行;真实服务链路测试覆盖驱动身份、不同 IP 写法、占用互斥和释放。 +- 前端整个硬件模块、相关升级状态和文案,以及 CAN 通道编辑回归共 174 项通过。清空异常和取消回归使用实际 Element Plus 确认框;调整了受入口变化影响的旧测试。 +- SDK 构建、前端生产构建和改动文件 ESLint 通过。 +- 原 PR 的后端 CI 失败项与基线 `404f249c` 的 [main CI](https://github.com/crysound/OpenTest/actions/runs/44218810513) 一致,均位于插件运行时测试与 `CommonProtoCompatibilityTest`。前端测试类型检查的 9 处既有错误也出现在同一基线中。完整 CI 未通过,不能将定向检查通过解释为全量 CI 成功。 + +本节自动化验证不替代前文的真机记录。此前的物理设备实测早于本轮审查修复,新增占用互斥的真机验收仍待完成。