Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ _Avoid_:运行实例、单个仓库
**版本运行实例(Version Runtime Instance)**:由版本与 HTTP/gRPC 端口对共同标识的独立运行环境,拥有自己的业务数据、插件安装状态与运行配置,其启停不影响其他版本或端口对的运行实例。
_Avoid_:版本源码目录、共享运行状态的分支切换

## 硬件配置术语

**离线设备清空(Clear Offline Devices)**:对一组离线设备记录执行设备移除的操作,其删除含义与单条设备移除相同。
_Avoid_:仅隐藏列表、清理临时缓存

**设备 SDK/驱动版本(Device SDK/Driver Version)**:用于设备接入的 SDK 或驱动运行库的版本标识,与设备驱动插件包版本及设备固件版本分别表达。
_Avoid_:设备驱动插件包版本、设备固件版本

**设备固件版本(Device Firmware Version)**:设备自身运行的固件的版本标识。
_Avoid_:设备 SDK/驱动版本、设备驱动插件包版本

## 结果名称术语

**结果名称键(Result Name Key)**:所属业务为结果名称指定的稳定文案标识,同一标识可以对应不同语言的显示名称。
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package com.opentest.common.model.dto;

public record DeviceProtocolVersionDto(String name, String version, String status) { }
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.opentest.common.model.dto;

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.List;

public record OfflineDeviceClearDto(
@NotNull Long projectId,
@NotEmpty @Size(max = 100000) List<@NotNull Long> ids,
Boolean deleteVirtualChannel) { }
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.opentest.common.model.dto;

import java.util.List;

public record OfflineDeviceClearResult(List<String> deletedIds, List<String> skippedIds, List<String> failedIds) { }
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
/** Raw JNI declarations for audio devices, playback, capture, and calibration. */
@Service
public class AudioJNIBridge {
/** Queries the SDK version exported by the specified active plugin library. */
public native String getDeviceSdkVersion(String pluginLibraryPath);
/** Optional localized plugin error lookup; older native libraries retain the original error handling. */
public native String getPluginErrorMessage(String protocol, String deviceId, int errorCode, String language);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.nio.charset.StandardCharsets;

/**
* C++层HTTP接口调用控制层
Expand Down Expand Up @@ -63,6 +64,11 @@ public Object proxyRequest(
try {
// 获取实际请求路径
String path = request.getRequestURI().substring(request.getContextPath().length() + "/v1/cpp".length());
if (HttpMethod.POST.matches(request.getMethod()) && ("/api/system/upgrade/upload".equals(path)
Comment thread
KyleHuangFromHZ marked this conversation as resolved.
Resolved
|| ("/api/system/upgrade/action".equals(path) && body != null
&& "confirm".equals(JSONUtil.parseObj(new String(body, StandardCharsets.UTF_8)).getStr("action"))))) {
cppHttpProxyService.assertUpgradeIdle(serverIp);
Comment thread
KyleHuangFromHZ marked this conversation as resolved.
Resolved
}
String targetUrl = buildUrl(serverIp, path);
log.info("调用C++接口,URL: {}, Method: {}", targetUrl, request.getMethod());
// 构建 HTTP 请求对象
Expand All @@ -88,6 +94,8 @@ public Object proxyRequest(
response = httpRequest.execute();
}
return buildProxyResponse(response);
} catch (CryBusinessException e) {
throw e;
} catch (Exception e) {
log.error("调用C++接口失败", e);
throw new CryBusinessException(ErrorCode.FAILED, "调用C++接口失败");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.opentest.common.model.DeleteDto;
import com.opentest.common.model.dto.DeviceDto;
import com.opentest.common.model.dto.DeviceProtocolVersionDto;
import com.opentest.common.model.dto.OfflineDeviceClearDto;
import com.opentest.common.model.dto.OfflineDeviceClearResult;
import com.opentest.common.model.dto.ptp.PtpDeviceStatusDto;
import com.opentest.common.model.dto.ptp.PtpSyncConfigDto;
import com.opentest.common.model.dto.ptp.PtpSyncRequestDto;
import com.opentest.common.model.query.DeviceQuery;
import com.opentest.common.result.CommonResult;
import com.opentest.core.jni.model.SonoDAQBoardInfo;
import com.opentest.service.DeviceService;
import com.opentest.service.DeviceProtocolVersionService;
import com.opentest.service.jni.DeviceDiscoveryRefreshCoordinator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
Expand All @@ -34,6 +38,19 @@ public class DeviceController extends BaseController {
@Resource
private DeviceService deviceService;

@Resource
private DeviceProtocolVersionService protocolVersions;

@GetMapping("protocol/versions")
public CommonResult<List<DeviceProtocolVersionDto>> protocolVersions() {
return success(protocolVersions.versions());
}

@PostMapping("offline/clear")
public CommonResult<OfflineDeviceClearResult> clearOffline(@Validated @RequestBody OfflineDeviceClearDto dto) {
return success(deviceService.clearOfflineDevices(dto));
}

@Resource
private DeviceDiscoveryRefreshCoordinator deviceDiscoveryRefreshCoordinator;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,23 @@ public class CppHttpProxyService {
@Resource
private AudioJNIBridgeService audioJNIBridgeService;

public void assertUpgradeIdle(String serverIp) {
List<JNIDriver> drivers = audioJNIBridgeService.getDrivers(true);
if (drivers != null) {
for (JNIDriver driver : drivers) {
if (driver != null && OPENDAQ_PROTOCOL.equalsIgnoreCase(driver.getProtocol()) && serverIp.equals(driver.getIp())) {
Comment thread
KyleHuangFromHZ marked this conversation as resolved.
Resolved
Device device = new Device();
device.setProtocol(OPENDAQ_PROTOCOL);
device.setDeviceName(driver.getDevId());
Comment thread
KyleHuangFromHZ marked this conversation as resolved.
Resolved
device.setIpAddress(serverIp);
audioJNIBridgeService.assertFirmwareUpgradeIdle(device);
return;
}
}
}
throw new CryBusinessException(ErrorCode.JNI_DEVICE_NOT_FOUND);
}

public String buildTargetUrl(String serverIp, String path) {
if (StrUtil.isBlank(serverIp)) {
throw new CryBusinessException(ErrorCode.PARAMETER, "服务器IP不能为空");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.opentest.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opentest.common.model.dto.DeviceProtocolVersionDto;
import com.opentest.core.jni.AudioJNIBridge;
import com.opentest.service.deviceplugin.DevicePluginManagement;
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
public class DeviceProtocolVersionService {
private final DevicePluginManagement devices;
private final AudioJNIBridge bridge;
private final ObjectMapper json;

public DeviceProtocolVersionService(DevicePluginManagement devices, AudioJNIBridge bridge, ObjectMapper json) {
this.devices = devices;
this.bridge = bridge;
this.json = json;
}

public List<DeviceProtocolVersionDto> versions() {
JsonNode packages = devices.snapshot(false).path("packages");
return List.of(version(packages, "opentest.sonodaq.device", "SonoDAQ SDK", false),
version(packages, "opentest.nidaq.device", "NI-DAQmx", !System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows")));
}

private DeviceProtocolVersionDto version(JsonNode packages, String id, String name, boolean unsupported) {
JsonNode installed = null;
for (JsonNode item : packages) {
if (id.equals(item.path("packageId").asText()) && item.path("installed").asBoolean()) {
installed = item;
break;
}
}
if (installed == null) return new DeviceProtocolVersionDto(name, null, "notInstalled");
if (unsupported) return new DeviceProtocolVersionDto(name, null, "unsupported");
if (!"active".equals(installed.path("status").asText())) {
return new DeviceProtocolVersionDto(name, null, installed.path("enabled").asBoolean() ? "unavailable" : "disabled");
}
try {
Path activeLibrary = devices.activeLibrary(id);
if (activeLibrary == null) return new DeviceProtocolVersionDto(name, null, "unavailable");
JsonNode response = json.readTree(bridge.getDeviceSdkVersion(activeLibrary.toString()));
if (response != null && response.path("code").isIntegralNumber() && response.path("code").asInt() == 0
&& response.path("data").isTextual() && !response.path("data").asText().isBlank()) {
return new DeviceProtocolVersionDto(name, response.path("data").asText(), "ready");
}
} catch (Exception | LinkageError error) {
Comment thread
KyleHuangFromHZ marked this conversation as resolved.
Resolved
// A missing native entry or one unavailable SDK must not hide the other row.
}
return new DeviceProtocolVersionDto(name, null, "failed");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import com.opentest.common.enums.ChannelSourceEnum;
import com.opentest.common.enums.DeviceAddTypEnum;
import com.opentest.common.enums.DeviceStateEnum;
import com.opentest.common.model.dto.OfflineDeviceClearDto;
import com.opentest.common.model.dto.OfflineDeviceClearResult;
import com.opentest.common.enums.FieldColumnEnum;
import com.opentest.common.exception.CryBusinessException;
import com.opentest.common.exception.ErrorCode;
Expand Down Expand Up @@ -1073,6 +1075,39 @@ public Boolean deleteFromCurrentProject(DeleteDto dto) {
return deleted;
}

/** Each item shares individual Remove semantics and commits independently. */
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public OfflineDeviceClearResult clearOfflineDevices(OfflineDeviceClearDto request) {
if (request == null || request.projectId() == null || request.ids() == null || request.ids().isEmpty()) {
throw new CryBusinessException(ErrorCode.CHECK_PARAMETER_REQUIRED, "projectId/ids");
}
List<String> deleted = new ArrayList<>();
List<String> skipped = new ArrayList<>();
List<String> failed = new ArrayList<>();
for (Long id : request.ids().stream().distinct().toList()) {
try {
Boolean removed = executeInShortTransaction(() -> {
Device current = (Device) getById(id);
if (current == null || !Objects.equals(current.getActiveState(), DeviceStateEnum.OFFLINE.getActiveState())) {
return null;
}
DeleteDto dto = new DeleteDto();
dto.setId(id);
dto.setProjectId(request.projectId());
dto.setDeleteVirtualChannel(Boolean.TRUE.equals(request.deleteVirtualChannel()));
return deleteFromCurrentProject(dto);
});
if (removed == null) skipped.add(String.valueOf(id));
else if (Boolean.TRUE.equals(removed)) deleted.add(String.valueOf(id));
else failed.add(String.valueOf(id));
} catch (RuntimeException error) {
log.warn("Offline device removal failed, deviceId={}", id, error);
failed.add(String.valueOf(id));
}
}
return new OfflineDeviceClearResult(deleted, skipped, failed);
}

private void deleteDeviceAndPhysicalChannels(Device device) {
log.info("设备删除,设备名称:" + device.getDeviceName() + ",设备id:" + device.getId());
if (ObjectUtil.equal(device.getProtocol(), "OTHER")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,16 @@ public synchronized ObjectNode snapshot(boolean permitted) {
}
return result;
}

/** Resolve the admitted runtime content, never a pending replacement's candidate. */
public synchronized Path activeLibrary(String id) {
Installed installed = state.installed().get(id);
RuntimeView observed = runtime.get(id);
if (!started || closed || infrastructureError != null || installed == null || !installed.enabled()
|| !admitted.contains(id) || !Boolean.TRUE.equals(decisions.get(id))
|| observed == null || !"ready".equals(observed.state())) return null;
return packages.entry(installed.content());
}
private static ObjectNode receipt(Receipt value) {
ObjectNode result = DevicePluginJson.JSON.valueToTree(value);
if (value.packageId() == null) result.remove("packageId");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,31 @@ static String bluetoothInputName(String name) {
private final ConcurrentMap<Long, Object> activeGeneratorSessionLocks = new ConcurrentHashMap<>();
private final AtomicLong activeGeneratorSessionSequence = new AtomicLong();
private volatile PlaybackStreamSessionManager playbackStreams;
private final ConcurrentMap<String, Integer> 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);
}
}

private int withFinitePlaybackActivity(String protocol, String requestJson, Supplier<Integer> operation) {
JSONObject request = JSONUtil.parseObj(requestJson);
Set<String> 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);
});
}
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)); }
}
// 保存实际运行配置;独立于页面选择,供差异修改、补偿和暂停恢复使用。
private final ConcurrentMap<Long, Map<String, GeneratorConfigDto>> generatorRuntimeConfigs = new ConcurrentHashMap<>();
private final ConcurrentMap<Long, GeneratorConfigDto> generatorTargetConfigs = new ConcurrentHashMap<>();
Expand Down Expand Up @@ -2082,7 +2107,8 @@ public void playAudioData(Device device, List<ChannelDto> channelList, Map<Integ
String protocol = channelList.get(0).getProtocol();
FinitePlaybackBatchV1.Request request = FinitePlaybackBatchV1.build(protocol, "NORMAL", outputs, List.of());
requireSelectedBatch(protocol, request.json());
JNIUtils.checkJniReturn(audioJNIBridge.playAudioDataBatchV1(protocol, request.json(), request.data()), "仅播放");
JNIUtils.checkJniReturn(withFinitePlaybackActivity(protocol, request.json(),
() -> audioJNIBridge.playAudioDataBatchV1(protocol, request.json(), request.data())), "仅播放");
}

/**
Expand Down Expand Up @@ -2123,8 +2149,8 @@ public void playPreparedFinitePlaybackBatchV1(PreparedFinitePlaybackBatchV1 prep
throw new CryBusinessException(ErrorCode.CHECK_PARAMETER, "有限播放请求未准备");
}
requireSelectedBatch(prepared.protocol, prepared.request.json());
JNIUtils.checkJniReturn(audioJNIBridge.playAudioDataBatchV1(
prepared.protocol, prepared.request.json(), prepared.request.data()), "有限批次播放");
JNIUtils.checkJniReturn(withFinitePlaybackActivity(prepared.protocol, prepared.request.json(),
() -> audioJNIBridge.playAudioDataBatchV1(prepared.protocol, prepared.request.json(), prepared.request.data())), "有限批次播放");
}

/** 仅由本服务创建和执行,调用方不能改写已经校验的 JNI 请求。 */
Expand Down Expand Up @@ -3072,7 +3098,8 @@ public Map<Long, double[]> playAndCaptureData(Device device, List<ChannelDto> ch
JniNamedDoubleResultCollector collector = new JniNamedDoubleResultCollector();
try (var reservation = reserveExclusiveInputs(Map.of(device, inputChannels))) {
requireSelectedBatch(protocol, request.json());
int code = audioJNIBridge.playAndCaptureDataBatchV1(protocol, request.json(), request.data(), collector);
int code = withFinitePlaybackActivity(protocol, request.json(),
() -> audioJNIBridge.playAndCaptureDataBatchV1(protocol, request.json(), request.data(), collector));
JNIUtils.checkJniReturn(code, "播放并采集音频数据");
Map<String, double[]> captured = collector.finish();
for (Map.Entry<String, ChannelDto> entry : resultChannels.entrySet()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public final class CaptureInputResources {
private final Map<String, Integer> activeChannels = new HashMap<>();
private final Map<String, Occupancy> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,16 @@ 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();
}
}

private CaptureLease reserveLegacyCapture(Device device) {
synchronized (nativeStartMonitor) {
ensureNativeStartsOpen();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,13 @@ public boolean hasActive(List<Address> 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<Address> addresses) {
Set<Session> candidates;
synchronized (active) {
Expand Down
Loading
Loading