diff --git a/plugins/opentest_sonodaq_plugin/CMakeLists.txt b/plugins/opentest_sonodaq_plugin/CMakeLists.txt index d4fc8c8..2ff98cf 100644 --- a/plugins/opentest_sonodaq_plugin/CMakeLists.txt +++ b/plugins/opentest_sonodaq_plugin/CMakeLists.txt @@ -20,10 +20,16 @@ set(_sonodaq_sdk_default_library "") if(WIN32) set(_sonodaq_sdk_default_root "${CMAKE_CURRENT_LIST_DIR}/windows/sonodaq-sdk-1.4.0-windows-x64-cpp") endif() +if(APPLE) + set(_sonodaq_sdk_default_root "${CMAKE_CURRENT_LIST_DIR}/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp") +endif() set(SONODAQ_SDK_ROOT "${_sonodaq_sdk_default_root}" CACHE PATH "Root of the matching SonoDAQ C++ SDK package") if(WIN32 AND SONODAQ_SDK_ROOT) set(_sonodaq_sdk_default_library "${SONODAQ_SDK_ROOT}/sdk/lib/crydaqwrapper.lib") endif() +if(APPLE AND SONODAQ_SDK_ROOT) + set(_sonodaq_sdk_default_library "${SONODAQ_SDK_ROOT}/sdk/lib/libcrydaqwrapper.dylib") +endif() set(SONODAQ_SDK_LIBRARY "${_sonodaq_sdk_default_library}" CACHE FILEPATH "SonoDAQ crydaqwrapper import library") set(SONODAQ_SDK_INCLUDE "${OPENTEST_REPOSITORY_ROOT}/include/cry_opendaq") if(SONODAQ_SDK_ROOT) diff --git a/plugins/opentest_sonodaq_plugin/README.md b/plugins/opentest_sonodaq_plugin/README.md index c02abd7..f74872e 100644 --- a/plugins/opentest_sonodaq_plugin/README.md +++ b/plugins/opentest_sonodaq_plugin/README.md @@ -15,7 +15,7 @@ cmake -S plugins/opentest_sonodaq_plugin -B ../OpenTest-Plugins-build/sonodaq -G cmake --build ../OpenTest-Plugins-build/sonodaq --config Release --target OpenTestSonoDaqDevicePlugin --parallel ``` -Windows 默认使用随目录提供的 SDK 1.4.0。`SONODAQ_SDK_ROOT` 和 `SONODAQ_SDK_LIBRARY` 可覆盖 SDK 目录及导入库。当前源码使用 SDK 1.4 的 CAN、primitive connection 和 control 接口。不再随仓库提供旧版 macOS SDK 1.3.7;macOS 和 Linux 完整构建都需要另行提供匹配平台的 SDK 1.4/runtime,并通过 `SONODAQ_SDK_ROOT` 指定。 +Windows 默认使用随目录提供的 SDK 1.4.0。`SONODAQ_SDK_ROOT` 和 `SONODAQ_SDK_LIBRARY` 可覆盖 SDK 目录及导入库。当前源码使用 SDK 1.4 的 CAN、primitive connection 和 control 接口。macOS 默认使用随目录提供的 ARM64 SDK 1.4.0,最低系统为 macOS 26,构建及打包说明见 [macOS](macos/README.zh-CN.md)。Linux 完整构建仍需另行提供匹配平台的 SDK 1.4/runtime,并通过 `SONODAQ_SDK_ROOT` 指定。 专属测试及 CMake 配置位于本目录 `tests/`,只依赖公共 SDK 和厂商 SDK。`SONODAQ_BUILD_TESTS` 默认 `ON`,使用公共 SDK 和适配的厂商 SDK 构建,再执行 `ctest --test-dir -C Release --output-on-failure`。 diff --git a/plugins/opentest_sonodaq_plugin/macos/README.md b/plugins/opentest_sonodaq_plugin/macos/README.md new file mode 100644 index 0000000..3c764c3 --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/macos/README.md @@ -0,0 +1,17 @@ +# SonoDAQ macOS ARM64 + +The bundled headers, import dylib and complete runtime come from the official [SDK 1.4.0 release](https://github.com/crysound/sonodaq-sdk/releases/tag/v1.4.0). Archive SHA-256: `b439b4663174fdf2c71fce2e960791313d0a1beb7d106f5a462db2452e201d5b`. Vendor SDK bytes are unchanged. Examples and test programs are not bundled. The SDK requires macOS 26; this is separate from the core OpenTest runtime's macOS 12 minimum. + +From the plugin repository, with sibling OpenTest sources: + +```sh +cmake -S plugins/opentest_sonodaq_plugin -B ../OpenTest-Plugins-build/macos -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=26.0 -DCMAKE_CXX_FLAGS="-ffile-prefix-map=$HOME=/build" +cmake --build ../OpenTest-Plugins-build/macos --parallel 4 +ctest --test-dir ../OpenTest-Plugins-build/macos --output-on-failure +cmake --install ../OpenTest-Plugins-build/macos --prefix ../OpenTest-Plugins-build/install +python3 plugins/opentest_sonodaq_plugin/package/publish-macos.py --library ../OpenTest-Plugins-build/install/lib/libOpenTestSonoDaqDevicePlugin.dylib --stage ../OpenTest-Plugins-build/package-stage --output dist --framework ../OpenTest/apps/native +``` + +The packaging stage must be empty. It strips debug/local symbols from copies, verifies that exported symbols are unchanged, and signs the staged dylibs ad hoc. All SDK modules remain present. This brings the expanded payload below the host's 128 MiB limit. The vendor SDK source files remain unchanged. SDK internal development paths have not been redacted. + +Validation: Release compilation and staged SDK/module loading succeeded. The earlier 14/14 root CTest result used shared runtime fixes from OpenTest commit `10dced55`; those fixes have been withdrawn from the macOS PR as unrelated scope. That result is historical and does not establish that the current companion branch passes all root tests. Property payload length and channel-scoped streaming tests require separate owner triage. The previously generated local package also used those withdrawn fixes and must not be treated as a release artifact for the current branch. No hardware acceptance has been performed. diff --git a/plugins/opentest_sonodaq_plugin/macos/README.zh-CN.md b/plugins/opentest_sonodaq_plugin/macos/README.zh-CN.md new file mode 100644 index 0000000..4388074 --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/macos/README.zh-CN.md @@ -0,0 +1,7 @@ +# SonoDAQ macOS ARM64 + +随仓库提供官方 SDK 1.4.0 的头文件、链接动态库及完整 runtime;原始 SDK 文件保持不变。下载来源和 SHA-256 见 [英文说明](README.md)。不包含示例和测试程序。SDK 最低要求 macOS 26,与核心 OpenTest 的 macOS 12 要求不同。 + +构建、测试、安装和打包命令见英文说明。打包暂存目录必须为空。脚本仅对暂存副本移除调试及局部符号,核对全部导出符号不变后执行临时签名,保留全部 SDK 模块,使解压大小满足宿主的 128 MiB 限制。厂商 SDK 内部开发路径未脱敏。 + +验证:Release 编译及暂存 SDK/模块加载已通过。此前根 CTest 14/14 的结果使用了 OpenTest 提交 `10dced55` 的共享运行时修复;这些修复已作为无关范围从 macOS PR 撤出,因此历史结果不代表当前配套分支全部测试通过。属性字符串长度、通道运行状态相关测试交由对应维护者另行排查。此前本地生成的插件包也使用了已撤出的修复,不能作为当前分支的发布产物。尚未完成真机验收。 diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/manifest.json b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/manifest.json new file mode 100644 index 0000000..3b744b0 --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/manifest.json @@ -0,0 +1,8 @@ +{ + "sdkVersion": "1.4.0", + "language": "cpp", + "headerLayout": "compact", + "targetPlatform": "macos-arm64", + "distribution": "public", + "configuration": "Release" +} diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libcrydaqwrapper.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libcrydaqwrapper.dylib new file mode 100755 index 0000000..748fcf6 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libcrydaqwrapper.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libdaqcoreobjects-64-3.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libdaqcoreobjects-64-3.dylib new file mode 100755 index 0000000..96d0e11 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libdaqcoreobjects-64-3.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libdaqcoretypes-64-3.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libdaqcoretypes-64-3.dylib new file mode 100755 index 0000000..1a6db8d Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libdaqcoretypes-64-3.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libopendaq-64-3.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libopendaq-64-3.dylib new file mode 100755 index 0000000..865cdd1 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libopendaq-64-3.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libsonodaq_console_protocol.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libsonodaq_console_protocol.dylib new file mode 100755 index 0000000..e2d68a4 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libsonodaq_console_protocol.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libteds.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libteds.dylib new file mode 100755 index 0000000..c371636 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/libteds.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libbasic_csv_recorder_module-64-3.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libbasic_csv_recorder_module-64-3.module.dylib new file mode 100755 index 0000000..81ca2a1 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libbasic_csv_recorder_module-64-3.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libnative_stream_cl_module-64-3.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libnative_stream_cl_module-64-3.module.dylib new file mode 100755 index 0000000..1276392 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libnative_stream_cl_module-64-3.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libnative_stream_srv_module-64-3.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libnative_stream_srv_module-64-3.module.dylib new file mode 100755 index 0000000..ee7b229 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libnative_stream_srv_module-64-3.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libopcua_client_module-64-4.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libopcua_client_module-64-4.module.dylib new file mode 100755 index 0000000..7014ee1 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libopcua_client_module-64-4.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libopcua_server_module-64-4.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libopcua_server_module-64-4.module.dylib new file mode 100755 index 0000000..73cb411 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libopcua_server_module-64-4.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libref_fb_module-64-3.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libref_fb_module-64-3.module.dylib new file mode 100755 index 0000000..f7360a7 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libref_fb_module-64-3.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libsonodaq_fb_module-64-3.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libsonodaq_fb_module-64-3.module.dylib new file mode 100755 index 0000000..d51c20f Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libsonodaq_fb_module-64-3.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libws_stream_cl_module-64-4.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libws_stream_cl_module-64-4.module.dylib new file mode 100755 index 0000000..e91d39e Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libws_stream_cl_module-64-4.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libws_stream_srv_module-64-4.module.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libws_stream_srv_module-64-4.module.dylib new file mode 100755 index 0000000..6670298 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/runtime/modules/libws_stream_srv_module-64-4.module.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/README.md b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/README.md new file mode 100644 index 0000000..17c4186 --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/README.md @@ -0,0 +1,8 @@ +# Compact C++ SDK headers + +Include or ; include both when using both domains. +Link the SDK libraries as usual. +The split header paths are not included in this layout. Use this complete include +directory instead of overlaying it onto a modular SDK installation. +The optional opendaq_interop.h still needs the matching openDAQ SDK. +See ../docs/install_package_usage.md and ../docs/build-info/amalgamation-manifest.json. diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/crydaq_common.h b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/crydaq_common.h new file mode 100644 index 0000000..e331eaf --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/crydaq_common.h @@ -0,0 +1,3083 @@ +// Generated by amalgamate_cpp_sdk_headers.py; do not edit. +#ifndef SONODAQ_COMPACT_COMMON_H +#define SONODAQ_COMPACT_COMMON_H + +// BEGIN SDK HEADER: crydaq/capture_task.h +#ifndef SONODAQ_COMPACT_FILE_CC12ACCBB3B6E6CC1312 +#define SONODAQ_COMPACT_FILE_CC12ACCBB3B6E6CC1312 + +// BEGIN SDK HEADER: crydaq/export.h +#ifndef CRYDAQ_EXPORT_H +#define CRYDAQ_EXPORT_H + +#define CRYDAQ_PUBLIC_API_REVISION 4 + +#if defined(CRYDAQWRAPPER_STATIC) +#ifndef DAQ_API_EXPORT +#define DAQ_API_EXPORT +#endif +#elif defined(_WIN32) +#ifndef DAQ_API_EXPORT +#ifdef CRYDAQWRAPPER_EXPORT_API +#define DAQ_API_EXPORT __declspec(dllexport) +#else +#define DAQ_API_EXPORT __declspec(dllimport) +#endif +#endif +#else +#ifndef DAQ_API_EXPORT +#define DAQ_API_EXPORT __attribute__((visibility("default"))) +#endif +#endif + +#endif // CRYDAQ_EXPORT_H +// END SDK HEADER: crydaq/export.h + +// BEGIN SDK HEADER: crydaq/result.h +#ifndef CRYDAQ_RESULT_H +#define CRYDAQ_RESULT_H + +#include +#include +#include + + +// BEGIN SDK HEADER: crydaq/optional.h +#ifndef CRYDAQ_OPTIONAL_H +#define CRYDAQ_OPTIONAL_H + +#if defined(_MSVC_LANG) +#define CRYDAQ_CPP_LANG_VERSION _MSVC_LANG +#else +#define CRYDAQ_CPP_LANG_VERSION __cplusplus +#endif + +#if CRYDAQ_CPP_LANG_VERSION >= 201703L +#include +#else +#include +#include +#include +#include +#endif + +namespace CryDaq +{ +#if CRYDAQ_CPP_LANG_VERSION >= 201703L + template + using Optional = std::optional; +#else + template + class Optional + { + public: + Optional() noexcept = default; + + Optional(const T& value) + { + emplace(value); + } + + Optional(T&& value) + { + emplace(std::move(value)); + } + + Optional(const Optional& other) + { + if (other.has_value()) + emplace(*other); + } + + Optional(Optional&& other) noexcept(std::is_nothrow_move_constructible::value) + { + if (other.has_value()) + emplace(std::move(*other)); + } + + ~Optional() + { + reset(); + } + + Optional& operator=(const Optional& other) + { + if (this == &other) + return *this; + + if (other.has_value()) + assign(*other); + else + reset(); + return *this; + } + + Optional& operator=(Optional&& other) + { + if (this == &other) + return *this; + + if (other.has_value()) + assign(std::move(*other)); + else + reset(); + return *this; + } + + Optional& operator=(const T& value) + { + assign(value); + return *this; + } + + Optional& operator=(T&& value) + { + assign(std::move(value)); + return *this; + } + + explicit operator bool() const noexcept + { + return hasValue_; + } + + bool has_value() const noexcept + { + return hasValue_; + } + + T& operator*() noexcept + { + return *ptr(); + } + + const T& operator*() const noexcept + { + return *ptr(); + } + + T* operator->() noexcept + { + return ptr(); + } + + const T* operator->() const noexcept + { + return ptr(); + } + + T& value() + { + if (!hasValue_) + throw std::logic_error("CryDaq::Optional::value() called without a value."); + return *ptr(); + } + + const T& value() const + { + if (!hasValue_) + throw std::logic_error("CryDaq::Optional::value() called without a value."); + return *ptr(); + } + + template + T& emplace(Args&&... args) + { + reset(); + new (&storage_) T(std::forward(args)...); + hasValue_ = true; + return *ptr(); + } + + void reset() noexcept + { + if (hasValue_) + { + ptr()->~T(); + hasValue_ = false; + } + } + + private: + template + void assign(U&& value) + { + if (hasValue_) + **this = std::forward(value); + else + emplace(std::forward(value)); + } + + T* ptr() noexcept + { + return reinterpret_cast(&storage_); + } + + const T* ptr() const noexcept + { + return reinterpret_cast(&storage_); + } + + typename std::aligned_storage::type storage_; + bool hasValue_ = false; + }; +#endif +} + +#undef CRYDAQ_CPP_LANG_VERSION + +#endif // CRYDAQ_OPTIONAL_H +// END SDK HEADER: crydaq/optional.h + +// BEGIN SDK HEADER: crydaq/core_types.h +#ifndef CRYDAQ_CORE_TYPES_H +#define CRYDAQ_CORE_TYPES_H + +#include +#include + +// BEGIN SDK HEADER: crydaq/version.h +#ifndef CRYDAQ_VERSION_H +#define CRYDAQ_VERSION_H + +namespace CryDaq +{ + +constexpr const char *VERSION = "1.4.0"; + +} + +#endif // CRYDAQ_VERSION_H +// END SDK HEADER: crydaq/version.h + +namespace CryDaq +{ + + // Forward declaration for C++ interface + class CRYDaqInstance; + + enum class DataSaveTimestampMode : int + { + Utc = 0, + LocalUnmarked = 1, + }; + + enum class LogLevel : uint8_t + { + Trace = 0, + Debug = 1, + Info = 2, + Warn = 3, + Error = 4, + Critical = 5, + }; + + struct LoggingConfig + { + // Console logging is disabled when stdout is a pipe at initialization. + bool consoleEnabled = false; + bool fileEnabled = true; + LogLevel logLevel = LogLevel::Info; + std::string logFilePath; ///< UTF-8 主机文件路径。 + }; + + enum class ErrorCode : int + { + Success = 0, // Success + NotInitialized, // Not initialized + InvalidHandle, // Invalid handle + InvalidParameter, // Invalid parameter + ConnectionFailed, // Connection failed + NotConnected, // Not connected + NullPointer, // Null pointer + OutOfRange, // Out of range + NotImplemented, // Not implemented + NoData, // No data + DeviceNotFound, // Device not found + OperationFailed, // Operation failed + Unknown, // Unknown error + SyncNotAligned, // Sync playback not aligned + ChannelPowerOff, // ChannelPowerSwitch is off for one or more target channels + ResourceBusy, // Playback/capture resource is already reserved + TotalCount // Total count, used to help get the number of Enum + }; + + inline const char* error_code_name(ErrorCode code) noexcept + { + switch (code) + { + case ErrorCode::Success: return "Success"; + case ErrorCode::NotInitialized: return "NotInitialized"; + case ErrorCode::InvalidHandle: return "InvalidHandle"; + case ErrorCode::InvalidParameter: return "InvalidParameter"; + case ErrorCode::ConnectionFailed: return "ConnectionFailed"; + case ErrorCode::NotConnected: return "NotConnected"; + case ErrorCode::NullPointer: return "NullPointer"; + case ErrorCode::OutOfRange: return "OutOfRange"; + case ErrorCode::NotImplemented: return "NotImplemented"; + case ErrorCode::NoData: return "NoData"; + case ErrorCode::DeviceNotFound: return "DeviceNotFound"; + case ErrorCode::OperationFailed: return "OperationFailed"; + case ErrorCode::Unknown: return "Unknown"; + case ErrorCode::SyncNotAligned: return "SyncNotAligned"; + case ErrorCode::ChannelPowerOff: return "ChannelPowerOff"; + case ErrorCode::ResourceBusy: return "ResourceBusy"; + case ErrorCode::TotalCount: return "TotalCount"; + default: return "Unknown"; + } + } + + enum class SampleUnit : uint8_t + { + RawFs = 0, // 原始满量程码值(FS / PCM32) + Voltage, // 瞬时电压样本 V(t), not RMS + ChargePc // 瞬时电荷样本 pC(t),仅采集输出支持 + }; + + /***************************************************************** + ***************** 阻塞式 Play/Rec/PlayRec API 类型 ************** + *****************************************************************/ + + /** + * @brief 通道引用,用于唯一定位一个通道 + */ + struct ChannelRef + { + std::string connectionString; ///< 设备连接字符串 + std::string channelLocalId; ///< 通道本地ID,如 "Ch-3#1" + }; + +} // namespace CryDaq + +#endif // CRYDAQ_CORE_TYPES_H +// END SDK HEADER: crydaq/core_types.h + +namespace CryDaq +{ + enum class ErrorCategory : uint8_t + { + Validation = 0, + Runtime, + Device, + Transport, + FileSystem, + Unsupported, + Timeout, + Unknown + }; + + enum class ErrorSeverity : uint8_t + { + Info = 0, + Warning, + Error, + Fatal + }; + + struct SdkError + { + ErrorCategory category = ErrorCategory::Unknown; + ErrorSeverity severity = ErrorSeverity::Error; + ErrorCode code = ErrorCode::Unknown; + std::string issueCode; + std::string message; + Optional channel; + Optional remediation; + Optional action; + Optional context; + }; + + template + class Result + { + public: + static Result success(T value) + { + Result result; + result.value_ = std::move(value); + return result; + } + + static Result failure(SdkError error) + { + Result result; + result.error_ = std::move(error); + return result; + } + + static Result failure(SdkError error, T partialValue) + { + auto result = failure(std::move(error)); + result.partialValue_ = std::move(partialValue); + return result; + } + + const Optional& partial_value() const noexcept { return partialValue_; } + + T&& move_partial_value() + { + if (!partialValue_.has_value()) + throw std::logic_error("CryDaq::Result::move_partial_value() called without a partial value."); + return std::move(*partialValue_); + } + + bool ok() const noexcept + { + return value_.has_value(); + } + + explicit operator bool() const noexcept + { + return ok(); + } + + const T& value() const + { + if (!value_.has_value()) + throw std::logic_error("CryDaq::Result::value() called on a failed result."); + return *value_; + } + + T& value() + { + if (!value_.has_value()) + throw std::logic_error("CryDaq::Result::value() called on a failed result."); + return *value_; + } + + T&& move_value() + { + if (!value_.has_value()) + throw std::logic_error("CryDaq::Result::move_value() called on a failed result."); + return std::move(*value_); + } + + const SdkError& error() const + { + if (value_.has_value()) + throw std::logic_error("CryDaq::Result::error() called on a successful result."); + return error_; + } + + private: + Optional value_; + Optional partialValue_; + SdkError error_; + }; + + template <> + class Result + { + public: + static Result success() noexcept + { + Result result; + result.ok_ = true; + return result; + } + + static Result failure(SdkError error) + { + Result result; + result.error_ = std::move(error); + return result; + } + + bool ok() const noexcept + { + return ok_; + } + + explicit operator bool() const noexcept + { + return ok(); + } + + const SdkError& error() const + { + if (ok_) + throw std::logic_error("CryDaq::Result::error() called on a successful result."); + return error_; + } + + private: + bool ok_ = false; + SdkError error_; + }; +} + +#endif // CRYDAQ_RESULT_H +// END SDK HEADER: crydaq/result.h + +// BEGIN SDK HEADER: crydaq/capture_types.h +#ifndef CRYDAQ_CAPTURE_TYPES_H +#define CRYDAQ_CAPTURE_TYPES_H + + +// BEGIN SDK HEADER: crydaq/sample_types.h +#ifndef CRYDAQ_SAMPLE_TYPES_H +#define CRYDAQ_SAMPLE_TYPES_H + +#include + +namespace CryDaq +{ + + struct DataPoint + { + int value = 0; + long long timestamp = 0; + // SonoDAQ recording-axis marker derived from the input sample domain timestamp. + // Valid points use recordUtc100ms as the 100 ms bucket and recordFrameOffsetSamples + // as the sample offset inside that bucket. recordFrameStart marks the exact first + // ADC sample of the 100 ms frame used by scheduled-playback latency checks. + bool hasRecordFrameMarker = false; + uint64_t recordUtc100ms = 0; + // Diagnostic CNT derived from recordUtc100ms modulo 4096. The authoritative + // hardware scheduling CNT is reported in SyncPlaybackScheduledAnchor. + uint16_t recordCnt100ms = 0; + uint32_t recordFrameOffsetSamples = 0; + bool recordFrameStart = false; + }; + + struct ChannelInData + { + int count; // users can specify the max count of data points to read, if 0, read all data points(100ms by default) + std::vector data; // Data points vector + void *handle = nullptr; // reader handle must be the same between different reads if data continuity is needed, mainly used for sync capture mode + std::string localId; // Channel local ID + std::string connectionString; // Connection string + int samplerate; + }; + + struct DeviceInData + { + std::vector channelData; // Channel data + std::string connectionString; // Connection string + }; + + struct ChannelOutData + { + int sampleRate; + int bitDepth; + std::vector data; // Data vector + std::string localId; // Channel local ID + std::string connectionString; // Connection string + }; + + struct DeviceOutData + { + std::vector channelData; // Channel data + std::string connectionString; // Connection string + std::string zmqEndPoint; + }; + + struct SampleFrame + { + SampleUnit unit = SampleUnit::RawFs; + std::vector rawSamples; + std::vector engineeringSamples; + std::vector timestamps; + int sampleRate = 0; + std::string localId; + std::string connectionString; + }; + + using DataCallback = void (*)(void *handle, const std::string &connectionString, const std::string &channelLocalId, const ChannelInData &data); + + using SampleCallback = void (*)(void *handle, const SampleFrame &data); + + enum class PcmLayout : uint8_t + { + Interleaved = 0 + }; + + struct AlignedSampleFrame : SampleFrame + { + std::vector channels; + int frameCount = 0; + PcmLayout layout = PcmLayout::Interleaved; + std::string groupId; + std::vector validityMask; + }; + + struct ChannelScale + { + ChannelRef channel; + double effectiveFullScale = 0.0; + std::string rangeId; + std::string rangeLabel; + }; + + struct EngineeringScaleSnapshot + { + SampleUnit unit = SampleUnit::RawFs; + std::vector channels; + }; + + enum class CaptureMissingPolicy : uint8_t + { + Drop = 0, + ZeroFill = 1 + }; + + struct AlignGroupConfig + { + std::string groupId; + std::vector channels; + CaptureMissingPolicy missingPolicy = CaptureMissingPolicy::Drop; + uint64_t maxWaitMs = 50; + }; + + struct AsyncCaptureOptions + { + std::vector alignGroups; + }; + + struct AlignedPcmData + { + std::string groupId; + int channelCount = 0; + int frameCount = 0; + int sampleRate = 0; + PcmLayout layout = PcmLayout::Interleaved; + std::vector channels; + std::vector pcmData; + std::vector timestamps; + std::vector validityMask; + }; + + using AlignedPcmCallback = void (*)(void *handle, const AlignedPcmData &data); + + using AlignedSampleCallback = void (*)(void *handle, const AlignedSampleFrame &data); + +} // namespace CryDaq + +#endif // CRYDAQ_SAMPLE_TYPES_H +// END SDK HEADER: crydaq/sample_types.h + +namespace CryDaq +{ + + /** + * @brief 录音输出控制 + * + * 输出模式自动判断: + * - filepath 为空:返回内存数据(必须提供 outResult) + * - filepath 非空:保存到文件 + */ + enum class AlignedOutputMode : uint8_t + { + InterleavedOnly = 0, ///< 仅保存 aligned group 的交织多通道 WAV + PerChannelOnly = 1, ///< 仅保存 aligned group 拆分后的每通道 mono WAV + Both = 2 ///< 同时保存交织多通道 WAV 和每通道 mono WAV + }; + + struct RecordOutput + { + std::string filepath; ///< UTF-8 文件路径:空=内存模式,非空=文件模式(单通道为文件,多通道为目录) + int bitDepth = 32; ///< 文件模式:保存位深 16/24/32 + bool autoCreateDir = true; ///< 文件模式:自动创建目录 + bool overwrite = true; ///< 文件模式:自动覆盖已存在文件 + bool saveAlignedMetadata = false; ///< aligned 文件模式:显式开启后额外保存 metadata sidecar + AlignedOutputMode alignedOutputMode = AlignedOutputMode::InterleavedOnly; ///< aligned 文件模式 WAV 输出布局 + bool retainSamples = false; ///< 文件模式:显式保留完整采样数组 + }; + + struct RecordCaptureOptions + { + std::vector alignGroups; ///< 为空时走 legacy 模式;非空时走 aligned 模式 + bool populateLegacyChannelData = false; ///< aligned 模式下是否回填 legacy channelData + }; + + /** + * @brief 单通道录音数据 + */ + struct ChannelRecordData + { + ChannelRef channel; ///< 通道引用 + SampleUnit unit = SampleUnit::RawFs; ///< 返回数据单位 + std::vector rawSamples; ///< RawFs 采样数据 + std::vector voltageSamples; ///< Voltage 瞬时电压样本 V(t),不是 RMS + std::vector chargeSamples; ///< ChargePc 瞬时电荷样本 pC(t) + std::vector timestamps; ///< 每个样本的设备时间戳;为空表示该路径未提供 + std::vector validityMask; ///< 每个样本是否有效;为空表示全部样本有效 + int sampleRate = 0; ///< 采样率(Hz) + double effectiveVp = 1.0; ///< 本次换算实际使用的 VP(优先取档位 vp,缺失时尝试从 label 解析) + bool vpFallbackUsed = false; ///< true 表示 vp 和 label 都无法解析,最终按 1.0 处理 + std::string vpRangeId; ///< 本次换算使用的档位 ID + std::string vpRangeLabel; ///< 本次换算使用的档位显示名 + double effectiveChargePc = 1.0; ///< ChargePc 模式下换算使用的满量程电荷 pC + bool chargeFallbackUsed = false; ///< true 表示 pC 档位解析失败后回退为 1.0 + std::string chargeRangeId; ///< ChargePc 模式下使用的档位 ID + std::string chargeRangeLabel; ///< ChargePc 模式下使用的档位显示名 + std::string outputFilepath; ///< 文件模式下实际保存的 WAV 路径;内存模式为空 + int64_t capturedFrameCount = 0; ///< 文件模式保存的帧数 + }; + + struct AlignedChannelRecordInfo + { + ChannelRef channel; ///< 通道引用(顺序与交织 PCM 对齐) + double effectiveVp = 1.0; ///< Voltage 模式下换算使用的 VP + bool vpFallbackUsed = false; ///< true 表示 VP 解析失败后回退为 1.0 + std::string vpRangeId; ///< Voltage 模式下使用的档位 ID + std::string vpRangeLabel; ///< Voltage 模式下使用的档位显示名 + double effectiveChargePc = 1.0; ///< ChargePc 模式下换算使用的满量程电荷 pC + bool chargeFallbackUsed = false; ///< true 表示 pC 解析失败后回退为 1.0 + std::string chargeRangeId; ///< ChargePc 模式下使用的档位 ID + std::string chargeRangeLabel; ///< ChargePc 模式下使用的档位显示名 + std::string outputFilepath; ///< 每通道 WAV 实际保存路径;未保存每通道 WAV 时为空 + }; + + struct AlignedGroupRecordData + { + std::string groupId; + SampleUnit unit = SampleUnit::RawFs; + int sampleRate = 0; + int channelCount = 0; + int frameCount = 0; + PcmLayout layout = PcmLayout::Interleaved; + std::vector channels; + std::vector interleavedRawSamples; + std::vector interleavedVoltageSamples; ///< 交织的瞬时电压样本 V(t),不是 RMS + std::vector interleavedChargeSamples; ///< 交织的瞬时电荷样本 pC(t) + std::vector timestamps; + std::vector validityMask; + std::string outputFilepath; ///< 文件模式下实际保存的 WAV 路径;内存模式为空 + std::string metadataFilepath; ///< 文件模式下实际保存的 metadata sidecar 路径;未保存时为空 + }; + + /** + * @brief 录音结果(内存模式) + */ + struct RecordResult + { + std::vector channelData; ///< 各通道数据 + std::vector alignedGroups; ///< aligned 模式结果 + std::string errorCode; ///< 失败诊断码;通道电源预检失败时为 ERR_CHANNEL_POWER_OFF + std::string errorInfo; ///< 失败诊断信息;成功时为空 + std::vector requestedChannels; ///< 失败诊断:本次请求目标通道 + std::vector powerOffChannels; ///< 失败诊断:ChannelPowerSwitch=false 的目标通道 + }; + + /** + * @brief 采集请求(支持多设备多通道) + */ + struct RecordRequest + { + std::vector channels; ///< 输入通道集合(可跨设备) + int fs = 0; ///< 采样率(Hz) + int64_t durationMs = 0; ///< 采集样本时长(ms)。frameCount 为 0 时按 fs 换算帧数,向上取整。 + int64_t frameCount = 0; ///< 目标采集帧数;0 表示按 durationMs 采集 + SampleUnit outputUnit = SampleUnit::RawFs; ///< 输出数据单位;内存模式支持 RawFs/Voltage/ChargePc,文件模式仅支持 RawFs + RecordOutput output; ///< 输出策略 + RecordCaptureOptions capture; ///< 采集模式扩展 + }; + +} // namespace CryDaq + +#endif // CRYDAQ_CAPTURE_TYPES_H +// END SDK HEADER: crydaq/capture_types.h +#include + +namespace CryDaq +{ + namespace detail { class CaptureTaskAccess; } + enum class CaptureState : uint8_t { Created, Running, Stopping, Completed, Stopped, Failed, Closed }; + struct CaptureStatus + { + CaptureState state = CaptureState::Created; + Optional error; + }; + class DAQ_API_EXPORT CaptureTask + { + public: + CaptureTask() noexcept; + ~CaptureTask(); + CaptureTask(CaptureTask&&) noexcept; + CaptureTask& operator=(CaptureTask&&) noexcept; + CaptureTask(const CaptureTask&) = delete; + CaptureTask& operator=(const CaptureTask&) = delete; + CaptureStatus GetStatus() const; + // A stopped finite capture returns the data collected before the stop. + Result Wait(int64_t timeoutMs = -1) const; + Result Stop(); + Result Close(int64_t timeoutMs = 5000); + private: + struct Impl; + std::shared_ptr impl_; + friend class detail::CaptureTaskAccess; + }; +} + +namespace CryDaq +{ + namespace primitive::capture { class Controller; } + class DAQ_API_EXPORT CaptureStream + { + public: + CaptureStream() noexcept; + ~CaptureStream(); + CaptureStream(CaptureStream&&) noexcept; + CaptureStream& operator=(CaptureStream&&) noexcept; + CaptureStream(const CaptureStream&) = delete; + CaptureStream& operator=(const CaptureStream&) = delete; + CaptureStatus GetStatus() const; + Result Wait(int64_t timeoutMs = -1) const; + Result Stop(); + Result Close(); + private: + struct Impl; + std::shared_ptr impl_; + friend class primitive::capture::Controller; + }; +} +#endif // SONODAQ_COMPACT_FILE_CC12ACCBB3B6E6CC1312 +// END SDK HEADER: crydaq/capture_task.h + +// BEGIN SDK HEADER: crydaq/device_types.h +#ifndef CRYDAQ_DEVICE_TYPES_H +#define CRYDAQ_DEVICE_TYPES_H + +#include +#include + +namespace CryDaq +{ + + enum class DevicePropertyOperationKind + { + WritableProperty, + FunctionProperty + }; + + struct DevicePropertyArgument + { + std::string name; + std::string valueJson; // JSON scalar: true, false, 123, 1.25, "text" + int valueType = 3; + }; + + struct DevicePropertyTarget + { + std::string connectionString; + std::string localId; // empty means device-level property; non-empty means channel-level property + std::string propertyName; + }; + + struct DevicePropertyOperation + { + std::string connectionString; + std::string localId; // empty means device-level property; non-empty means channel-level property + std::string propertyName; + + DevicePropertyOperationKind kind = DevicePropertyOperationKind::WritableProperty; + + // WritableProperty + std::string valueJson; + int valueType = 3; + int itemType = 65535; + int keyType = 65535; + + // FunctionProperty + std::vector arguments; + int returnType = 0; + }; + + enum class ChannelType : uint8_t + { + Input = 0, + Output = 1, + Can = 2, + Count = 3 + }; + + enum class BoardType : uint8_t + { + Unknown = 0, + IED = 1, // Input board + ADD = 4, // Output+Input board + IES = 6, // Input board with IEPE support + ADS = 7, // AD+DA hybrid board + AOS = 10, // Output board + LMQ = 11, // LMQ four-channel input board + LMC = 12, // LMC two-channel input board + }; + + enum class ConnectionMode : uint8_t + { + // Normal control. Multiple clients can connect to the same device concurrently. + Control = 0, + // Exclusive control. Connect succeeds only when no other clients are connected to the device. + ExclusiveControl = 1, + // Forced exclusive control. Other clients are disconnected before this client takes control. + ExclusiveControlDropOthers = 2, + }; + + struct ConnectionOptions + { + ConnectionMode mode = ConnectionMode::ExclusiveControl; + }; + + enum class DeviceConnectionState : uint8_t + { + Unknown = 0, + Connected = 1, + Reconnecting = 2, + Unrecoverable = 3, + Disconnected = 4, + }; + + struct DeviceConnectionStatusEvent + { + std::string connectionString; // User-facing connection string passed to Connect/Open. + std::string rawConnectionString; // Runtime event connection string, often daq.ns://... + DeviceConnectionState state = DeviceConnectionState::Unknown; + std::string rawStatus; + bool terminal = false; + std::uint64_t sequence = 0; + }; + + struct GeneralDeviceInfo + { + std::string name; // Device name + std::string manufacturer; // Device manufacturer + std::string serialNumber; // Device serial number + std::string softwareRevision; // Software version + std::string hardwareRevision; // Hardware version + std::string sdkVersion; // SDK version + std::string macAddress; // MAC address + std::string connectionString; // Connection string + std::string model; // Device model + std::string extra; // Extra information, reserved + }; + + enum class ChannelPropertyValueType : uint8_t + { + Enum = 0, + Boolean, + Number, + Text, + }; + + enum class ChannelPropertyApplyScope : uint8_t + { + ThisChannelOnly = 0, + RelatedChannels, + DeviceWide, + }; + + struct ChannelPropertyOption + { + std::string id; + std::string label; + }; + + struct ChannelPropertyValue + { + bool hasValue = false; + std::string textValue; // Enum id or text value. + std::string displayText; // User-facing value label when available. + bool boolValue = false; + double numberValue = 0.0; + }; + + struct ChannelPropertyStatus + { + std::string key; // Stable SDK key, e.g. "measurementMode". + std::string displayName; // User-facing property name. + std::string propertyName; // Runtime/openDAQ property name when one exists. + ChannelPropertyValueType valueType = ChannelPropertyValueType::Text; + ChannelPropertyValue value; + std::vector options; + bool readable = false; + bool writable = false; + ChannelPropertyApplyScope applyScope = ChannelPropertyApplyScope::ThisChannelOnly; + std::vector affectedChannelLocalIds; + }; + + struct ChannelInfo + { + bool iepeSwitch; // IEPE switch state, for inputs exposing IEPE state or profile-backed IEPE mode + bool chargeSwitch; // Charge switch/state, for profile-backed charge-capable inputs + bool outputEnable; // Output enable state, only for channels exposing OutputEnable + bool adcEnabled; // ADC enable state, only for channels exposing ADCEnabled + bool channelPowerSwitch; // Raw state when exposed; GetChannelPowerSwitch reports true when it is not exposed + uint8_t ioMode; // 0:Differential, 1:Single-ended; maps to InputMode or OutputMode by channel profile + bool pvPowerChannelSwitch; // LMQ PV power switch state when exposed by the channel profile/property + bool cicEnableSwitch; // LMQ CIC enable switch state when exposed by the channel profile/property + uint8_t couplingMode; // 0:AC, 1:DC, for channels exposing coupling state; profile modes may force AC + ChannelType type; // Channel type: input or output + BoardType boardType; // Board type this channel belongs to + int bitDepth; // Bit depth, fixed to 32 for now + int sampleRate; // Sample rate + std::string localId; // Channel local ID + std::string globalId; // Channel global ID + std::string currentVpRangeId; // Current VP range ID (e.g. "range0") + std::string currentVpRangeLabel; // Current VP range display label (e.g. "0.24Vp") + std::vector properties; // Capability-aware dynamic channel properties + int rawBoardTypeId = 0; // Raw device BoardTypeId when reported; 0 means unknown + Optional currentVp; // Current finite positive actual VP reported by the device + }; + + /** + * @brief Channel VP (Voltage Peak) values information + * This structure contains all valid VP value combinations for a channel + */ + struct ChannelVpInfo + { + std::string connectionString; // Device connection string + std::string channelLocalId; // Channel local ID + std::string vpValuesJson; // VP values in JSON format, containing all valid VP combinations + }; + + /** + * @brief Single VP range tier information + */ + struct VpRangeInfo + { + std::string id; // Range ID (e.g. "range0"), used internally + std::string label; // Display label (e.g. "0.24Vp"), user-visible + bool isDefault = false; // Whether this is the default range + double vp = -1.0; // VP value (Voltage Peak), -1 if unavailable + bool isCurrent = false; // Whether this is the currently active range + }; + + /** + * @brief Result of querying available VP ranges for a channel + */ + struct ChannelVpRangesResult + { + std::string connectionString; // Device connection string + std::string channelLocalId; // Channel local ID + std::vector ranges; // All available VP ranges + std::string currentRangeId; // Currently selected range ID + std::string currentRangeLabel; // Currently selected range display label + }; + + struct DetailDeviceInfo + { + GeneralDeviceInfo generalInfo; // Device general information + std::vector channelInfo; // Channel information + }; + + struct DeviceModuleInfo + { + std::string connectionString; // Device connection string + int boardNumber = 0; // One-based board number parsed from channel local ID, e.g. Ch-3#1 -> 3 + BoardType boardType = BoardType::Unknown; // Module board type + std::string boardTypeName; // Display board type name, e.g. "AOS" or "ADD" + std::string serialNumber; // Module serial number + std::string firmwareVersion; // Module firmware version + std::string hardwareVersion; // Module hardware version + std::vector channelLocalIds; // Channels that belong to this module + int rawBoardTypeId = 0; // Raw device BoardTypeId when reported; 0 means unknown + }; + + struct DeviceDates + { + std::string connectionString; // Device connection string + std::string warrantyDate; // DeviceWarrantyDate normalized when it uses a supported date format + std::string calibrationDate; // Derived from nextCalibrationDate minus one calendar year + std::string nextCalibrationDate; // DeviceNextCalibrationDate normalized when it uses a supported date format + }; + + struct BoardChannelControlCapabilities + { + std::string channelLocalId; // Channel local ID within the board/module + std::vector controls; // Capability-aware controls exposed by this channel + }; + + struct BoardControlCapabilities + { + DeviceModuleInfo module; // Board/module identity + std::vector channels; // Channels that belong to the module + std::vector boardControls; // Deduplicated controls that affect related channels or the whole device + std::vector channelControls; // Per-channel controls, preserving channel order + }; + + enum class DeviceTypeName : uint8_t + { + Connection = 0, + }; + + struct ComponentState + { + int state; + DeviceTypeName type; + }; + + struct DeviceState + { + ComponentState connectState; + // Reserved + }; + + struct DeviceChannelsConfig + { + std::vector channels; // Channel information + std::string connectionString; // Connection string + std::map lemoSwitches; // Request-only LMQ LEMO switch values keyed by channel local ID + }; + + struct ReadbackChannelConfig + { + std::string localId; // AOS source output channel local ID + bool enabled = false; + }; + + struct DeviceReadbackConfig + { + std::string connectionString; + std::vector channels; + }; + + // Callback function types + using DeviceConnectionStatusCallback = void (*)(void *handle, const DeviceConnectionStatusEvent &event); + + struct GnssData + { + std::uint64_t timestampUs = 0; + double longitudeDegrees = 0.0; + double latitudeDegrees = 0.0; + double altitudeMeters = 0.0; + double speedMetersPerSecond = 0.0; + double courseDegrees = 0.0; + bool positionValid = false; + bool speedValid = false; + bool isMoving = false; + bool courseValid = false; + }; + + using GnssDataCallback = void (*)(void *handle, const std::string &connectionString, const GnssData &data); + +} // namespace CryDaq + +#endif // CRYDAQ_DEVICE_TYPES_H +// END SDK HEADER: crydaq/device_types.h + +// BEGIN SDK HEADER: crydaq/digital_filter_types.h +#ifndef CRYDAQ_DIGITAL_FILTER_TYPES_H +#define CRYDAQ_DIGITAL_FILTER_TYPES_H + +#include +#include + +namespace CryDaq +{ + enum class DigitalFilterHighPass : int + { + Off = 0, + Dc = 1, + Ac = 2, + Butterworth = 3, + Elliptic = 4 + }; + + enum class DigitalFilterLowPass : int + { + Off = 0, + Nyquist = 1, + Butterworth = 2, + Elliptic = 3, + SafeNyquist = 4 + }; + + struct DigitalFilterConfig + { + DigitalFilterHighPass highPass = DigitalFilterHighPass::Off; + double highPassFrequencyHz = 10.0; + DigitalFilterLowPass lowPass = DigitalFilterLowPass::Nyquist; + double lowPassFrequencyHz = 40000.0; + }; + + struct DigitalFilterCallResult + { + bool accepted = false; + int innerCode = 0; + std::string message; + std::string rawResponseJson; + }; + + struct DigitalFilterOption + { + int value = 0; + std::string key; + Optional effectiveFrequencyHz; + std::vector allowedFrequenciesHz; + }; + + struct DigitalFilterCapabilities : DigitalFilterCallResult + { + int schemaVersion = 0; + std::string preferredValueType; + bool frequencyWeightingSupported = false; + std::vector highPassOptions; + std::vector lowPassOptions; + }; + + struct DigitalFilterCurrentConfig : DigitalFilterCallResult + { + std::string channelLocalId; + DigitalFilterHighPass highPass = DigitalFilterHighPass::Off; + std::string highPassKey; + double highPassFrequencyHz = 10.0; + DigitalFilterLowPass lowPass = DigitalFilterLowPass::Nyquist; + std::string lowPassKey; + double lowPassFrequencyHz = 40000.0; + }; + +} + +#endif // CRYDAQ_DIGITAL_FILTER_TYPES_H +// END SDK HEADER: crydaq/digital_filter_types.h + +// BEGIN SDK HEADER: crydaq/input_capabilities.h +#ifndef CRYDAQ_INPUT_CAPABILITIES_H +#define CRYDAQ_INPUT_CAPABILITIES_H + +#include + + +// BEGIN SDK HEADER: crydaq/measurement_mode.h +#ifndef CRYDAQ_MEASUREMENT_MODE_H +#define CRYDAQ_MEASUREMENT_MODE_H + +#include + +namespace CryDaq +{ + enum class MeasurementMode : uint8_t + { + Voltage = 0, + Iepe = 1, + Charge = 2, + Lemo = 3, + }; +} + +#endif // CRYDAQ_MEASUREMENT_MODE_H +// END SDK HEADER: crydaq/measurement_mode.h + +namespace CryDaq +{ + struct InputCapabilities + { + ChannelRef channel; + std::string globalId; + Optional boardType; + bool existsInSession = false; + bool isInputChannel = false; + bool supportsVoltage = false; + bool supportsIepe = false; + bool supportsCharge = false; + bool supportsLemo = false; + bool supportsCouplingMode = false; + + bool supports(MeasurementMode mode) const noexcept + { + switch (mode) + { + case MeasurementMode::Voltage: + return supportsVoltage; + case MeasurementMode::Iepe: + return supportsIepe; + case MeasurementMode::Charge: + return supportsCharge; + case MeasurementMode::Lemo: + return supportsLemo; + default: + return false; + } + } + }; +} + +#endif // CRYDAQ_INPUT_CAPABILITIES_H +// END SDK HEADER: crydaq/input_capabilities.h + +// BEGIN SDK HEADER: crydaq/input_config.h +#ifndef CRYDAQ_INPUT_CONFIG_H +#define CRYDAQ_INPUT_CONFIG_H + +#include + + +// BEGIN SDK HEADER: crydaq/range_policy.h +#ifndef CRYDAQ_RANGE_POLICY_H +#define CRYDAQ_RANGE_POLICY_H + +#include +#include +#include +#include + + +namespace CryDaq +{ + /** + * @brief Engineering domain used by range auto-selection. + * + * Voltage-like inputs should use VoltagePeak. + * Charge measurement inputs on profile-backed boards such as LMQ + * should use ChargePeak. + */ + enum class SignalDomain : uint8_t + { + VoltagePeak = 0, + ChargePeak = 1, + }; + + /** + * @brief High-level range selection strategy exposed by the facade API. + */ + enum class RangeSelectionMode : uint8_t + { + AutoSelect = 0, + KeepCurrentIfValid = 1, + FixedLabel = 2, + FixedRange = 3, + }; + + /** + * @brief Optional expected signal information used by range_auto(). + * + * `peak` is expressed in the unit implied by `domain`: + * - VoltagePeak => Vp + * - ChargePeak => pC peak + */ + struct ExpectedSignalHint + { + SignalDomain domain = SignalDomain::VoltagePeak; + double peak = 0.0; + double safetyMargin = 1.2; + }; + + /** + * @brief Auto-selection knobs for facade-internal resolution. + * + * These options are intentionally small in the first version to keep the + * default behavior easy to explain in README and IntelliSense. + */ + struct RangeAutoOptions + { + bool keepCurrentIfValid = true; + bool preferProfileDefaultWhenNoHint = true; + bool excludeDiagnosticRanges = true; + }; + + /** + * @brief Structured range candidate for fixed range selection. + * + * `id` is preferred when available because it is stable across display label + * formatting changes. `label` is still stored for compatibility with device + * APIs that currently apply ranges by display label. `isCurrent` is for UI + * and explicit selection; it does not change fixed_range matching. + */ + struct RangeCandidate + { + std::string id; + std::string label; + SignalDomain domain = SignalDomain::VoltagePeak; + // Effective engineering magnitude used by selection logic. Device + // readback ranges prefer actualVp; profile-only ranges use the catalog + // label; device ranges without a real VP value may fall back to parsing + // the label and set magnitudeFromLabelFallback. + double magnitude = 0.0; + // Actual calibrated VP value read from device NewChannelVps. This is + // only meaningful when hasActualVp is true. + double actualVp = 0.0; + bool isDefault = false; + bool isCurrent = false; + bool hasActualVp = false; + bool magnitudeFromLabelFallback = false; + // False marks a manual/diagnostic range that auto policy must ignore. + bool autoSelectable = true; + // False marks a range whose VP calibration value is read-only. + bool vpWritable = true; + }; + + /** + * @brief High-level range selection policy used by Recorder/Capture builders. + * + * This type is intentionally immutable from the builder's perspective: + * callers construct it through factory helpers and the facade resolves the + * actual board-specific range label later, after the input measurement mode is applied. + */ + class DAQ_API_EXPORT RangePolicy + { + public: + static RangePolicy auto_select() + { + return RangePolicy(RangeSelectionMode::AutoSelect, + Optional(), + Optional(), + Optional(), + RangeAutoOptions{}); + } + + static RangePolicy auto_select(const ExpectedSignalHint& hint) + { + return RangePolicy(RangeSelectionMode::AutoSelect, + Optional(hint), + Optional(), + Optional(), + RangeAutoOptions{}); + } + + static RangePolicy keep_current_if_valid() + { + RangeAutoOptions options; + options.keepCurrentIfValid = true; + options.preferProfileDefaultWhenNoHint = false; + return RangePolicy(RangeSelectionMode::KeepCurrentIfValid, + Optional(), + Optional(), + Optional(), + options); + } + + static RangePolicy fixed_label(std::string label) + { + return RangePolicy(RangeSelectionMode::FixedLabel, + Optional(), + Optional(std::move(label)), + Optional(), + RangeAutoOptions{}); + } + + static RangePolicy fixed_range(RangeCandidate range) + { + return RangePolicy(RangeSelectionMode::FixedRange, + Optional(), + Optional(), + Optional(std::move(range)), + RangeAutoOptions{}); + } + + RangeSelectionMode mode() const noexcept + { + return mode_; + } + + const Optional& expected_signal_hint() const noexcept + { + return expectedSignalHint_; + } + + const Optional& fixed_label_value() const noexcept + { + return fixedLabel_; + } + + const Optional& fixed_range_value() const noexcept + { + return fixedRange_; + } + + const RangeAutoOptions& auto_options() const noexcept + { + return autoOptions_; + } + + bool requires_runtime_candidate_resolution() const noexcept + { + return mode_ != RangeSelectionMode::FixedLabel && + !(mode_ == RangeSelectionMode::FixedRange && + fixedRange_.has_value() && + fixedRange_->id.empty() && + !fixedRange_->label.empty()); + } + + private: + RangePolicy(RangeSelectionMode mode, + Optional expectedSignalHint, + Optional fixedLabel, + Optional fixedRange, + RangeAutoOptions autoOptions) noexcept + : mode_(mode) + , expectedSignalHint_(std::move(expectedSignalHint)) + , fixedLabel_(std::move(fixedLabel)) + , fixedRange_(std::move(fixedRange)) + , autoOptions_(autoOptions) + { + } + + RangeSelectionMode mode_ = RangeSelectionMode::AutoSelect; + Optional expectedSignalHint_; + Optional fixedLabel_; + Optional fixedRange_; + RangeAutoOptions autoOptions_; + }; + +} + +#endif // CRYDAQ_RANGE_POLICY_H +// END SDK HEADER: crydaq/range_policy.h + +namespace CryDaq +{ + class DAQ_API_EXPORT InputConfig + { + public: + static InputConfig voltage(RangePolicy rangePolicy = RangePolicy::keep_current_if_valid()) + { + return InputConfig(MeasurementMode::Voltage, std::move(rangePolicy)); + } + + static InputConfig iepe(RangePolicy rangePolicy = RangePolicy::keep_current_if_valid()) + { + return InputConfig(MeasurementMode::Iepe, std::move(rangePolicy)); + } + + static InputConfig charge(RangePolicy rangePolicy = RangePolicy::keep_current_if_valid()) + { + return InputConfig(MeasurementMode::Charge, std::move(rangePolicy)); + } + + static InputConfig lemo(RangePolicy rangePolicy = RangePolicy::keep_current_if_valid()) + { + return InputConfig(MeasurementMode::Lemo, std::move(rangePolicy)); + } + + InputConfig(MeasurementMode measurementMode = MeasurementMode::Voltage, + RangePolicy rangePolicy = RangePolicy::keep_current_if_valid()) + : measurementMode_(measurementMode) + , rangePolicy_(std::move(rangePolicy)) + { + } + + MeasurementMode measurement_mode() const noexcept + { + return measurementMode_; + } + + const RangePolicy& range_policy() const noexcept + { + return rangePolicy_; + } + + private: + MeasurementMode measurementMode_ = MeasurementMode::Voltage; + RangePolicy rangePolicy_ = RangePolicy::keep_current_if_valid(); + }; +} + +#endif // CRYDAQ_INPUT_CONFIG_H +// END SDK HEADER: crydaq/input_config.h + +// BEGIN SDK HEADER: crydaq/playback.h +#ifndef CRYDAQ_PLAYBACK_H +#define CRYDAQ_PLAYBACK_H + +#include +#include +#include +#include +#include +#include + + +// BEGIN SDK HEADER: crydaq/timing.h +#ifndef CRYDAQ_TIMING_H +#define CRYDAQ_TIMING_H + +#include +#include + + +namespace CryDaq +{ + enum class TimingMode : uint8_t + { + Finite = 0, + Continuous = 1, + }; + + class DAQ_API_EXPORT Timing + { + public: + static Timing finite(int sampleRate, std::chrono::milliseconds duration) noexcept + { + return Timing(TimingMode::Finite, sampleRate, duration, 0); + } + + static Timing finite_frames(int sampleRate, int64_t frameCount) noexcept; + + static Timing continuous(int sampleRate) noexcept + { + return Timing(TimingMode::Continuous, sampleRate, std::chrono::milliseconds(0), 0); + } + + TimingMode mode() const noexcept + { + return mode_; + } + + int sample_rate() const noexcept + { + return sampleRate_; + } + + std::chrono::milliseconds duration() const noexcept + { + return duration_; + } + + bool is_finite() const noexcept + { + return mode_ == TimingMode::Finite; + } + + bool is_continuous() const noexcept + { + return mode_ == TimingMode::Continuous; + } + + bool has_frame_count() const noexcept + { + return frameCount_ > 0; + } + + int64_t frame_count() const noexcept + { + return frameCount_; + } + + private: + + Timing(TimingMode mode, int sampleRate, std::chrono::milliseconds duration, int64_t frameCount) noexcept + : mode_(mode) + , sampleRate_(sampleRate) + , duration_(duration) + , frameCount_(frameCount) + { + } + + TimingMode mode_ = TimingMode::Finite; + int sampleRate_ = 0; + std::chrono::milliseconds duration_{0}; + int64_t frameCount_ = 0; + }; +} + +#endif // CRYDAQ_TIMING_H +// END SDK HEADER: crydaq/timing.h + +// BEGIN SDK HEADER: crydaq/playback_types.h +#ifndef CRYDAQ_PLAYBACK_TYPES_H +#define CRYDAQ_PLAYBACK_TYPES_H + + +namespace CryDaq +{ + + /** + * @brief 播放数据源(支持内存 PCM 或文件路径) + */ + struct PlaybackSource + { + enum class Kind : uint8_t + { + Memory = 0, ///< 内存数据 + FilePath ///< WAV 文件路径(当前仅支持 RawFs) + }; + + Kind kind = Kind::Memory; + + // Memory 模式使用:根据 PlayRequest::inputUnit 选择其一 + // Voltage 模式表示逐点瞬时电压样本 V(t),不是 RMS 幅值参数 + std::vector rawSamples; + std::vector voltageSamples; + + // FilePath 模式使用:UTF-8 路径,当前仅支持 RawFs WAV + std::string path; + }; + + /** + * @brief 播放条目:一个输出通道 + 对应的数据源 + */ + struct PlayItem + { + ChannelRef channel; ///< 输出通道 + PlaybackSource source; ///< 数据源(内存 or 文件) + }; + + /** + * @brief 播放请求(支持多设备多通道) + */ + struct PlayRequest + { + std::vector items; ///< 多设备多通道播放条目 + int fs = 0; ///< 采样率(Hz) + SampleUnit inputUnit = SampleUnit::RawFs; ///< 播放输入数据单位 + std::string pid; ///< 可选:播放ID,空则内部生成 + int64_t timeoutMs = -1; ///< 超时时间(ms),-1 表示不超时 + }; + + /***************************************************************** + ************************ 同步播放请求 ***************************** + *****************************************************************/ + + struct SyncPlaybackDeviceConfig + { + std::vector channelLocalIds; + std::string connectionString; + }; + + struct SyncPlaybackRecordAnchorRequest + { + std::string connectionString; ///< Read-only recording/reference device for the first-playback timestamp axis. + uint8_t boardId = 0; ///< Recording/reference board ID, 0-based. + int maxAnchorWallDeltaMs = 45; ///< Maximum receive-time delta between reference and playback board CNT samples. + }; + + struct SyncPlaybackAnchorSnapshot + { + std::string connectionString; + uint8_t boardId = 0; + bool recordReference = false; + bool playbackTarget = false; + bool valid = false; + uint64_t utc100ms = 0; + uint16_t cnt = 0; + uint16_t bucketCnt = 0; + uint16_t diffMod = 0; + int16_t delta = 0; + bool sameSoftwareBucket = false; + int64_t arrivalWallDeltaMs = 0; + bool recordTimeAxis = false; + uint64_t dacFirstUtc100msOnRecordAxis = 0; + uint16_t dacFirstCntOnRecordAxis = 0; + uint32_t dacFirstFrameOffset = 0; + }; + + struct SyncPlaybackScheduledAnchor + { + bool hasRecordTimeAxis = false; + std::string recordConnectionString; + uint8_t recordBoardId = 0; + uint64_t recordRefUtc100ms = 0; + uint16_t recordRefCnt = 0; + uint16_t playbackTargetCnt = 0; + // Generic SDK timestamp anchor: recording-board 100 ms time-axis + // bucket where the first DAC playback frame is scheduled. + // Locate the exact ADC sample in ChannelInData by finding a DataPoint with + // hasRecordFrameMarker=true, recordFrameStart=true, and matching recordUtc100ms. + uint64_t dacFirstUtc100msOnRecordAxis = 0; + // Sample offset from the matched recording-frame start to the first DAC frame. + // Current scheduled playback starts at the bucket boundary, so this is 0. + // Customer-specific delay samples require caller-chosen audio/correlation + // logic and are not part of this SDK anchor contract. + uint32_t dacFirstFrameOffset = 0; + int offsetCntForPlay = 0; + std::string anchorConfidence; + std::string message; + std::vector alignmentSnapshots; + }; + + enum class SyncPlaybackStopMode : uint8_t + { + Drain = 0, + Abort + }; + + enum class SyncPlaybackState : uint8_t + { + Created = 0, + WaitingForData, + Starting, + Running, + StopRequested, + Completed, + Stopped, + Failed, + Closed + }; + + enum class SyncPlaybackStage : uint8_t + { + Validating = 0, + Preparing, + Aligning, + WaitingForPrefill, + Prefilling, + Arming, + Streaming, + Draining, + Completed, + Failed + }; + + enum class ReferenceTimeResetPolicy : uint8_t + { + Never = 0, + Auto = 1, + Always = 2 + }; + + enum class PlaybackTransport : uint8_t + { + Zmq = 0, + OpenDaq = 1, + Auto = 2 + }; + + struct SyncPlaybackStartRequest + { + std::vector devices; + int sampleRate = 0; + SampleUnit inputUnit = SampleUnit::RawFs; + int offsetCntForPlay = 0; // Auto: capability-gated local CNT+4, otherwise 10. + // Zero permits arm before the first Write on reusable-capable devices. + int startupBufferMs = 500; + int maxQueuedBufferMs = 5000; + Optional recordAnchor; + std::vector recordAnchorCandidates; + std::vector recordAxisCandidates; + bool resetReferenceTimeAfterCntAlignment = false; + ReferenceTimeResetPolicy referenceTimeResetPolicy = ReferenceTimeResetPolicy::Never; + std::vector resetReferenceTimeConnections; + PlaybackTransport transport = PlaybackTransport::Zmq; + // Bounds preparation, prefill and arm, independently of Wait's polling timeout. + int64_t startupOperationTimeoutMs = 15000; + }; + + struct SyncPlaybackRequest + { + std::vector items; + int sampleRate = 0; + SampleUnit inputUnit = SampleUnit::RawFs; + int offsetCntForPlay = 0; // Auto: capability-gated local CNT+4, otherwise 10. + int64_t timeoutMs = -1; + Optional recordAnchor; + std::vector recordAnchorCandidates; + std::vector recordAxisCandidates; + bool resetReferenceTimeAfterCntAlignment = false; + ReferenceTimeResetPolicy referenceTimeResetPolicy = ReferenceTimeResetPolicy::Never; + std::vector resetReferenceTimeConnections; + PlaybackTransport transport = PlaybackTransport::Zmq; + }; + + struct SyncPlaybackWithRecordAnchorStartRequest + { + SyncPlaybackStartRequest playback; + SyncPlaybackRecordAnchorRequest recordAnchor; + std::vector recordAnchorCandidates; + std::vector recordAxisCandidates; + }; + + struct SyncPlaybackWithRecordAnchorRequest + { + SyncPlaybackRequest playback; + SyncPlaybackRecordAnchorRequest recordAnchor; + std::vector recordAnchorCandidates; + std::vector recordAxisCandidates; + }; + + struct SyncPlaybackChunkItem + { + ChannelRef channel; + std::vector rawSamples; + std::vector voltageSamples; + }; + + struct SyncPlaybackDataChunk + { + std::vector items; + }; + + struct SyncPlaybackBoardStatus + { + int boardDisplayId = 0; + int ret = 0; + std::string message; + std::string fifoState = "UNKNOWN"; + int64_t fifoAgeMs = -1; + bool softwareEmpty = false; + bool softwareEmptyKnown = false; + std::string controlState = "UNKNOWN"; + std::string operationId; + uint64_t generation = 0; + bool recoveryRequired = false; + std::string faultId; + std::string reason; + bool pauseConfirmed = false; + bool armMayBeActive = false; + bool prepared = false; + uint64_t latestUtc100ms = 0; + uint16_t latestCnt = 0; + int64_t cntAgeMs = -1; + std::string playbackPid; + }; + + struct SyncPlaybackDeviceStatus + { + std::string connectionString; + bool reusablePlaybackV1 = false; + bool localCnt4 = false; + std::string deviceEpoch; + uint64_t syncRevision = 0; + std::string alignmentState; + uint64_t alignmentUtc100ms = 0; + uint16_t alignmentCnt = 0; + int64_t alignmentAgeMs = -1; + std::vector boards; + }; + + struct SyncPlaybackRecoveryRequest + { + std::string connectionString; + std::vector boardDisplayIds; + std::string operationId; + uint64_t generation = 0; + std::string playbackPid; + std::string faultId; + }; + + struct SyncPlaybackStatus + { + std::string operationId; + PlaybackTransport requestedTransport = PlaybackTransport::Auto; + PlaybackTransport actualTransport = PlaybackTransport::Zmq; + std::string transportSelectionReason; + SyncPlaybackState state = SyncPlaybackState::Created; + SyncPlaybackStage stage = SyncPlaybackStage::Validating; + bool started = false; + bool stopRequested = false; + bool completed = false; + bool stopped = false; + Optional lastErrorCode; + Optional lastUpdatedTimeMs; + Optional queuedBufferMs; + Optional scheduledAnchor; + std::string message; + bool reusablePlayback = false; + bool armed = false; + // Never inferred from a successful arm command or elapsed host time. + bool physicalStarted = false; + bool recoveryRequired = false; + bool closed = false; + std::string failureReason; + Optional failedStage; + std::string cleanupError; + uint64_t generation = 0; + std::string playbackPid; + std::vector deviceStatuses; + }; + +} // namespace CryDaq + +#endif // CRYDAQ_PLAYBACK_TYPES_H +// END SDK HEADER: crydaq/playback_types.h + +// BEGIN SDK HEADER: crydaq/validation.h +#ifndef CRYDAQ_VALIDATION_H +#define CRYDAQ_VALIDATION_H + +#include +#include +#include + + +namespace CryDaq +{ + using ValidationIssue = SdkError; + + struct ValidationReport + { + bool ok = true; + std::vector issues; + + bool has_issues() const noexcept + { + return !ok || !issues.empty(); + } + + void add_issue(std::string code, + std::string message, + Optional channel = Optional(), + Optional remediation = Optional(), + ErrorCode errorCode = ErrorCode::InvalidParameter, + ErrorCategory category = ErrorCategory::Validation) + { + ok = false; + SdkError issue; + issue.category = category; + issue.severity = ErrorSeverity::Error; + issue.code = errorCode; + issue.issueCode = std::move(code); + issue.message = std::move(message); + issue.channel = std::move(channel); + issue.remediation = std::move(remediation); + issues.push_back(std::move(issue)); + } + }; +} + +#endif // CRYDAQ_VALIDATION_H +// END SDK HEADER: crydaq/validation.h + +namespace CryDaq +{ + namespace detail + { + class OrdinaryPlaybackOperation; + class OrdinaryPlaybackStreamRuntime; + class OrdinaryPlaybackTaskRuntime; + class PlaybackHandleAccess; + class SynchronizedPlaybackRuntime; + } + + enum class PlaybackState : uint8_t + { + Created = 0, + Starting, + Running, + Draining, + Canceling, + Completed, + Canceled, + Failed + }; + + enum class PlaybackStopMode : uint8_t + { + Drain = 0, + Abort = 1 + }; + + struct PlaybackAnchorOptions + { + std::vector recordChannels; + std::vector recordAxisChannels; + ReferenceTimeResetPolicy referenceTimeResetPolicy = ReferenceTimeResetPolicy::Never; + bool acknowledgeDataLoss = false; + bool resetPlaybackDevicesReferenceTime = false; + int maxAnchorWallDeltaMs = 45; + }; + + struct PlaybackSynchronization + { + int offsetCntForPlay = 0; // Auto: capability-gated local CNT+4, otherwise 10. + int startupBufferMs = 500; + int maxQueuedBufferMs = 5000; + int64_t startupOperationTimeoutMs = 15000; + Optional anchor; + }; + + struct PlaybackOptions + { + PlaybackTransport transport = PlaybackTransport::Zmq; + int64_t timeoutMs = -1; + int64_t cleanupTimeoutMs = 5000; + std::string pid; + Optional synchronization; + }; + + struct PlaybackStreamChunk + { + // RawFs samples in the same order as PlaybackStreamConfig::channels. + // Every channel must contain exactly frameCount samples. + std::size_t frameCount = 0; + std::vector> channels; + std::vector> voltageChannels; + }; + + struct PlaybackStreamConfig + { + std::vector channels; + SampleUnit inputUnit = SampleUnit::RawFs; + int sampleRate = 0; + std::string pid; + // Per-stream source queue limits. The SDK also enforces one shared + // process-wide playback memory budget across queued and in-flight data. + std::size_t maxQueuedFrames = 262144; + std::size_t maxQueuedBytes = 16u * 1024u * 1024u; + std::size_t maxChunkFrames = 16384; + }; + + struct PlaybackProgressValue + { + uint64_t value = 0; + bool valid = false; + }; + + struct PlaybackStatus + { + std::string operationId; + std::string pid; + PlaybackState state = PlaybackState::Created; + std::string stage = "Created"; + PlaybackTransport requestedTransport = PlaybackTransport::Auto; + PlaybackTransport actualTransport = PlaybackTransport::Auto; + bool actualTransportValid = false; + std::string transportSelectionReason; + std::string connectionGeneration; + ErrorCode errorCode = ErrorCode::Success; + ErrorCategory errorCategory = ErrorCategory::Unknown; + std::string errorIssueCode; + std::string errorMessage; + std::vector cleanupDiagnostics; + uint64_t framesRead = 0; + uint64_t framesAccepted = 0; + uint64_t framesQueued = 0; + uint64_t framesSent = 0; + PlaybackProgressValue receivedOffset; + PlaybackProgressValue acceptedOffset; + PlaybackProgressValue committedOffset; + PlaybackProgressValue playedOffset; + PlaybackProgressValue creditFrames; + uint64_t peakQueuedFrames = 0; + uint64_t peakQueuedBytes = 0; + std::string lastBackpressureReason; + bool crashCleanupGuaranteed = false; + bool generationIsolationGuaranteed = false; + Optional synchronization; + }; + + class DAQ_API_EXPORT PlaybackControl + { + public: + PlaybackControl(); + ~PlaybackControl(); + PlaybackControl(const PlaybackControl& other) noexcept; + PlaybackControl& operator=(const PlaybackControl& other) noexcept; + PlaybackControl(PlaybackControl&& other) noexcept; + PlaybackControl& operator=(PlaybackControl&& other) noexcept; + + PlaybackStatus GetStatus() const; + Result Cancel(); + std::string OperationId() const; + + private: + struct Impl; + std::shared_ptr impl_; + friend class detail::PlaybackHandleAccess; + }; + + class DAQ_API_EXPORT PlaybackTask + { + public: + PlaybackTask() noexcept; + ~PlaybackTask(); + PlaybackTask(const PlaybackTask&) = delete; + PlaybackTask& operator=(const PlaybackTask&) = delete; + PlaybackTask(PlaybackTask&& other) noexcept; + PlaybackTask& operator=(PlaybackTask&& other) noexcept; + + PlaybackStatus GetStatus() const; + Result Wait(int64_t timeoutMs = -1) const; + Result Cancel(); + Result Close(); + std::string OperationId() const; + + private: + struct Impl; + explicit PlaybackTask( + std::shared_ptr operation, + std::shared_ptr runtime = {}, + int64_t cleanupTimeoutMs = 5000); + explicit PlaybackTask(std::shared_ptr synchronized); + std::unique_ptr impl_; + friend class detail::PlaybackHandleAccess; + }; + + class DAQ_API_EXPORT PlaybackStream + { + public: + PlaybackStream() noexcept; + ~PlaybackStream(); + PlaybackStream(const PlaybackStream&) = delete; + PlaybackStream& operator=(const PlaybackStream&) = delete; + PlaybackStream(PlaybackStream&& other) noexcept; + PlaybackStream& operator=(PlaybackStream&& other) noexcept; + + PlaybackStatus GetStatus() const; + Result Wait(int64_t timeoutMs = -1) const; + // Success means local bounded-queue acceptance, not device receipt. + // A timeout leaves chunk unaccepted and safe for the caller to retry. + Result Write(const PlaybackStreamChunk& chunk, int64_t timeoutMs = -1); + // Requests stop without waiting. Use Wait to observe completion and Close for cleanup. + Result Stop(PlaybackStopMode mode); + Result Cancel(); + Result Close(); + std::string OperationId() const; + + private: + struct Impl; + explicit PlaybackStream( + std::shared_ptr operation, + std::shared_ptr runtime = {}, + int64_t cleanupTimeoutMs = 5000); + explicit PlaybackStream(std::shared_ptr synchronized); + std::unique_ptr impl_; + friend class detail::PlaybackHandleAccess; + }; + + struct PlaybackRecordAnchorResult + { + SyncPlaybackStatus status; + SyncPlaybackRecordAnchorRequest selectedRecordAnchor; + }; + + +} + +#endif // CRYDAQ_PLAYBACK_H +// END SDK HEADER: crydaq/playback.h + +// BEGIN SDK HEADER: crydaq/record_output_template.h +#ifndef CRYDAQ_RECORD_OUTPUT_TEMPLATE_H +#define CRYDAQ_RECORD_OUTPUT_TEMPLATE_H + + +#include +#include +#include + +namespace CryDaq +{ + struct RecordOutputTemplateField + { + std::string name; + std::string placeholder; + std::string category; + std::string description; + std::string example; + }; + + struct RecordOutputTemplateFieldValue + { + std::string name; + std::string placeholder; + std::string category; + std::string description; + std::string value; + }; + + struct RecordOutputTemplatePreviewContext + { + std::string filepathTemplate; ///< UTF-8 host path template. + + std::string operation = "record"; + std::string sessionId; + std::string pid; + int sampleRate = 0; + int bitDepth = 32; + int64_t durationMs = 0; + + std::string connection; + std::string deviceName; + std::string channel; + int channelIndex = 1; + std::string channelType = "input"; + std::string group; + + std::string date; + std::string time; + std::string datetime; + std::string utcdate; + std::string utctime; + std::string utcdatetime; + std::string timestampMs; + std::string timezone; + + std::string computerName; + std::string userName; + std::string processId; + std::string sdkVersion; + }; + + struct RecordOutputTemplatePreview + { + std::string filepath; + std::vector fields; + }; + + DAQ_API_EXPORT std::vector record_output_template_fields(); + + DAQ_API_EXPORT Result preview_record_output_template( + const RecordOutputTemplatePreviewContext& context); +} + +#endif // CRYDAQ_RECORD_OUTPUT_TEMPLATE_H +// END SDK HEADER: crydaq/record_output_template.h + +// BEGIN SDK HEADER: crydaq/signal_generator.h +#ifndef CRYDAQ_SIGNAL_GENERATOR_H +#define CRYDAQ_SIGNAL_GENERATOR_H + +#include +#include +#include +#include + + +namespace CryDaq +{ + class CRYDaqInstance; + class CRYHttpClient; + struct GeneralDeviceInfo; + struct DetailDeviceInfo; + + enum class SignalGeneratorWaveform + { + Sine, + Square, + Noise, + DualTone, + MultiTone, + Random, + SineOnRandom, + TimeDomain, + MultiAxis + }; + + enum class SignalGeneratorNoiseShape + { + White, + Pink + }; + + enum class SignalGeneratorLevelUnit + { + Vrms, + DBV + }; + + enum class SignalGeneratorStopMode + { + Drain, + Abort + }; + + enum class SignalGeneratorRandomShapeMode + { + RelativeDb, + AbsolutePsd + }; + + enum class SignalGeneratorRandomChannelMode + { + Uncorrelated, + Correlated + }; + + enum class SignalGeneratorMultiAxisSource + { + Sine, + Random + }; + + struct SignalGeneratorLevelConfig + { + std::string channelId; + double frequency = 1000.0; + double level = 0.05; + SignalGeneratorLevelUnit unit = SignalGeneratorLevelUnit::Vrms; + double dcOffset = 0.0; + std::string dcOffsetUnit = "V"; + double phase = 0.0; + std::string phaseUnit = "deg"; + }; + + struct SignalGeneratorDualToneSignal + { + double frequency = 1000.0; + double level = 0.05; + SignalGeneratorLevelUnit levelUnit = SignalGeneratorLevelUnit::Vrms; + double phase = 0.0; + std::string phaseUnit = "deg"; + }; + + struct SignalGeneratorDualToneConfig + { + bool normalize = true; + SignalGeneratorDualToneSignal signal1; + SignalGeneratorDualToneSignal signal2; + }; + + struct SignalGeneratorMultiToneConfig + { + double startFrequency = 100.0; + double endFrequency = 10000.0; + std::string octaveResolution = "1/3 Oct"; + int octaveDiv = 3; + double overallLevel = 0.05; + SignalGeneratorLevelUnit levelUnit = SignalGeneratorLevelUnit::Vrms; + double phase = 0.0; + }; + + struct SignalGeneratorRandomProfilePoint + { + double frequency = 0.0; + double value = 0.0; + }; + + struct SignalGeneratorRandomConfig + { + double level = 0.05; + SignalGeneratorLevelUnit levelUnit = SignalGeneratorLevelUnit::Vrms; + SignalGeneratorNoiseShape noiseShape = SignalGeneratorNoiseShape::White; + SignalGeneratorRandomShapeMode shapeMode = SignalGeneratorRandomShapeMode::RelativeDb; + std::vector profile; + std::uint64_t seed = 1; + std::uint32_t frameSize = 2048; + std::uint32_t hopSize = 1024; + bool crestFactorLimitEnabled = false; + std::uint32_t crestFactorIterations = 8; + double dcOffset = 0.0; + std::string dcOffsetUnit = "V"; + }; + + struct SignalGeneratorSineOnRandomConfig + { + SignalGeneratorRandomConfig random; + double toneRampTime = 0.0; + std::vector tones; + }; + + struct SignalGeneratorTimeDomainConfig + { + std::vector samples; + bool loop = true; + double gain = 1.0; + double offset = 0.0; + double dcOffset = 0.0; + std::string dcOffsetUnit = "V"; + }; + + struct SignalGeneratorMultiAxisSineConfig + { + double frequency = 1000.0; + double level = 0.05; + SignalGeneratorLevelUnit levelUnit = SignalGeneratorLevelUnit::Vrms; + double phase = 0.0; + std::string phaseUnit = "deg"; + double dcOffset = 0.0; + std::string dcOffsetUnit = "V"; + }; + + struct SignalGeneratorMultiAxisRandomConfig + { + SignalGeneratorRandomConfig random; + SignalGeneratorRandomChannelMode randomChannelMode = + SignalGeneratorRandomChannelMode::Uncorrelated; + std::vector correlationMatrix; + }; + + struct SignalGeneratorMultiAxisConfig + { + SignalGeneratorMultiAxisSource source = SignalGeneratorMultiAxisSource::Sine; + SignalGeneratorMultiAxisSineConfig sine; + SignalGeneratorMultiAxisRandomConfig random; + }; + + struct SignalGeneratorConfig + { + std::vector outputChannels; + SignalGeneratorWaveform waveform = SignalGeneratorWaveform::Sine; + Optional noiseShape; + double frequency = 1000.0; + bool useSeparatePara = true; + std::vector levelConfigs; + Optional dualToneConfig; + Optional multiToneConfig; + Optional randomConfig; + Optional sineOnRandomConfig; + Optional timeDomainConfig; + Optional multiAxisConfig; + }; + + class DAQ_API_EXPORT CRYSignalGenerator + { + public: + // Base-URL-only objects support query/configuration APIs. Start() requires + // a device connection binding and fails locally for this constructor. + explicit CRYSignalGenerator(const std::string& baseUrl); + CRYSignalGenerator( + std::shared_ptr instance, + const std::string& connectionString, + int port = 0); + ~CRYSignalGenerator(); + + CRYSignalGenerator(const CRYSignalGenerator&) = delete; + CRYSignalGenerator& operator=(const CRYSignalGenerator&) = delete; + CRYSignalGenerator(CRYSignalGenerator&& other) noexcept; + CRYSignalGenerator& operator=(CRYSignalGenerator&& other) noexcept; + + void SetBaseUrl(const std::string& baseUrl); + + std::string GetCapabilitiesJson(); + std::string GetChannelInventoryJson(); + std::string GetConfigJson(); + bool SetConfig(const SignalGeneratorConfig& config); + bool SetConfigJson(const std::string& configJson); + // Requires the bound SDK device connection to remain active. + bool Start(); + // Stops the device's current Generator output, including output started + // by an earlier SDK connection or another Generator object. + bool Stop(SignalGeneratorStopMode mode = SignalGeneratorStopMode::Drain); + // Reads the current device Generator state rather than local ownership. + bool IsActive() const noexcept; + std::string GetStatusJson(); + std::string GetDiagnosticsJson(); + + std::string GetLastError() const; + int GetLastStatusCode() const; + + static std::string ConfigToJson(const SignalGeneratorConfig& config); + static std::string HttpBaseUrlFromDeviceInfo( + const GeneralDeviceInfo& device, + int port = 0); + static std::string HttpBaseUrlFromDeviceInfo( + const DetailDeviceInfo& device, + int port = 0); + static std::string HttpBaseUrlFromConnectionString( + const std::string& connectionString, + int port = 0, + bool resolveHostname = true); + + private: + std::string m_baseUrl; + std::string m_lastError; + int m_lastStatusCode = 0; + std::unique_ptr m_httpClient; + + std::string getJsonPath(const std::string& path); + bool postJsonPath( + const std::string& path, + const std::string& body); + }; +} + +#endif // CRYDAQ_SIGNAL_GENERATOR_H +// END SDK HEADER: crydaq/signal_generator.h + +// BEGIN SDK HEADER: crydaq/teds.h +#ifndef CRYDAQ_TEDS_H +#define CRYDAQ_TEDS_H + + +#include + +namespace CryDaq +{ + class DAQ_API_EXPORT TedsCodec + { + public: + static Result parse(const std::string& hexData); + // Exactly eight bytes in firmware order [CRC, serial MSB..LSB, family]. + // CRC/family failures are reported in JSON, malformed hex fails the Result. + static Result parse_rom(const std::string& hexData); + static Result build(const std::string& jsonData); + }; +} + +#endif // CRYDAQ_TEDS_H +// END SDK HEADER: crydaq/teds.h + +// BEGIN SDK HEADER: crydaq/workflow/types.h +#ifndef CRYDAQ_WORKFLOW_TYPES_H +#define CRYDAQ_WORKFLOW_TYPES_H + +#include +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace detail +{ + class LegacySession; + class LegacyRuntime; + struct SessionAccess; +} + +namespace workflow +{ + + enum class DeviceOpenMode : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Shared = 0, + Exclusive = 1, + ForceExclusive = 2, + }; + + enum class InstancePolicy : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Owned = 0, + External = 1, + }; + + struct DeviceRef + { + std::string deviceId; + }; + + struct ChannelRef + { + std::string deviceId; + std::string channelName; + }; + + struct SignalRef + { + std::string deviceId; + std::string signalId; + }; + + struct DeviceOpenRequest + { + std::string connectionString; + DeviceOpenMode mode = DeviceOpenMode::Exclusive; + Optional clientName; + }; + + enum class ConfigValueKind : uint8_t + { + None = 0, + Enum, + Boolean, + Number, + Text, + }; + + struct ConfigValue + { + ConfigValueKind kind = ConfigValueKind::None; + std::string stringValue; + bool boolValue = false; + double numberValue = 0.0; + + static ConfigValue enum_value(std::string value) + { + ConfigValue result; + result.kind = ConfigValueKind::Enum; + result.stringValue = std::move(value); + return result; + } + + static ConfigValue boolean_value(bool value) + { + ConfigValue result; + result.kind = ConfigValueKind::Boolean; + result.boolValue = value; + result.stringValue = value ? "true" : "false"; + return result; + } + + static ConfigValue number_value(double value) + { + ConfigValue result; + result.kind = ConfigValueKind::Number; + result.numberValue = value; + result.stringValue = std::to_string(value); + return result; + } + + static ConfigValue text_value(std::string value) + { + ConfigValue result; + result.kind = ConfigValueKind::Text; + result.stringValue = std::move(value); + return result; + } + }; + + enum class ConfigDimensionVisibility : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + UserVisible = 0, + Derived = 1, + Internal = 2, + DebugOnly = 3, + }; + + enum class ConfigDimensionScope : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Channel = 0, + Device = 1, + Board = 2, + }; + + enum class ConfigDimensionSyncPolicy : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + TargetOnly = 0, + AllChannels = 1, + SameFrontendGroup = 2, + }; + + enum class ConfigValueType : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Enum = 0, + Boolean = 1, + Number = 2, + Text = 3, + }; + + struct ConfigValueOption + { + std::string id; + std::string label; + }; + + struct ConfigPropertyMap + { + std::string route; + std::string propertyName; + std::map valueMap; + }; + + struct ConfigDimensionForcedValueRule + { + std::vector conditions; + ConfigValue value; + std::string reason; + }; + + struct ConfigDimension + { + std::string key; + std::string displayName; + ConfigDimensionVisibility visibility = ConfigDimensionVisibility::UserVisible; + bool userSettable = false; + ConfigDimensionScope scope = ConfigDimensionScope::Channel; + ConfigDimensionSyncPolicy syncPolicy = ConfigDimensionSyncPolicy::TargetOnly; + ConfigValueType valueType = ConfigValueType::Enum; + std::vector values; + std::vector affects; + ConfigPropertyMap property; + int applyOrder = 100; + std::vector refreshAfterApply; + bool verify = true; + std::vector visibleWhen; + std::vector writableWhen; + std::vector forcedValues; + std::string hiddenReason; + std::string disabledReason; + }; + + struct CapabilityContext + { + std::map options; + }; + + struct ConfigDimensionQuery + { + CapabilityContext context; + }; + + struct ConfigDimensionState + { + ConfigDimension dimension; + bool visible = true; + bool writable = true; + Optional effectiveValue; + std::string reason; + }; + + struct RangeDescriptor + { + std::string id; + std::string label; + std::string direction; + std::string mode; + std::vector factoryStages; + std::vector channels; + std::string gain; + std::vector actions; + std::string domain; + double engineeringMagnitude{0.0}; + std::string vpSelector; + double vpScale{0.0}; + bool vpReadOnly{false}; + bool autoSelectable{true}; + }; + + struct ModeViewDescriptor + { + std::string id; + std::string label; + std::vector conditions; + std::vector visibleRangeIds; + std::map rangeLabels; + }; + + enum class VpRangeWriteStrategy : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + LegacyAggregate = 0, + SdkAtomicCommands = 1, + AutoProbe = 2, + }; + + struct ProfileDescriptor + { + std::string profileId; + int profileVersion = 0; + std::string displayName; + BoardType boardType = BoardType::Unknown; + ChannelType channelType = ChannelType::Input; + std::vector rawBoardTypeIds; + int firstChannelIndex = 0; + int lastChannelIndex = 0; + std::string rangeProfileId; + VpRangeWriteStrategy vpRangeWriteStrategy = VpRangeWriteStrategy::LegacyAggregate; + std::vector sampleRatesHz; + std::vector ranges; + std::vector modeViews; + std::map> measurementModeRecipes; + std::vector configDimensions; + + DAQ_API_EXPORT bool matches(BoardType board, ChannelType channel, int channelIndex) const; + + DAQ_API_EXPORT bool matches_raw_board_type_id(int rawBoardTypeId, ChannelType channel, int channelIndex) const; + }; + + struct BoardConfigOptions + { + std::string profileId; + int profileVersion = 0; + std::string displayName; + BoardType boardType = BoardType::Unknown; + ChannelType channelType = ChannelType::Input; + std::vector rawBoardTypeIds; + int firstChannelIndex = 0; + int lastChannelIndex = 0; + std::string rangeProfileId; + VpRangeWriteStrategy vpRangeWriteStrategy = VpRangeWriteStrategy::LegacyAggregate; + std::vector sampleRatesHz; + std::vector ranges; + std::vector dimensions; + }; + + DAQ_API_EXPORT int channel_index_from_channel_name(const std::string& channelName); + + struct ProfileCatalog + { + std::string catalogId; + std::string catalogVersion; + std::vector profiles; + + DAQ_API_EXPORT Optional find_profile(const std::string& profileId) const; + + DAQ_API_EXPORT Optional find_profile_for(BoardType boardType, + ChannelType channelType, + const std::string& channelName) const; + + DAQ_API_EXPORT Optional find_profile_for_raw_board_type_id(int rawBoardTypeId, + ChannelType channelType, + const std::string& channelName) const; + + DAQ_API_EXPORT Optional profile_for_channel(const ChannelInfo& channel) const; + + DAQ_API_EXPORT Optional board_config_options_for(BoardType boardType, + ChannelType channelType, + const std::string& channelName) const; + + DAQ_API_EXPORT Optional board_config_options_for_raw_board_type_id(int rawBoardTypeId, + ChannelType channelType, + const std::string& channelName) const; + + DAQ_API_EXPORT Optional find_user_settable_dimension(const std::string& key) const; + + static DAQ_API_EXPORT BoardConfigOptions board_config_options_from_profile(const ProfileDescriptor& profile); + + static DAQ_API_EXPORT Result from_toml(const std::string& tomlText); + static DAQ_API_EXPORT ProfileCatalog sdk_default(); + }; + + DAQ_API_EXPORT int board_index_from_channel_name(const std::string& channelName); + + DAQ_API_EXPORT std::string board_key_from_channel_name(const std::string& channelName); + + + + DAQ_API_EXPORT SdkError make_error(ErrorCategory category, + ErrorCode code, + std::string issueCode, + std::string message); +} +} + +#endif // CRYDAQ_WORKFLOW_TYPES_H +// END SDK HEADER: crydaq/workflow/types.h + +// BEGIN SDK HEADER: crydaqsync_types.h +#ifndef CRYDAQ_SYNC_TYPES_H +#define CRYDAQ_SYNC_TYPES_H + +#include +#include +#include + + +namespace CryDaq +{ + enum class ErrorCode : int; + constexpr int64_t kDefaultSynchronizationTimeoutMs = 120000; + + /** + * @brief Synchronization mode requested by the application. + * + * `Normal` means disabling synchronization and returning to default clock mode. + * `Ptp` and `Gps` are mutually exclusive clock synchronization modes. + */ + enum class SyncMode : uint8_t + { + Normal = 0, + Ptp = 1, + Gps = 2, + }; + + /** + * @brief PTP role reported by the device or requested by the application. + */ + enum class PtpRole : uint8_t + { + Master = 0, + Slave = 1, + Unknown = 2, + }; + + /** + * @brief Fine-grained progress stage for synchronization tasks. + * + * This is intended for progress display and diagnostics while a long-running + * synchronization task is in flight. + */ + enum class SyncTaskStage : uint8_t + { + Preparing = 0, + EnablingGnss, + WaitingGnssFix, + SwitchingToNormal, + SwitchingToPtp, + SwitchingToGps, + ConfiguringPtpRoles, + WaitingSyncLock, + ResettingReferenceTime, + Completed, + Failed, + Cancelled, + }; + + /** + * @brief Coarse-grained lifecycle state of a synchronization task. + */ + enum class SyncTaskState : uint8_t + { + Created = 0, + Running, + CancelRequested, + Cancelled, + Completed, + Failed, + TimedOut, + }; + + /** + * @brief Synchronization capabilities exposed by a device. + * + * These fields describe whether the current device supports the corresponding + * synchronization mode or auxiliary control points. + */ + struct DeviceSyncCapabilities + { + bool supportsPtpMode = false; + bool supportsGpsMode = false; + bool supportsGnssControl = false; + bool supportsPtpRoleControl = false; + bool supportsResetReferenceTime = false; + }; + + /** + * @brief Per-device configuration used in synchronization requests. + * + * The task-level target mode is stored in `MultiDeviceSyncRequest::targetMode`. + * This structure holds only per-device overrides and preferences. + */ + struct DeviceSyncConfig + { + std::string connectionString; + Optional requestedPtpRole; + bool enableGnssIfNeeded = true; + bool keepGnssEnabledInPtpMode = true; + int64_t settleTimeoutMs = kDefaultSynchronizationTimeoutMs; + }; + + /** + * @brief Latest synchronization snapshot of a single device. + * + * This structure is used by both direct status queries and long-running task + * progress reporting. + */ + struct DeviceSyncStatus + { + std::string connectionString; + SyncMode targetMode = SyncMode::Normal; + SyncMode effectiveMode = SyncMode::Normal; + bool synchronized = false; + Optional syncStatusString; + SyncTaskStage stage = SyncTaskStage::Preparing; + std::string message; + Optional lastErrorCode; + Optional lastUpdatedTimeMs; + Optional stableSinceTimeMs; + Optional ptpRole; + Optional sysOffsetNs; + Optional phaseOffsetNs; + Optional gnssStatus; + }; + + /** + * @brief Request for configuring synchronization across one or more devices. + * + * All devices in a single request must belong to the same target synchronization + * mode. When `targetMode` is `Ptp`, the application may optionally designate + * exactly one master device via `designatedMasterConnectionString`. + */ + struct MultiDeviceSyncRequest + { + SyncMode targetMode = SyncMode::Normal; + std::vector devices; + Optional designatedMasterConnectionString; + bool autoResetReferenceTime = true; + int64_t waitTimeoutMs = kDefaultSynchronizationTimeoutMs; + int64_t pollIntervalMs = 1000; + int stableWindowMs = 3000; + }; + + /** + * @brief Aggregated result of a synchronization task. + * + * This structure can represent an in-progress snapshot or the final result of a + * finished task. + */ + struct MultiDeviceSyncResult + { + std::string operationId; + SyncTaskState state = SyncTaskState::Created; + std::vector deviceStatuses; + bool allSynchronized = false; + bool completed = false; + bool timedOut = false; + bool cancelled = false; + std::string message; + }; +} + +#endif +// END SDK HEADER: crydaqsync_types.h + +#endif // SONODAQ_COMPACT_COMMON_H diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/opendaq_interop.h b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/opendaq_interop.h new file mode 100644 index 0000000..62e7ce1 --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/opendaq_interop.h @@ -0,0 +1,119 @@ +// Generated by amalgamate_cpp_sdk_headers.py; do not edit. +#ifndef SONODAQ_COMPACT_OPENDAQ_INTEROP_H +#define SONODAQ_COMPACT_OPENDAQ_INTEROP_H +#include + +// BEGIN SDK HEADER: opendaq_interop.h +#ifndef CRYDAQ_OPENDAQ_INTEROP_H +#define CRYDAQ_OPENDAQ_INTEROP_H + +// Optional native access. Requires the matching openDAQ SDK headers and libraries. + +// BEGIN SDK HEADER: crydaq/primitive/opendaq_interop.h +#ifndef SONODAQ_COMPACT_FILE_5DB8BC662D1B56671A30 +#define SONODAQ_COMPACT_FILE_5DB8BC662D1B56671A30 + +#include +#include +#include + +#include +#include + + +// BEGIN SDK HEADER: crydaq/primitive/opendaq_interop_build.h +#ifndef SONODAQ_COMPACT_FILE_0CABE83688F6A68020FE +#define SONODAQ_COMPACT_FILE_0CABE83688F6A68020FE + +#define CRYDAQ_OPENDAQ_INTEROP_API_VERSION 1u +#define CRYDAQ_OPENDAQ_PACKAGE_VERSION "3.40.3-7e8fe742" +#define CRYDAQ_OPENDAQ_PACKAGE_SHA256 "b27b3932fd24dd9935574345abd992714970b07c0ccb140584facc38568fd91b" +#define CRYDAQ_OPENDAQ_PACKAGE_PLATFORM "macos-arm64" +#endif // SONODAQ_COMPACT_FILE_0CABE83688F6A68020FE +// END SDK HEADER: crydaq/primitive/opendaq_interop_build.h + + +namespace CryDaq +{ + namespace workflow + { + class MeasurementSession; + } + + namespace primitive + { + namespace opendaq + { + struct InteropIdentity + { + std::uint32_t apiVersion = 0; + std::string openDaqPackageVersion; + std::string openDaqPackageSha256; + std::string platform; + + friend bool operator==(const InteropIdentity& lhs, const InteropIdentity& rhs) + { + return lhs.apiVersion == rhs.apiVersion && + lhs.openDaqPackageVersion == rhs.openDaqPackageVersion && + lhs.openDaqPackageSha256 == rhs.openDaqPackageSha256 && + lhs.platform == rhs.platform; + } + + friend bool operator!=(const InteropIdentity& lhs, const InteropIdentity& rhs) + { + return !(lhs == rhs); + } + }; + + inline InteropIdentity caller_interop_identity() + { + return {CRYDAQ_OPENDAQ_INTEROP_API_VERSION, + CRYDAQ_OPENDAQ_PACKAGE_VERSION, + CRYDAQ_OPENDAQ_PACKAGE_SHA256, + CRYDAQ_OPENDAQ_PACKAGE_PLATFORM}; + } + + class SessionAccess; + + class DAQ_API_EXPORT OpenDaqAccessLease final + { + public: + OpenDaqAccessLease() noexcept; + OpenDaqAccessLease(OpenDaqAccessLease&& other) noexcept; + OpenDaqAccessLease& operator=(OpenDaqAccessLease&& other) noexcept; + ~OpenDaqAccessLease(); + + OpenDaqAccessLease(const OpenDaqAccessLease&) = delete; + OpenDaqAccessLease& operator=(const OpenDaqAccessLease&) = delete; + + daq::IInstance* instance() const noexcept; + daq::IDevice* device() const noexcept; + const std::string& connection_string() const noexcept; + std::uint64_t generation() const noexcept; + bool is_current() const noexcept; + explicit operator bool() const noexcept; + + private: + class Impl; + explicit OpenDaqAccessLease(std::unique_ptr impl) noexcept; + + std::unique_ptr impl_; + friend class SessionAccess; + }; + + DAQ_API_EXPORT InteropIdentity sdk_interop_identity(); + + DAQ_API_EXPORT Result acquire_native_access( + const CryDaq::workflow::MeasurementSession& session, + const std::string& connectionString, + const InteropIdentity& callerIdentity); + } + } +} +#endif // SONODAQ_COMPACT_FILE_5DB8BC662D1B56671A30 +// END SDK HEADER: crydaq/primitive/opendaq_interop.h + +#endif // CRYDAQ_OPENDAQ_INTEROP_H +// END SDK HEADER: opendaq_interop.h + +#endif // SONODAQ_COMPACT_OPENDAQ_INTEROP_H diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/primitive.h b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/primitive.h new file mode 100644 index 0000000..c2ae591 --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/primitive.h @@ -0,0 +1,1471 @@ +// Generated by amalgamate_cpp_sdk_headers.py; do not edit. +#ifndef SONODAQ_COMPACT_PRIMITIVE_H +#define SONODAQ_COMPACT_PRIMITIVE_H +#include + +// BEGIN SDK HEADER: primitive.h +#ifndef CRYDAQ_PRIMITIVE_H +#define CRYDAQ_PRIMITIVE_H + +// CryDAQ Primitive API umbrella. +// +// Include this header when application code wants the low-level public domain: +// +// #include +// +// Includes every public category controller, opaque instance creation, +// device system management, and shared utilities. Native openDAQ interop +// remains an explicit opt-in requiring the matching openDAQ SDK. + + +// BEGIN SDK HEADER: crydaq/primitive.h +#ifndef CRYDAQ_PRIMITIVE_API_H +#define CRYDAQ_PRIMITIVE_API_H + +// CryDAQ Primitive API: expert-only low-level and long-task primitives. +// Raw CRYDaqInstance escape hatch is intentionally explicit: +// include only when the category controllers are insufficient. +// New projects should prefer for acquisition/playback/config tasks. + + +// BEGIN SDK HEADER: crydaq/primitive/authorization.h +#ifndef CRYDAQ_PRIMITIVE_AUTHORIZATION_H +#define CRYDAQ_PRIMITIVE_AUTHORIZATION_H + + +#include +#include +#include + + +// BEGIN SDK HEADER: crydaq/primitive/detail/controller_base.h +#ifndef CRYDAQ_PRIMITIVE_DETAIL_CONTROLLER_BASE_H +#define CRYDAQ_PRIMITIVE_DETAIL_CONTROLLER_BASE_H + +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace detail +{ + class ControllerBase + { + public: + ControllerBase() = default; + + explicit ControllerBase(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) noexcept + : instance_(std::move(instance)) + { + } + + explicit operator bool() const noexcept + { + return static_cast(instance_); + } + + protected: + std::shared_ptr<::CryDaq::CRYDaqInstance> shared_instance() const noexcept + { + return instance_; + } + + ::CryDaq::CRYDaqInstance* instance_ptr() const noexcept + { + return instance_.get(); + } + + private: + std::shared_ptr<::CryDaq::CRYDaqInstance> instance_; + }; +} +} +} + +#endif // CRYDAQ_PRIMITIVE_DETAIL_CONTROLLER_BASE_H +// END SDK HEADER: crydaq/primitive/detail/controller_base.h + +// BEGIN SDK HEADER: crydaq/string_view.h +#ifndef CRYDAQ_STRING_VIEW_H +#define CRYDAQ_STRING_VIEW_H + +#if defined(_MSVC_LANG) +#define CRYDAQ_CPP_LANG_VERSION _MSVC_LANG +#else +#define CRYDAQ_CPP_LANG_VERSION __cplusplus +#endif + +#if CRYDAQ_CPP_LANG_VERSION >= 201703L +#include +#endif + +namespace CryDaq +{ +#if CRYDAQ_CPP_LANG_VERSION >= 201703L + using StringView = std::string_view; +#else + using StringView = const char*; +#endif +} + +#undef CRYDAQ_CPP_LANG_VERSION + +#endif // CRYDAQ_STRING_VIEW_H +// END SDK HEADER: crydaq/string_view.h + +namespace CryDaq +{ +namespace primitive +{ +namespace authorization +{ + static constexpr ::CryDaq::StringView kCategory = "authorization"; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::ErrorCode get_machine_code(const std::string& connectionString, + std::string& machineCode) const; + + ::CryDaq::ErrorCode write_authorization_info(const std::string& connectionString, + const std::string& authorizationInfo) const; + + ::CryDaq::ErrorCode read_authorization_info(const std::string& connectionString, + std::string& authorizationInfo) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_AUTHORIZATION_H +// END SDK HEADER: crydaq/primitive/authorization.h + +// BEGIN SDK HEADER: crydaq/primitive/capture.h +#ifndef CRYDAQ_PRIMITIVE_CAPTURE_H +#define CRYDAQ_PRIMITIVE_CAPTURE_H + + +// Unified finite capture tasks and callback-oriented capture streams. + +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace capture +{ + static constexpr ::CryDaq::StringView kCategory = "capture"; + + using ::CryDaq::AlignGroupConfig; + using ::CryDaq::AlignedPcmData; + using ::CryDaq::AsyncCaptureOptions; + using ::CryDaq::ChannelInData; + using ::CryDaq::DeviceChannelsConfig; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + Result start(const RecordRequest& source) const; + Result run(const RecordRequest& source) const; + + ::CryDaq::ErrorCode set_data_callback(::CryDaq::DataCallback callback) const; + + ::CryDaq::ErrorCode set_aligned_pcm_callback(::CryDaq::AlignedPcmCallback callback) const; + + Result open_stream(const std::vector& channels, + const AsyncCaptureOptions& options = {}) const; + + ::CryDaq::Optional is_channel_busy(const std::string& connectionString, const std::string& channelLocalId) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_CAPTURE_H +// END SDK HEADER: crydaq/primitive/capture.h + +// BEGIN SDK HEADER: crydaq/primitive/connection.h +#ifndef SONODAQ_COMPACT_FILE_3C3777EFD96E47484D7D +#define SONODAQ_COMPACT_FILE_3C3777EFD96E47484D7D + + +namespace CryDaq::primitive::connection +{ + // Connection management for Primitive clients. The instance is opaque; + // device operations are exposed by their category controllers. + class DAQ_API_EXPORT Controller : public detail::ControllerBase + { + public: + using detail::ControllerBase::ControllerBase; + + ErrorCode discover(std::vector& devices) const; + ErrorCode connect(const std::string& connection, const ConnectionOptions& options = {}) const; + ErrorCode disconnect(const std::string& connection = {}) const; + Optional details(const std::string& connection) const; + Optional> modules(const std::string& connection) const; + bool is_online(const std::string& connection) const; + ErrorCode set_status_callback(DeviceConnectionStatusCallback callback) const; + }; + + inline Controller bind(std::shared_ptr instance) + { + return Controller(std::move(instance)); + } +} +#endif // SONODAQ_COMPACT_FILE_3C3777EFD96E47484D7D +// END SDK HEADER: crydaq/primitive/connection.h + +// BEGIN SDK HEADER: crydaq/primitive/control.h +#ifndef CRYDAQ_PRIMITIVE_CONTROL_H +#define CRYDAQ_PRIMITIVE_CONTROL_H + + +// Advanced control primitives: sample rate, coupling, IEPE/charge and VP range +// low-level controls remain on CRYDaqInstance. + +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace control +{ + static constexpr ::CryDaq::StringView kCategory = "control"; + + using ::CryDaq::BoardControlCapabilities; + using ::CryDaq::ChannelVpInfo; + using ::CryDaq::ChannelVpRangesResult; + using ::CryDaq::DeviceChannelsConfig; + using ::CryDaq::DeviceReadbackConfig; + using ::CryDaq::ReadbackChannelConfig; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::Optional> available_sample_rates(const std::string& connectionString, + const std::string& channelLocalId) const; + + ::CryDaq::Optional> board_control_capabilities(const std::string& connectionString) const; + + ::CryDaq::ErrorCode set_sample_rate(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_sample_rate(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_coupling_mode(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_coupling_mode(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_io_mode(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_io_mode(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_iepe_switch(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_iepe_switch(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_charge_switch(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_charge_switch(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_lemo_switch(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_lemo_switch(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_lemo_switch(const std::string& connectionString, + const std::string& channelLocalId, + bool enabled) const; + + ::CryDaq::ErrorCode set_output_enable(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_output_enable(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_adc_enabled(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_adc_enabled(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_readback_enabled(const ::CryDaq::DeviceReadbackConfig& ctl) const; + + ::CryDaq::ErrorCode get_readback_enabled(::CryDaq::DeviceReadbackConfig& ctl) const; + + ::CryDaq::ErrorCode set_readback_enabled(const std::string& connectionString, + const std::string& channelLocalId, + bool enabled) const; + + ::CryDaq::ErrorCode set_channel_power_switch(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_channel_power_switch(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_pv_power_channel_switch(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_pv_power_channel_switch(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode set_cic_enable_switch(const ::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_cic_enable_switch(::CryDaq::DeviceChannelsConfig& ctl) const; + + ::CryDaq::ErrorCode get_channel_dc_bias_calibration(const std::string& connectionString, + const std::string& channelLocalId, + double& outVoltage) const; + + ::CryDaq::Optional<::CryDaq::ChannelVpInfo> channel_vp_values(const std::string& connectionString, + const std::string& channelLocalId) const; + + ::CryDaq::Optional<::CryDaq::ChannelVpRangesResult> channel_vp_ranges(const std::string& connectionString, + const std::string& channelLocalId) const; + + ::CryDaq::ErrorCode set_channel_vp_range(const std::string& connectionString, + const std::string& channelLocalId, + const std::string& vpRangeLabel) const; + + ::CryDaq::ErrorCode set_channel_vp_value(const std::string& connectionString, + const std::string& channelLocalId, + double vpValue) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_CONTROL_H +// END SDK HEADER: crydaq/primitive/control.h + +// BEGIN SDK HEADER: crydaq/primitive/dangerous_operation.h +#ifndef CRYDAQ_PRIMITIVE_DANGEROUS_OPERATION_H +#define CRYDAQ_PRIMITIVE_DANGEROUS_OPERATION_H + +#include +#include + +namespace CryDaq +{ +namespace primitive +{ + namespace dangerous_operation + { + static constexpr const char* kWriteTeds = "maintenance.write_teds"; + static constexpr const char* kClearHardwareConfigAndReboot = "maintenance.clear_hardware_config_and_reboot"; + static constexpr const char* kAdjustBoardCount = "diagnostic.adjust_board_count"; + static constexpr const char* kResetReferenceTime = "synchronization.reset_reference_time"; + } + + struct DangerousOperationApproval + { + bool acknowledged = false; + std::string operation; + std::string reason; + + static DangerousOperationApproval acknowledge(std::string operationName, std::string reasonText = {}) + { + DangerousOperationApproval approval; + approval.acknowledged = true; + approval.operation = std::move(operationName); + approval.reason = std::move(reasonText); + return approval; + } + }; + + inline bool is_dangerous_operation_approved(const DangerousOperationApproval& approval, + const char* expectedOperation) + { + return approval.acknowledged && expectedOperation != nullptr && approval.operation == expectedOperation; + } +} +} + +#endif // CRYDAQ_PRIMITIVE_DANGEROUS_OPERATION_H +// END SDK HEADER: crydaq/primitive/dangerous_operation.h + +// BEGIN SDK HEADER: crydaq/primitive/diagnostic.h +#ifndef CRYDAQ_PRIMITIVE_DIAGNOSTIC_H +#define CRYDAQ_PRIMITIVE_DIAGNOSTIC_H + + +// Advanced diagnostic primitives such as board-count adjustments and channel +// summary queries. + +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace diagnostic +{ + static constexpr ::CryDaq::StringView kCategory = "diagnostic"; + static constexpr const char* kDataSaveTimestampModeProperty = "DataSaveTimestampMode"; + static constexpr int kCoreTypeInt = 1; + static constexpr int kCoreTypeUndefined = 65535; + + DAQ_API_EXPORT Optional consume_error_detail( + ErrorCode code, const std::string& action, const std::string& context); + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::ErrorCode adjust_board_count(const std::string& connectionString, + std::uint8_t boardId, + int16_t delta, + std::string& errorInfo, + const ::CryDaq::primitive::DangerousOperationApproval& approval = {}) const; + + ::CryDaq::ErrorCode query_channel_info_summary(const std::string& connectionString, + const std::string& channelLocalId, + std::string& summary) const; + + ::CryDaq::Result<::CryDaq::DeviceDates> device_dates(const std::string& connectionString) const; + + ::CryDaq::ErrorCode get_device_bool_property(const std::string& connectionString, + const std::string& propertyName, + bool& outValue) const; + + ::CryDaq::ErrorCode set_device_bool_property(const std::string& connectionString, + const std::string& propertyName, + bool value) const; + + ::CryDaq::ErrorCode get_data_save_timestamp_mode( + const std::string& connectionString, + ::CryDaq::DataSaveTimestampMode& outMode) const; + + ::CryDaq::ErrorCode set_data_save_timestamp_mode( + const std::string& connectionString, + ::CryDaq::DataSaveTimestampMode mode) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_DIAGNOSTIC_H +// END SDK HEADER: crydaq/primitive/diagnostic.h + +// BEGIN SDK HEADER: crydaq/primitive/digital_filter.h +#ifndef CRYDAQ_PRIMITIVE_DIGITAL_FILTER_H +#define CRYDAQ_PRIMITIVE_DIGITAL_FILTER_H + + +#include +#include +#include +#include + + + +namespace CryDaq +{ + +namespace primitive +{ +namespace digital_filter +{ + static constexpr ::CryDaq::StringView kCategory = "digital_filter"; + + + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::Result<::CryDaq::DigitalFilterCapabilities> get_capabilities( + const std::string& connectionString, + const std::string& channelLocalId) const; + + ::CryDaq::Result<::CryDaq::DigitalFilterCurrentConfig> get_config( + const std::string& connectionString, + const std::string& channelLocalId) const; + + ::CryDaq::Result<::CryDaq::DigitalFilterCallResult> setup_config( + const std::string& connectionString, + const std::string& channelLocalId, + const ::CryDaq::DigitalFilterConfig& config) const; + + ::CryDaq::Result<::CryDaq::DigitalFilterCallResult> reset_config( + const std::string& connectionString) const; + + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_DIGITAL_FILTER_H +// END SDK HEADER: crydaq/primitive/digital_filter.h + +// BEGIN SDK HEADER: crydaq/primitive/digital_io.h +#ifndef CRYDAQ_PRIMITIVE_DIGITAL_IO_H +#define CRYDAQ_PRIMITIVE_DIGITAL_IO_H + + +// Advanced digital IO primitives. These wrappers talk directly to device +// properties exposed by SonoDAQ devices, without going through monitor APIs. + +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace digital_io +{ + static constexpr ::CryDaq::StringView kCategory = "digital_io"; + + struct DigitalIoCapabilities + { + std::vector inputLines; + std::vector outputLines; + bool hasInputMask = false; + bool hasOutputMask = false; + + int input_count() const + { + return static_cast(inputLines.size()); + } + + int output_count() const + { + return static_cast(outputLines.size()); + } + }; + + struct DigitalInputEvent + { + std::string connectionString; + int line = 0; + bool value = false; + int stateMask = 0; + }; + + struct DigitalInputMonitorOptions + { + int pollIntervalMs = 50; + std::vector lines; + }; + + using DigitalInputCallback = void (*)(void* handle, const DigitalInputEvent& event); + + class DAQ_API_EXPORT DigitalInputMonitor + { + public: + DigitalInputMonitor(std::shared_ptr<::CryDaq::CRYDaqInstance> instance, + std::string connectionString, + DigitalInputMonitorOptions options, + DigitalInputCallback callback, + void* callbackHandle) + : instance_(std::move(instance)) + , connectionString_(std::move(connectionString)) + , options_(std::move(options)) + , callback_(callback) + , callbackHandle_(callbackHandle) + { + if (options_.pollIntervalMs <= 0) + options_.pollIntervalMs = 50; + } + + DigitalInputMonitor(const DigitalInputMonitor&) = delete; + DigitalInputMonitor& operator=(const DigitalInputMonitor&) = delete; + + ~DigitalInputMonitor() + { + stop(); + } + + ::CryDaq::ErrorCode start(); + + void stop(); + + bool running() const; + + private: + void emit_events(int mask, int changedMask); + + void run(); + + std::shared_ptr<::CryDaq::CRYDaqInstance> instance_; + std::string connectionString_; + DigitalInputMonitorOptions options_; + DigitalInputCallback callback_ = nullptr; + void* callbackHandle_ = nullptr; + std::atomic running_{false}; + std::thread worker_; + }; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::ErrorCode detect_capabilities(const std::string& connectionString, + DigitalIoCapabilities& outCapabilities) const; + + ::CryDaq::ErrorCode get_input_mask(const std::string& connectionString, int& outMask) const; + + ::CryDaq::ErrorCode get_input(const std::string& connectionString, int line, bool& outValue) const; + + ::CryDaq::ErrorCode get_output_mask(const std::string& connectionString, int& outMask) const; + + ::CryDaq::ErrorCode get_output(const std::string& connectionString, int line, bool& outValue) const; + + ::CryDaq::ErrorCode set_output(const std::string& connectionString, int line, bool value) const; + + ::CryDaq::ErrorCode start_input_monitor(const std::string& connectionString, + DigitalInputMonitorOptions options, + DigitalInputCallback callback, + void* callbackHandle, + std::shared_ptr& outMonitor) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_DIGITAL_IO_H +// END SDK HEADER: crydaq/primitive/digital_io.h + +// BEGIN SDK HEADER: crydaq/primitive/emergency_stop.h +#ifndef CRYDAQ_PRIMITIVE_EMERGENCY_STOP_H +#define CRYDAQ_PRIMITIVE_EMERGENCY_STOP_H + + +// Advanced emergency-stop primitives. These wrappers call device-level +// FunctionProperty entries directly; they intentionally do not depend on +// monitor HTTP routes. + +#include +#include +#include + + + +namespace CryDaq +{ +namespace primitive +{ +namespace emergency_stop +{ + static constexpr ::CryDaq::StringView kCategory = "emergency_stop"; + static constexpr int kNetworkDisconnectTimeoutMinMs = 200; + static constexpr int kNetworkDisconnectTimeoutDefaultMs = 300; + static constexpr int kNetworkDisconnectTimeoutMaxMs = 10000; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::ErrorCode get_status(const std::string& connectionString, + std::string& responseJson) const; + + ::CryDaq::ErrorCode set_enabled(const std::string& connectionString, + bool enabled, + std::string& responseJson) const; + + ::CryDaq::ErrorCode set_network_disconnect_config( + const std::string& connectionString, + bool enabled, + int timeoutMs, + std::string& responseJson) const; + + ::CryDaq::ErrorCode trigger(const std::string& connectionString, + std::string source, + std::string reason, + std::string& responseJson) const; + + ::CryDaq::ErrorCode recover(const std::string& connectionString, + std::string& responseJson) const; + + private: + ::CryDaq::ErrorCode call_function(const ::CryDaq::DevicePropertyOperation& operation, + std::string& responseJson) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_EMERGENCY_STOP_H +// END SDK HEADER: crydaq/primitive/emergency_stop.h + +// BEGIN SDK HEADER: crydaq/primitive/gnss.h +#ifndef CRYDAQ_PRIMITIVE_GNSS_H +#define CRYDAQ_PRIMITIVE_GNSS_H + + +#include +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace gnss +{ + static constexpr ::CryDaq::StringView kCategory = "gnss"; + + using Data = ::CryDaq::GnssData; + using DataCallback = ::CryDaq::GnssDataCallback; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::ErrorCode set_enabled(const std::string& connectionString, bool enabled) const; + + ::CryDaq::ErrorCode status(const std::string& connectionString, std::string& outStatus) const; + + // Subscribe to the latest state; intermediate samples may be coalesced. + // Samples older than 3 s invalidate fix/motion flags and clear timestampUs. + // Does not start the receiver. nullptr unsubscribes; a new callback replaces the old one. + // Data is valid only during the call. Keep callbacks short and copy retained data. + ::CryDaq::ErrorCode subscribe(DataCallback callback, void* callbackHandle = nullptr) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_GNSS_H +// END SDK HEADER: crydaq/primitive/gnss.h + +// BEGIN SDK HEADER: crydaq/primitive/maintenance.h +#ifndef CRYDAQ_PRIMITIVE_MAINTENANCE_H +#define CRYDAQ_PRIMITIVE_MAINTENANCE_H + + +// Advanced maintenance primitives for TEDS, device time, aliases and reboot- +// level operations. + +#include +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace maintenance +{ + static constexpr ::CryDaq::StringView kCategory = "maintenance"; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::ErrorCode get_teds_read_write_supported(const std::string& connectionString, + const std::string& channelLocalId, + bool& supported) const; + + ::CryDaq::ErrorCode read_teds(const std::string& connectionString, + const std::string& channelLocalId, + std::string& tedsHexData) const; + + ::CryDaq::ErrorCode read_teds_rom_info(const std::string& connectionString, + const std::string& channelLocalId, + std::string& tedsHexData) const; + + ::CryDaq::ErrorCode write_teds(const std::string& connectionString, + const std::string& channelLocalId, + const std::string& tedsHexData, + const ::CryDaq::primitive::DangerousOperationApproval& approval = {}) const; + + ::CryDaq::ErrorCode set_device_time(const std::string& connectionString, + const std::string& timeText, + std::string* outResponseJson = nullptr) const; + + ::CryDaq::ErrorCode setup_device_alias(const std::string& connectionString, + const std::string& alias) const; + + ::CryDaq::ErrorCode clear_hardware_config_and_reboot( + const std::string& connectionString, + const ::CryDaq::primitive::DangerousOperationApproval& approval = {}) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_MAINTENANCE_H +// END SDK HEADER: crydaq/primitive/maintenance.h + +// BEGIN SDK HEADER: crydaq/primitive/playback_control.h +#ifndef CRYDAQ_PRIMITIVE_PLAYBACK_CONTROL_H +#define CRYDAQ_PRIMITIVE_PLAYBACK_CONTROL_H + +#define CRYDAQ_HAS_PLAYBACK_STATUS_PROPERTY_OBJECT 1 + +#include +#include +#include +#include +#include + + + +namespace CryDaq +{ + enum class PlaybackFifoControlMode : int + { + Manual = 0, + Auto = 1 + }; + + enum class PlaybackFifoClampReason : int + { + None = 0, + MinimumStartupOrWriteBatch = 1, + TargetLimit = 2, + PhysicalFifoLimit = 3, + Unknown = 4 + }; + + struct PlaybackBufferConfig + { + int asioPrimeBlocks = 0; + int unifiedPrimeBlocks = 0; + int targetBufferMs = 0; + PlaybackFifoControlMode fifoControlMode = PlaybackFifoControlMode::Manual; + int writeSamplesPerChannel = 0; + int hwFifoMs = 0; + int fifoDirectThresholdMs = 0; + int fifoGrowthDivisor = 0; + int fifoMaxMs = 0; + }; + + struct PlaybackBufferConfigPatch + { + Optional asioPrimeBlocks; + Optional unifiedPrimeBlocks; + Optional targetBufferMs; + Optional fifoControlMode; + Optional writeSamplesPerChannel; + Optional hwFifoMs; + Optional fifoDirectThresholdMs; + Optional fifoGrowthDivisor; + Optional fifoMaxMs; + + bool empty() const noexcept + { + return !asioPrimeBlocks.has_value() && + !unifiedPrimeBlocks.has_value() && + !targetBufferMs.has_value() && + !fifoControlMode.has_value() && + !writeSamplesPerChannel.has_value() && + !hwFifoMs.has_value() && + !fifoDirectThresholdMs.has_value() && + !fifoGrowthDivisor.has_value() && + !fifoMaxMs.has_value(); + } + }; + + struct PlaybackBufferStatus + { + double bufferMs = 0.0; + std::uint64_t creditBytes = 0; + double effectiveTargetBufferMs = 0.0; + double lowWatermarkMs = 0.0; + double maxBufferMs = 0.0; + double effectiveHwFifoMs = 0.0; + std::uint64_t effectiveHwFifoBytes = 0; + PlaybackFifoClampReason fifoClampReason = PlaybackFifoClampReason::Unknown; + // Legacy property snapshots do not provide a transport age guarantee. + std::string statusSource = "properties"; + bool statusFresh = false; + double statusAgeMs = -1.0; + }; + +namespace primitive +{ +namespace playback_control +{ + static constexpr ::CryDaq::StringView kCategory = "playback_control"; + + + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::Result get_target_buffer_ms(const std::string& connectionString) const; + + ::CryDaq::ErrorCode set_target_buffer_ms( + const std::string& connectionString, + int targetBufferMs) const; + + ::CryDaq::Result<::CryDaq::PlaybackBufferConfig> get_config( + const std::string& connectionString) const; + + ::CryDaq::Result<::CryDaq::PlaybackBufferStatus> get_status( + const std::string& connectionString, + const std::string& channelLocalId) const; + + ::CryDaq::Result<::CryDaq::PlaybackBufferConfig> update_config( + const std::string& connectionString, + const ::CryDaq::PlaybackBufferConfigPatch& patch) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_PLAYBACK_CONTROL_H +// END SDK HEADER: crydaq/primitive/playback_control.h + +// BEGIN SDK HEADER: crydaq/primitive/playback.h +#ifndef SONODAQ_COMPACT_FILE_065956D9BD806FCF6DD3 +#define SONODAQ_COMPACT_FILE_065956D9BD806FCF6DD3 + +namespace CryDaq::primitive::playback +{ + class DAQ_API_EXPORT Controller : public detail::ControllerBase + { + public: + using detail::ControllerBase::ControllerBase; + Result start(const PlayRequest& source, const PlaybackOptions& options = {}) const; + Result open_stream(const PlaybackStreamConfig& config, const PlaybackOptions& options = {}) const; + Result run(const PlayRequest& source, const PlaybackOptions& options = {}) const; + Result sync_device_status( + const std::string& connection, const std::vector& boardDisplayIds) const; + // Explicit recovery only; use the identity returned by sync_device_status. + Result recover_sync_playback(const SyncPlaybackRecoveryRequest& request) const; + // Retry cleanup using error.context from a failed synchronized run. + Result close_sync_playback(const std::string& operationId) const; + }; + inline Controller bind(std::shared_ptr instance) + { + return Controller(std::move(instance)); + } +} +#endif // SONODAQ_COMPACT_FILE_065956D9BD806FCF6DD3 +// END SDK HEADER: crydaq/primitive/playback.h + +// BEGIN SDK HEADER: crydaq/primitive/property.h +#ifndef CRYDAQ_PRIMITIVE_PROPERTY_H +#define CRYDAQ_PRIMITIVE_PROPERTY_H + + +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace property +{ + static constexpr ::CryDaq::StringView kCategory = "property"; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::ErrorCode get_property(const ::CryDaq::DevicePropertyTarget& target, + std::string& responseJson) const; + + ::CryDaq::ErrorCode set_property(const ::CryDaq::DevicePropertyOperation& operation, + std::string& responseJson) const; + + ::CryDaq::ErrorCode set_properties(const std::vector<::CryDaq::DevicePropertyOperation>& operations, + std::string& responseJson) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_PROPERTY_H +// END SDK HEADER: crydaq/primitive/property.h + +// BEGIN SDK HEADER: crydaq/primitive/synchronization.h +#ifndef CRYDAQ_PRIMITIVE_SYNCHRONIZATION_H +#define CRYDAQ_PRIMITIVE_SYNCHRONIZATION_H + + +// Advanced multi-device synchronization task primitives. + +#include +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace primitive +{ +namespace synchronization +{ + static constexpr ::CryDaq::StringView kCategory = "synchronization"; + + using ::CryDaq::DeviceSyncCapabilities; + using ::CryDaq::DeviceSyncConfig; + using ::CryDaq::DeviceSyncStatus; + using ::CryDaq::MultiDeviceSyncRequest; + using ::CryDaq::MultiDeviceSyncResult; + using ::CryDaq::PtpRole; + using ::CryDaq::SyncMode; + using ::CryDaq::SyncTaskStage; + using ::CryDaq::SyncTaskState; + + class DAQ_API_EXPORT Controller : public ::CryDaq::primitive::detail::ControllerBase + { + public: + using ::CryDaq::primitive::detail::ControllerBase::ControllerBase; + + ::CryDaq::ErrorCode capabilities(const std::string& connectionString, + ::CryDaq::DeviceSyncCapabilities& caps) const; + + ::CryDaq::ErrorCode configure(const ::CryDaq::MultiDeviceSyncRequest& req, + ::CryDaq::MultiDeviceSyncResult* outResult = nullptr) const; + + ::CryDaq::ErrorCode start(const ::CryDaq::MultiDeviceSyncRequest& req, + std::string& operationId) const; + + ::CryDaq::ErrorCode progress(const std::string& operationId, + ::CryDaq::MultiDeviceSyncResult& result) const; + + ::CryDaq::ErrorCode wait(const std::string& operationId, + int64_t timeoutMs, + ::CryDaq::MultiDeviceSyncResult* outResult = nullptr) const; + + ::CryDaq::ErrorCode cancel(const std::string& operationId) const; + + ::CryDaq::ErrorCode status(const std::string& connectionString, + ::CryDaq::DeviceSyncStatus& statusValue) const; + + ::CryDaq::ErrorCode reset_reference_time( + const std::vector& connectionStrings, + const ::CryDaq::primitive::DangerousOperationApproval& approval = {}) const; + }; + + using Instance = Controller; + + inline Controller bind(std::shared_ptr<::CryDaq::CRYDaqInstance> instance) + { + return Controller(std::move(instance)); + } +} +} +} + +#endif // CRYDAQ_PRIMITIVE_SYNCHRONIZATION_H +// END SDK HEADER: crydaq/primitive/synchronization.h + +#endif // CRYDAQ_PRIMITIVE_API_H +// END SDK HEADER: crydaq/primitive.h + +// BEGIN SDK HEADER: crydaq/primitive/instance.h +#ifndef CRYDAQ_PRIMITIVE_INSTANCE_H +#define CRYDAQ_PRIMITIVE_INSTANCE_H + +#include + + + +namespace CryDaq +{ +namespace workflow { class MeasurementSession; } +namespace primitive +{ + static constexpr ::CryDaq::StringView kLayer = "primitive"; + static constexpr ::CryDaq::StringView kAudience = "expert_control"; + + using RawInstance = ::CryDaq::CRYDaqInstance; + using ::CryDaq::CRYDaqInstance; + using Instance = RawInstance; + using ::CryDaq::LoggingConfig; + DAQ_API_EXPORT Result> from_session(const ::CryDaq::workflow::MeasurementSession& session); + DAQ_API_EXPORT std::shared_ptr CreateInstance( + void* callbackHandle = nullptr, const LoggingConfig& logging = {}); +} +} + +#endif // CRYDAQ_PRIMITIVE_INSTANCE_H +// END SDK HEADER: crydaq/primitive/instance.h + +// BEGIN SDK HEADER: crydaq/primitive/system.h +#ifndef CRYDAQ_PRIMITIVE_SYSTEM_H +#define CRYDAQ_PRIMITIVE_SYSTEM_H + +#include +#include + + +// BEGIN SDK HEADER: crydaq/system_types.h +#ifndef CRYDAQ_SYSTEM_TYPES_H +#define CRYDAQ_SYSTEM_TYPES_H + +#include +#include +#include + +namespace CryDaq +{ +struct SystemInfo +{ + std::string buildDate; + std::string buildTime; + std::string compiler; + std::int64_t systemUptime = 0; + std::string memoryUsage; + std::string cpuUsage; +}; + +struct SystemUptimeInfo +{ + std::string systemUptime; + std::string serviceUptime; +}; + +struct DiskInfo +{ + std::string path; + double availableGb = 0.0; + double totalGb = 0.0; + double usedGb = 0.0; + double usagePercent = 0.0; +}; + +struct BatteryEntry +{ + std::string name; + bool hasBattery = false; + int capacity = -1; + std::string status; +}; + +struct BatteryStatus +{ + bool success = false; + std::string powerSupply; + std::int64_t timestamp = 0; + std::vector batteries; +}; + +struct GpsStatus +{ + bool gnssStarted = false; + bool hasFix = false; + bool success = false; + int usedSatellites = 0; + int visibleSatellites = 0; + std::string gnssError; + std::int64_t timestamp = 0; +}; + +} + +#endif // CRYDAQ_SYSTEM_TYPES_H +// END SDK HEADER: crydaq/system_types.h + +namespace CryDaq +{ +class CRYSystemManager; +namespace primitive +{ + using DeviceRef = workflow::DeviceRef; + using workflow::make_error; + + class DAQ_API_EXPORT System + { + public: + System() = default; + + explicit System(std::string baseUrl); + + static Result from_base_url(const std::string& baseUrl); + + static Result from_connection_string(const std::string& connectionString, int port = 8080); + + static Result from_device(const DeviceRef& device, int port = 8080); + + static Result http_base_url_from_connection_string(const std::string& connectionString, + int port = 8080); + + const std::string& base_url() const noexcept; + + Result set_base_url(const std::string& baseUrl); + + Result system_info_json() const; + + Result system_uptime_json() const; + + Result get_system_uptime() const; + + Result disk_info_json() const; + + Result software_versions_json() const; + + Result battery_status_json() const; + + Result sync_status_json() const; + + Result gps_status_json() const; + + Result network_status_json(const std::string& iface = "") const; + + Result network_info_json(const std::string& iface = "") const; + + Result network_connections_json() const; + + Result active_network_connections_json() const; + + Result wifi_scan_json(const std::string& iface = "") const; + + Result wifi_saved_json() const; + + Result wifi_radio_json() const; + + Result get_backlight() const; + + Result set_backlight(int brightness) const; + + Result connect_wifi(const std::string& ssid) const; + + Result create_wifi_connection(const std::string& ssid, + const std::string& password, + const std::string& interfaceName = "wlan0") const; + + Result delete_wifi(const std::string& ssid) const; + + Result create_network_connection_static(const std::string& ipAddress, + const std::string& netmask = "255.255.255.0", + const std::string& gateway = "192.168.17.1", + const std::string& interfaceName = "eth1") const; + + private: + std::string baseUrl_; + std::shared_ptr manager_; + }; +} +} + +#endif // CRYDAQ_PRIMITIVE_SYSTEM_H +// END SDK HEADER: crydaq/primitive/system.h + +// Shared public utilities available from either domain entry. + +// BEGIN SDK HEADER: crysystemmanager.h +#ifndef CRY_SYSTEM_MANAGER_H +#define CRY_SYSTEM_MANAGER_H + + +#include +#include +#include +#include +#include + +namespace CryDaq +{ +class CRYHttpClient; + +class DAQ_API_EXPORT CRYSystemManager +{ +public: + explicit CRYSystemManager(const std::string& baseUrl); + ~CRYSystemManager(); + + CRYSystemManager(const CRYSystemManager&) = delete; + CRYSystemManager& operator=(const CRYSystemManager&) = delete; + CRYSystemManager(CRYSystemManager&& other) noexcept; + CRYSystemManager& operator=(CRYSystemManager&& other) noexcept; + + Optional GetSystemInfo(); + Optional GetSystemUptime(); + Optional GetDiskInfo(); + std::map GetSoftwareVersions(); + Optional GetBatteryStatus(); + std::string GetSyncStatus(); + Optional GetGpsStatus(); + + Optional GetBacklight(); + bool SetBacklight(int brightness); + + std::string GetNetworkStatus(const std::string& iface = ""); + std::string GetNetworkInfo(const std::string& iface = ""); + std::string GetNetworkConnections(); + std::string GetActiveNetworkConnections(); + + std::string GetWifiScan(const std::string& iface = ""); + std::string GetWifiSaved(); + bool ConnectWifi(const std::string& ssid); + bool CreateWifiConnection( + const std::string& ssid, + const std::string& password, + const std::string& interfaceName = "wlan0"); + bool DeleteWifi(const std::string& ssid); + std::string GetWifiRadio(); + + bool CreateNetworkConnectionStatic( + const std::string& ipAddress, + const std::string& netmask = "255.255.255.0", + const std::string& gateway = "192.168.17.1"); + bool CreateNetworkConnectionStatic( + const std::string& ipAddress, + const std::string& netmask, + const std::string& gateway, + const std::string& interfaceName); + + void SetBaseUrl(const std::string& baseUrl); + + std::string GetSystemInfoJson(); + std::string GetSystemUptimeJson(); + std::string GetDiskInfoJson(); + std::string GetSoftwareVersionsJson(); + std::string GetBatteryStatusJson(); + std::string GetGpsStatusJson(); + + static std::string PrettyPrintJson(const std::string& json); + static bool IsValidIPv4(const std::string& s); + static std::string HttpBaseUrlFromDeviceInfo( + const GeneralDeviceInfo& device, + int port = 8080); + static std::string HttpBaseUrlFromDeviceInfo( + const DetailDeviceInfo& device, + int port = 8080); + static std::string HttpBaseUrlFromAvailableDevice( + const std::string& connectionString, + int port = 8080); + static std::string HttpBaseUrlFromConnectionString( + const std::string& connectionString, + int port = 8080, + bool resolveHostname = true); + + std::string GetLastError() const + { + return m_lastError; + } + + int GetLastStatusCode() const + { + return m_lastStatusCode; + } + +private: + std::string m_baseUrl; + std::string m_lastError; + int m_lastStatusCode = 0; + std::unique_ptr m_httpClient; + + std::string getJsonPath(const std::string& path); +}; +} + +#endif // CRY_SYSTEM_MANAGER_H +// END SDK HEADER: crysystemmanager.h + +#endif // CRYDAQ_PRIMITIVE_H +// END SDK HEADER: primitive.h + +#endif // SONODAQ_COMPACT_PRIMITIVE_H diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/workflow.h b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/workflow.h new file mode 100644 index 0000000..f8b15c5 --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/include/workflow.h @@ -0,0 +1,2104 @@ +// Generated by amalgamate_cpp_sdk_headers.py; do not edit. +#ifndef SONODAQ_COMPACT_WORKFLOW_H +#define SONODAQ_COMPACT_WORKFLOW_H +#include + +// BEGIN SDK HEADER: workflow.h +#ifndef CRYDAQ_WORKFLOW_H +#define CRYDAQ_WORKFLOW_H + +// CryDAQ Workflow API umbrella. +// +// New application code should include this header when it wants the high-level +// Workflow API only: +// +// #include +// +// Shared utilities (TEDS, output templates, timing and signal generation) are +// also included. Native openDAQ interop remains an explicit opt-in. +// +// The lower-level split headers under are organization +// points for users who intentionally want a narrower include. + + +// BEGIN SDK HEADER: crydaq/workflow/sdk.h +#ifndef CRYDAQ_WORKFLOW_SDK_H +#define CRYDAQ_WORKFLOW_SDK_H + + +// BEGIN SDK HEADER: crydaq/workflow/capabilities.h +#ifndef CRYDAQ_WORKFLOW_CAPABILITIES_H +#define CRYDAQ_WORKFLOW_CAPABILITIES_H + +#include +#include + + + +// BEGIN SDK HEADER: crydaq/workflow/routes.h +#ifndef CRYDAQ_WORKFLOW_ROUTES_H +#define CRYDAQ_WORKFLOW_ROUTES_H + +#include +#include +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace workflow +{ + enum class RouteKind : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Raw = 0, + Downsampled = 1, + Statistics = 2, + Fft = 3, + Custom = 4, + }; + + enum class DownsampleMethod : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Decimate = 0, + MeanWindow = 1, + RmsWindow = 2, + MinMaxEnvelope = 3, + FirAntiAlias = 4, + }; + + enum class TimestampPolicy : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + InputSample = 0, + WindowStart = 1, + WindowCenter = 2, + WindowEnd = 3, + }; + + enum class BackpressurePolicy : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Block = 0, + DropOldest = 1, + DropNewest = 2, + FailRoute = 3, + FailAll = 4, + }; + + enum class RouteExecutionBackend : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + HostProcessor = 0, + OpenDaqFunctionBlock = 1, + }; + + struct RouteProcessingOptions + { + std::string functionBlockModulePath; ///< UTF-8 host directory path. + int functionBlockReadTimeoutMs = 1000; + }; + + struct RouteParameterBinding + { + std::string routeField; + std::string functionBlockProperty; + std::string valueMapping; + }; + + struct RouteProcessorCapability + { + std::string processorId; + std::string displayName; + RouteKind kind = RouteKind::Raw; + bool executable = false; + RouteExecutionBackend backend = RouteExecutionBackend::HostProcessor; + std::string functionBlockModuleId; + std::string functionBlockTypeId; + std::vector supportedDownsampleMethods; + std::vector supportedTimestampPolicies; + std::vector parameterBindings; + }; + + struct RouteSpec + { + std::string routeId; + RouteKind kind = RouteKind::Raw; + ChannelRef source; + SampleUnit unit = SampleUnit::RawFs; + int targetSampleRate = 0; + int factor = 0; + DownsampleMethod downsampleMethod = DownsampleMethod::FirAntiAlias; + TimestampPolicy timestampPolicy = TimestampPolicy::WindowCenter; + bool antiAlias = true; + int maxQueueFrames = 0; // 0 selects the shared queue default: 65536 input samples. + int maxQueueBytes = 0; // 0 selects the shared queue default: 16 MiB. + int maxLatencyMs = 0; // 0 disables the deadline; positive values include processing and callbacks. + BackpressurePolicy backpressure = BackpressurePolicy::Block; + }; + + class Route + { + public: + static Route raw(std::string routeId) + { + RouteSpec spec; + spec.routeId = std::move(routeId); + spec.kind = RouteKind::Raw; + spec.downsampleMethod = DownsampleMethod::Decimate; + spec.timestampPolicy = TimestampPolicy::InputSample; + spec.antiAlias = false; + return Route(std::move(spec)); + } + + static Route downsample(std::string routeId) + { + RouteSpec spec; + spec.routeId = std::move(routeId); + spec.kind = RouteKind::Downsampled; + return Route(std::move(spec)); + } + + Route& from(ChannelRef channel) + { + spec_.source = std::move(channel); + return *this; + } + + Route& unit(SampleUnit value) noexcept + { + spec_.unit = value; + return *this; + } + + Route& target_rate(int value) noexcept + { + spec_.targetSampleRate = value; + spec_.factor = 0; + return *this; + } + + Route& factor(int value) noexcept + { + spec_.factor = value; + spec_.targetSampleRate = 0; + return *this; + } + + Route& method(DownsampleMethod value) noexcept + { + spec_.downsampleMethod = value; + return *this; + } + + Route& timestamp_policy(TimestampPolicy value) noexcept + { + spec_.timestampPolicy = value; + return *this; + } + + Route& anti_alias(bool value) noexcept + { + spec_.antiAlias = value; + return *this; + } + + Route& max_queue_frames(int value) noexcept + { + spec_.maxQueueFrames = value; + return *this; + } + + Route& max_queue_bytes(int value) noexcept + { + spec_.maxQueueBytes = value; + return *this; + } + + Route& max_latency_ms(int value) noexcept + { + spec_.maxLatencyMs = value; + return *this; + } + + Route& backpressure_policy(BackpressurePolicy value) noexcept + { + spec_.backpressure = value; + return *this; + } + + const RouteSpec& spec() const noexcept + { + return spec_; + } + + operator RouteSpec() const + { + return spec_; + } + + private: + explicit Route(RouteSpec spec) + : spec_(std::move(spec)) + { + } + + RouteSpec spec_; + }; + + struct RouteData + { + std::string routeId; + RouteKind kind = RouteKind::Raw; + ChannelRef source; + SampleUnit unit = SampleUnit::RawFs; + int sampleRate = 0; + int sourceSampleRate = 0; + int64_t sourceFrameStart = 0; + int64_t sourceFrameCount = 0; + TimestampPolicy timestampPolicy = TimestampPolicy::WindowCenter; + std::vector rawSamples; + std::vector voltageSamples; + std::vector chargeSamples; + std::vector timestamps; + std::string transform; + }; + + struct RouteStatus + { + std::string routeId; + bool ok = true; + std::string issueCode; + std::string message; + int64_t producedFrames = 0; + int64_t droppedFrames = 0; + int queueDepth = 0; + int64_t lastSourceTimestamp = 0; + int64_t lastOutputTimestamp = 0; + int processingLatencyMs = 0; + }; + + struct AcquisitionResult + { + RecordResult legacy; + std::vector routes; + std::vector statuses; + }; + + struct RouteBatch + { + std::vector routes; + std::vector statuses; + }; + + struct StreamingRouteInputData + { + ChannelRef source; + SampleUnit unit = SampleUnit::RawFs; + int sampleRate = 0; + int count = 0; + std::vector rawSamples; + std::vector voltageSamples; + std::vector chargeSamples; + std::vector timestamps; + }; + + using RouteBatchCallback = void (*)(void* handle, const RouteBatch& batch); + + class DAQ_API_EXPORT StreamingRouteDispatcher + { + public: + StreamingRouteDispatcher(); + ~StreamingRouteDispatcher(); + + StreamingRouteDispatcher(StreamingRouteDispatcher&& other) noexcept; + StreamingRouteDispatcher& operator=(StreamingRouteDispatcher&& other) noexcept; + + StreamingRouteDispatcher(const StreamingRouteDispatcher&) = delete; + StreamingRouteDispatcher& operator=(const StreamingRouteDispatcher&) = delete; + + StreamingRouteDispatcher& on_route_batch(RouteBatchCallback callback, void* handle = nullptr) noexcept; + + Result prepare(const std::vector& routes, + const std::vector& channels, + int sourceSampleRate, + const RouteProcessingOptions& options = RouteProcessingOptions{}); + + Result process(const std::string& connectionString, + const std::string& channelLocalId, + const CryDaq::ChannelInData& data); + + Result process(const StreamingRouteInputData& data); + Result process(StreamingRouteInputData&& data); + + private: + struct Impl; + std::unique_ptr impl_; + }; + + namespace detail + { + template + struct has_route_processing_options : std::false_type + { + }; + + template + struct has_route_processing_options< + AcquisitionSpec, + std::void_t().routeProcessing)>> + : std::true_type + { + }; + + template + inline RouteProcessingOptions route_processing_options_for(const AcquisitionSpec& spec) + { + if constexpr (has_route_processing_options::value) + return spec.routeProcessing; + else + return RouteProcessingOptions{}; + } + + } + + + DAQ_API_EXPORT std::vector route_processor_capabilities( + const RouteProcessingOptions& options); + + DAQ_API_EXPORT std::vector route_processor_capabilities(); + + DAQ_API_EXPORT Result validate_routes(const std::vector& routes, + const std::vector& channels, + int sourceSampleRate); + + template + inline Result validate_routes(const AcquisitionSpec& spec) + { + return validate_routes(spec.routes, spec.channels, spec.sampleRate); + } + + DAQ_API_EXPORT Result process_acquisition_routes(const RecordResult& record, + const std::vector& routes, + const std::vector& channels, + int sourceSampleRate, + const RouteProcessingOptions& options); + + DAQ_API_EXPORT Result process_acquisition_routes(const RecordResult& record, + const std::vector& routes, + const std::vector& channels, + int sourceSampleRate); + + template + inline Result process_acquisition_routes(const RecordResult& record, + const AcquisitionSpec& spec) + { + return process_acquisition_routes(record, + spec.routes, + spec.channels, + spec.sampleRate, + detail::route_processing_options_for(spec)); + } + + template + inline Result process_acquisition_routes(const RecordResult& record, + const AcquisitionSpec& spec, + const RouteProcessingOptions& options) + { + return process_acquisition_routes(record, spec.routes, spec.channels, spec.sampleRate, options); + } +} +} + +#endif // CRYDAQ_WORKFLOW_ROUTES_H +// END SDK HEADER: crydaq/workflow/routes.h + +namespace CryDaq +{ +namespace workflow +{ + struct RangeQuery + { + CapabilityContext context; + SignalDomain domain = SignalDomain::VoltagePeak; + }; + + struct RangeOption : RangeCandidate + { + std::string source; + }; + + struct RangeModeContext + { + std::string measurementMode; + std::string ioMode; + // Empty when coupling does not distinguish range lists. + std::string couplingMode; + SignalDomain domain = SignalDomain::VoltagePeak; + }; + + struct RangeModeCatalog + { + RangeModeContext context; + // In this catalog magnitude is nominal; actualVp uses context.domain + // (V for VoltagePeak, pC for ChargePeak) and requires hasActualVp. + std::vector ranges; + bool calibrationComplete = false; + }; + + struct RangeCatalog + { + std::string profileId; + int profileVersion = 0; + BoardType boardType = BoardType::Unknown; + ChannelType channelType = ChannelType::Input; + std::string channelName; + std::string currentRangeId; + std::string currentRangeLabel; + std::string calibrationSource = "none"; + std::vector modes; + }; + + struct DeviceRangeCatalog + { + std::string deviceId; + std::vector channels; + }; + + class DAQ_API_EXPORT Capabilities + { + public: + Capabilities() = default; + + Result> channels() const; + + Result profile_catalog() const; + + static Result> ranges_for_profile(const ProfileCatalog& catalog, + const ProfileDescriptor& profile, + const RangeQuery& query); + + // Evaluate a known profile offline, using the same rules as session queries. + static std::vector config_dimension_states_for_profile( + const ProfileDescriptor& profile, const ConfigDimensionQuery& query); + + Result> route_processors() const; + + Result> route_processors(const RouteProcessingOptions& options) const; + + Result> config_dimensions(const ChannelRef& channel) const; + + Result> config_dimension_states( + const ChannelRef& channel, + const ConfigDimensionQuery& query) const; + + Result input_capabilities(const ChannelRef& channel) const; + Result supports_measurement_mode(const ChannelRef& channel, MeasurementMode mode) const; + Result> sample_rates(const ChannelRef& channel) const; + + Result> vp_ranges(const ChannelRef& channel) const; + + Result> range_candidates(const ChannelRef& channel, SignalDomain domain) const; + + Result> ranges(const ChannelRef& channel, const RangeQuery& query) const; + + // Read all supported mode/range combinations without changing hardware. + // Missing calibration remains missing. This is not an atomic hardware snapshot. + Result range_catalog(const ChannelRef& channel) const; + // All current channels, grouped by device, with one channel-detail read per device. + Result> range_catalog() const; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class Runtime; + friend class MeasurementSession; + friend class Control; + friend class TaskEngine; + friend class AcquisitionBuilder; + friend class PlaybackBuilder; + friend class PlayAndAcquireBuilder; + explicit Capabilities(CryDaq::detail::LegacySession session); + Optional profile_for_channel(const ProfileCatalog& catalog, const ChannelRef& channel) const; + + Optional profile_for_context_query(const ProfileCatalog& catalog, + const ChannelRef& channel, + const CapabilityContext& context) const; + + std::shared_ptr session_; + bool hasSession_ = false; + }; +} +} + +#endif // CRYDAQ_WORKFLOW_CAPABILITIES_H +// END SDK HEADER: crydaq/workflow/capabilities.h + +// BEGIN SDK HEADER: crydaq/workflow/config.h +#ifndef CRYDAQ_WORKFLOW_CONFIG_H +#define CRYDAQ_WORKFLOW_CONFIG_H + +#include +#include +#include +#include +#include +#include + + + +namespace CryDaq +{ +namespace workflow +{ + enum class ConfigApplyBackend : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + None = 0, + NativeProperty = 1, + NativeFunctionProperty = 2, + SdkAtomicCommands = 3, + HttpApi = 4, + }; + + enum class ConfigApplyStatus : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + NotApplied = 0, + Applied = 1, + Verified = 2, + Failed = 3, + }; + + enum class ConfigReceiptStatus : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + NotApplied = 0, + Applied = 1, + Verified = 2, + PartiallyFailed = 3, + Failed = 4, + }; + + struct ConfigIntentChannel + { + ChannelRef channel; + Optional sampleRate; + Optional rangeLabel; + Optional digitalFilter; + std::map options; + + static const char* range_id_option_key() noexcept + { + return "$crydaq.workflow.rangeId"; + } + + void set_range_id(std::string rangeId) + { + if (rangeId.empty()) + { + options.erase(range_id_option_key()); + return; + } + options[range_id_option_key()] = + ConfigValue::text_value(std::move(rangeId)); + } + + Optional range_id() const + { + const auto it = options.find(range_id_option_key()); + if (it == options.end() || it->second.stringValue.empty()) + return Optional(); + return Optional(it->second.stringValue); + } + }; + + struct ConfigIntent + { + std::vector channels; + }; + + struct ConfigSnapshot + { + std::string snapshotId; + std::string source; + std::string stateRevision; + std::vector devices; + }; + + struct ConfigPlanOperation + { + ChannelRef channel; + std::string propertyName; + std::string requestedValue; + ConfigValueType requestedValueType = ConfigValueType::Text; + ConfigApplyBackend backend = ConfigApplyBackend::None; + int applyOrder = 100; + ConfigDimensionScope targetScope = ConfigDimensionScope::Channel; + std::string groupId; + std::vector refreshAfterApply; + std::string compatibilityMode; + std::vector probeEvidence; + std::vector atomicActions; + }; + + struct ConfigPlanImpact + { + bool requiresStopTasks = false; + bool dataContinuityRisk = false; + bool affectsTimebase = false; + int estimatedInterruptMs = 0; + std::vector affectedChannels; + }; + + struct ConfigWriteStep + { + ChannelRef channel; + std::string propertyName; + std::string requestedValue; + ConfigValueType requestedValueType = ConfigValueType::Text; + ConfigApplyBackend backend = ConfigApplyBackend::None; + int applyOrder = 100; + ConfigDimensionScope targetScope = ConfigDimensionScope::Channel; + std::string groupId; + std::vector refreshAfterApply; + std::string compatibilityMode; + std::vector probeEvidence; + std::vector atomicActions; + }; + + struct ConfigVerifyStep + { + ChannelRef channel; + std::string propertyName; + std::string expectedValue; + bool required = true; + }; + + struct ConfigPlan + { + std::string planId; + ConfigSnapshot snapshot; + std::vector operations; + ConfigPlanImpact impact; + std::vector writePlan; + std::vector verifyPlan; + + std::size_t operation_count() const noexcept + { + return operations.size(); + } + }; + + struct ConfigReceiptEntry + { + ChannelRef channel; + std::string propertyName; + std::string requestedValue; + std::string readbackValue; + ConfigApplyBackend backend = ConfigApplyBackend::None; + ConfigApplyStatus status = ConfigApplyStatus::NotApplied; + }; + + struct ConfigReceipt + { + std::string receiptId; + std::string snapshotId; + std::string stateRevision; + std::string profileId; + int profileVersion = 0; + ConfigReceiptStatus status = ConfigReceiptStatus::NotApplied; + int64_t hostObservedTimeMs = 0; + std::vector entries; + std::vector warnings; + + std::size_t operation_count() const noexcept + { + return entries.size(); + } + }; + + enum class ConfigConflictPolicy : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Reject = 0, + Replan = 1, + }; + + enum class ConfigFailurePolicy : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + StopAndReport = 0, + BestEffort = 1, + }; + + struct ApplyPolicy + { + ConfigConflictPolicy onConflict = ConfigConflictPolicy::Reject; + ConfigFailurePolicy onFailure = ConfigFailurePolicy::StopAndReport; + bool verify = true; + std::string expectedStateRevision; + + static ApplyPolicy strict() + { + return ApplyPolicy(); + } + }; + + struct ConfigDifference + { + std::string path; + std::string expected; + std::string actual; + }; + + struct ConfigCompareResult + { + std::vector differences; + + bool match() const noexcept + { + return differences.empty(); + } + }; + + class ConfigComparator + { + public: + DAQ_API_EXPORT static ConfigCompareResult compare(const ConfigReceipt& expected, const ConfigReceipt& actual); + + }; + + class Configurator + { + public: + Configurator() = default; + + DAQ_API_EXPORT Result snapshot() const; + + DAQ_API_EXPORT Result validate(const ConfigIntent& intent) const; + + DAQ_API_EXPORT Result validate(const ConfigIntent& intent, const ConfigSnapshot& snapshot) const; + + DAQ_API_EXPORT Result plan(const ConfigIntent& intent, const ConfigSnapshot& snapshot) const; + + DAQ_API_EXPORT static Result plan_detached(const ConfigIntent& intent, const ConfigSnapshot& snapshot); + + DAQ_API_EXPORT Result apply(const ConfigPlan& plan, ApplyPolicy policy = ApplyPolicy::strict()) const; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class Runtime; + friend class MeasurementSession; + friend class Control; + friend class TaskEngine; + friend class AcquisitionBuilder; + friend class PlaybackBuilder; + friend class PlayAndAcquireBuilder; + DAQ_API_EXPORT explicit Configurator(CryDaq::detail::LegacySession session); + + std::shared_ptr session_; + bool hasSession_ = false; + }; +} +} + +#endif // CRYDAQ_WORKFLOW_CONFIG_H +// END SDK HEADER: crydaq/workflow/config.h + +// BEGIN SDK HEADER: crydaq/workflow/control.h +#ifndef CRYDAQ_WORKFLOW_CONTROL_H +#define CRYDAQ_WORKFLOW_CONTROL_H + +#include +#include +#include + + +// BEGIN SDK HEADER: crydaq/workflow/sync.h +#ifndef CRYDAQ_WORKFLOW_SYNC_H +#define CRYDAQ_WORKFLOW_SYNC_H + +#include +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace workflow +{ + struct ResetReferenceTimeOptions + { + bool acknowledgeDataLoss = false; + bool requireAllDevicesInSession = true; + std::string reason; + }; + + struct SyncStartResult + { + std::string operationId; + }; + + class DAQ_API_EXPORT Sync + { + public: + Sync() = default; + + Result capabilities(const DeviceRef& device) const; + + Result status(const DeviceRef& device) const; + + Result apply(const MultiDeviceSyncRequest& request) const; + + Result start(const MultiDeviceSyncRequest& request) const; + + Result progress(const std::string& operationId) const; + + Result wait(const std::string& operationId, int64_t timeoutMs = -1) const; + + Result cancel(const std::string& operationId) const; + + Result reset_reference_time(const DeviceRef& device, + const ResetReferenceTimeOptions& options) const; + + Result reset_reference_time(const std::vector& devices, + const ResetReferenceTimeOptions& options) const; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class Runtime; + friend class MeasurementSession; + friend class Control; + friend class Status; + friend class TaskEngine; + friend class AcquisitionBuilder; + friend class PlaybackBuilder; + friend class PlayAndAcquireBuilder; + explicit Sync(CryDaq::detail::LegacySession session); + Result> get_instance(const char* issueCode) const; + + std::shared_ptr session_; + bool hasSession_ = false; + }; +} +} + +#endif // CRYDAQ_WORKFLOW_SYNC_H +// END SDK HEADER: crydaq/workflow/sync.h + +namespace CryDaq +{ +namespace workflow +{ + class DAQ_API_EXPORT Control + { + public: + Control() = default; + + Result reset_reference_time(const DeviceRef& device, + const ResetReferenceTimeOptions& options) const; + + Result reset_reference_time(const std::vector& devices, + const ResetReferenceTimeOptions& options) const; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class Runtime; + friend class MeasurementSession; + friend class TaskEngine; + friend class AcquisitionBuilder; + friend class PlaybackBuilder; + friend class PlayAndAcquireBuilder; + explicit Control(CryDaq::detail::LegacySession session); + static Result detached_error(); + + std::shared_ptr session_; + bool hasSession_ = false; + }; +} +} + +#endif // CRYDAQ_WORKFLOW_CONTROL_H +// END SDK HEADER: crydaq/workflow/control.h + +// BEGIN SDK HEADER: crydaq/workflow/detached_config_planner.h +#ifndef CRYDAQ_WORKFLOW_DETACHED_CONFIG_PLANNER_H +#define CRYDAQ_WORKFLOW_DETACHED_CONFIG_PLANNER_H + +#include +#include + + +namespace CryDaq +{ +namespace workflow +{ + struct DetachedConfigWriteStep + { + ConfigPlanOperation operation; + DevicePropertyOperation deviceOperation; + std::string payloadJson; + }; + + class DAQ_API_EXPORT DetachedConfigPlanner + { + public: + Result plan(const ConfigIntent& intent, const ConfigSnapshot& snapshot) const; + Result preview(const ConfigIntent& intent, const ConfigSnapshot& snapshot) const; + Result> build_write_steps(const ConfigPlan& plan) const; + + }; +} +} + +#endif // CRYDAQ_WORKFLOW_DETACHED_CONFIG_PLANNER_H +// END SDK HEADER: crydaq/workflow/detached_config_planner.h + +// BEGIN SDK HEADER: crydaq/workflow/runtime.h +#ifndef CRYDAQ_WORKFLOW_RUNTIME_H +#define CRYDAQ_WORKFLOW_RUNTIME_H + +#include +#include + +// BEGIN SDK HEADER: crydaq/discovery.h +#ifndef CRYDAQ_DISCOVERY_H +#define CRYDAQ_DISCOVERY_H + +#include +#include + +namespace CryDaq +{ + enum class DiscoveryTransport + { + Unknown = 0, + OpenDaqNativeDirect, + OpenDaqNativeService, + OpenDaqAlias, + CryDaqLocal, + HttpSystemApi + }; + + enum class Reachability + { + Unknown = 0, + NotProbed, + Reachable, + Unreachable, + ProbeSkipped, + PolicyExcluded + }; + + struct DiscoveryEndpoint + { + std::string connectionString; + DiscoveryTransport transport = DiscoveryTransport::Unknown; + std::string host; + int port = 0; + int priority = 1000; + Reachability reachability = Reachability::NotProbed; + std::string source; + std::string lastError; + }; + + struct DiscoveredDevice + { + std::string deviceId; + std::string name; + std::string manufacturer; + std::string model; + std::string modelId; + std::string productId; + std::string serialNumber; + std::string recommendedConnectionString; + std::vector endpoints; + std::string status; + std::string rawOpenDaqInfoJson; + }; + + struct DiscoveryDiagnostic + { + std::string code; + std::string severity; + std::string message; + std::string remediation; + }; + + struct DiscoveryOptions + { + bool sonodaqOnly = true; + bool includeRawOpenDaqDevices = false; + bool probeReachability = false; + int probeTimeoutMs = 800; + bool includeHostNetworkDiagnostics = true; + }; + + struct DiscoveryResult + { + std::vector devices; + std::vector diagnostics; + }; +} + +#endif // CRYDAQ_DISCOVERY_H +// END SDK HEADER: crydaq/discovery.h +#include +#include + + +// BEGIN SDK HEADER: crydaq/workflow/can.h +#ifndef SONODAQ_COMPACT_FILE_19920D72E59B99C79288 +#define SONODAQ_COMPACT_FILE_19920D72E59B99C79288 +#include +#include +#include +#include +#include + +namespace CryDaq::workflow { +class MeasurementSession; +namespace can_detail { +struct Port; +struct Ticket; +struct Periodic; +} // namespace can_detail +enum class CanFlag : uint16_t { + Extended = 1, + Fd = 2, + Rtr = 4, + Brs = 8, + Esi = 16 +}; +enum class CanTxState : uint16_t { + Pending = 0, + Accepted = 1, + Submitted = 2, + Rejected = 3, + Cancelled = 4, + Indeterminate = 5 +}; +enum class CanSource : uint8_t { BusRx = 0, LocalTxEcho = 1 }; +enum class CanTimestampSource : uint8_t { + Unavailable = 0, + KernelSoftware = 1, + User = 2, + Hardware = 3 +}; +struct CanTxFrame { + uint32_t canId = 0; + uint16_t flags = 0; + uint8_t length = 0; + uint8_t dlc = 255; // RTR: requested length in DLC, payload length is zero. + std::array data{}; +}; +struct CanRxFrame { + CanTxFrame frame; + uint16_t portIndex = 0; + uint64_t sequence = 0, rawTimestampNs = 0, sessionEpoch = 0, + mappingRevision = 0; + uint32_t rawClockId = 0; + CanSource source = CanSource::BusRx; + CanTimestampSource timestampSource = CanTimestampSource::Unavailable; + // Transport preserves original time. Mapping is explicitly unavailable until + // calibrated. + bool measurementTimeValid = false; + int64_t measurementTimeNs = 0; +}; +struct CanTxResult { + uint64_t requestId = 0, itemId = 0, sessionEpoch = 0, timestampNs = 0, + resultSequence = 0; + uint32_t inputIndex = 0; + uint16_t portIndex = 0; + CanTxState state = CanTxState::Pending; + int32_t errorNumber = 0; +}; +struct CanFilter { + uint32_t id = 0, mask = 0; + bool extended = false; +}; +struct CanConfig { + bool fdEnabled = false, listenOnly = false; + uint32_t nominalBitrate = 500000, dataBitrate = 2000000, restartMs = 0; + std::vector filters; + // Ratio: 0.8 means 80%; zero keeps kernel automatic selection. + // Nonzero values must be finite and strictly between zero and one. + double nominalSamplePoint = 0.0, dataSamplePoint = 0.0; +}; +struct CanPortInfo { + std::string portId, channelPath; + uint16_t portIndex = 0; +}; +class DAQ_API_EXPORT CanSendTicket { +public: + CanSendTicket() = default; + uint64_t request_id() const noexcept; + Result> query() const; + // Timeout returns a snapshot including pending items; never retries + // transmission. + Result> wait(int64_t timeoutMs) const; + +private: + friend class CanPort; + explicit CanSendTicket(std::shared_ptr state); + std::shared_ptr state_; +}; +class DAQ_API_EXPORT CanPeriodicTask { +public: + CanPeriodicTask() = default; + uint64_t id() const noexcept; + Result status() const; + Result update(const CanTxFrame &frame, uint32_t periodMs); + Result update_frame(const CanTxFrame &frame); + Result set_period(uint32_t periodMs); + Result stop(); + +private: + friend class CanPort; + std::shared_ptr state_; +}; +class DAQ_API_EXPORT CanReader { +public: + CanReader() = default; + Result> read(size_t maxFrames = 256, + int64_t timeoutMs = 1000); + +private: + friend class CanPort; + std::weak_ptr port_; +}; +class DAQ_API_EXPORT CanPort { +public: + CanPort() = default; + Result configure(const CanConfig &config); + Result start(); + Result stop(); + Result close(); + Result status() const; + Result periodic_tasks() const; + Result send(const std::vector &frames); + Result start_periodic(const CanTxFrame &frame, + uint32_t periodMs); + CanReader reader() const; + +private: + friend class MeasurementSession; + explicit CanPort(std::shared_ptr state); + std::shared_ptr state_; +}; +} // namespace CryDaq::workflow +#endif // SONODAQ_COMPACT_FILE_19920D72E59B99C79288 +// END SDK HEADER: crydaq/workflow/can.h + +// BEGIN SDK HEADER: crydaq/workflow/status.h +#ifndef CRYDAQ_WORKFLOW_STATUS_H +#define CRYDAQ_WORKFLOW_STATUS_H + +#include +#include +#include +#include +#include + + +namespace CryDaq +{ +namespace workflow +{ + // Board indication: zero-valued playback with a white LED is Stopped, even while the task runs. + enum class ChannelState : uint8_t + { + Unknown = 0, Normal, Underload, Overload, Stopped, Playing, OverCurrent, Unsupported + }; + + struct InputOverload + { + std::string epoch; // Device-process epoch, used together with sequence for conditional ACK. + bool latched{}; + uint64_t sequence{}; // Number of sample batches containing an overload, not pulse count. + uint64_t timestampUs{}; // First over-threshold sample in the current or most recent latched interval. + }; + + struct ChannelStatus + { + ChannelRef channel; + ChannelType channelType{ChannelType::Input}; + ChannelState state{ChannelState::Unknown}; + uint32_t activeCauses{}; + // Age when the device created the snapshot; absent for Unknown/Unsupported. + Optional ageMs; + int32_t errorCode{}; + Optional inputOverload; + }; + + struct DeviceChannelSnapshot + { + DeviceRef device; + std::vector channels; + }; + + enum class AlarmAvailability : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Available = 0, + Unsupported = 1, + QueryFailed = 2, + }; + + enum ChannelAlarmCause : uint32_t + { + // Generated by tools/generate_workflow_contracts.py. + CauseNone = 0, + CauseInputOverload = 1, + CauseInputUnderload = 2, + CauseOutputOverCurrent1 = 4, + CauseOutputOverCurrent2 = 8, + }; + + struct ChannelAlarmStatus + { + ChannelRef channel; + ChannelType channelType{ChannelType::Input}; + AlarmAvailability availability{AlarmAvailability::Available}; + uint32_t activeCauses{}; + bool alarmActive{}; + bool overloaded{}; + int32_t errorCode{}; + std::string message; + }; + + struct DeviceAlarmSnapshot + { + DeviceRef device; + std::vector channels; + }; + + enum class DeviceEventSeverity : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Info = 0, + Warning = 1, + Error = 2, + Fatal = 3, + }; + + enum class DeviceStatusEventState : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Unknown = 0, + Recovered = 1, + Active = 2, + }; + + enum class DeviceStatusLocationKind : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Unknown = 0, + Device = 1, + Channel = 2, + }; + + struct DeviceStatusEvent + { + DeviceRef device; + Optional channel; + std::string code; + DeviceEventSeverity severity = DeviceEventSeverity::Info; + std::string message; + int64_t hostObservedTimeMs = 0; + Optional deviceTimeMs; + uint32_t rawCode = 0; + DeviceStatusEventState state = DeviceStatusEventState::Unknown; + uint8_t rawState = 0; + uint8_t rawSeverity = 0; + uint8_t rawLocation = 0; + DeviceStatusLocationKind locationKind = DeviceStatusLocationKind::Unknown; + int32_t boardIndex = -1; + int32_t channelIndex = -1; + bool active = false; + bool hasDeviceTimestampUs = false; + uint64_t deviceTimestampUs = 0; + }; + + using DeviceStatusCallback = void (*)(void* handle, const DeviceStatusEvent& event); + + class DAQ_API_EXPORT Status + { + public: + Status() = default; + + Result sync_status(const DeviceRef& device) const; + + Result device_alarms(const DeviceRef& device) const; + + // One device request; reads cached input alarms and output indications. + // The returned snapshot does not update itself. Unsupported firmware returns an error. + Result channel_statuses(const DeviceRef& device) const; + + // False means a newer observation, a different device epoch, or an active overload. + Result acknowledge_input_overload(const ChannelRef& channel, const InputOverload& observed) const; + + Result set_device_status_callback(DeviceStatusCallback callback, void* handle = nullptr) const; + Result set_device_status_callback( + DeviceStatusCallback callback, + void* handle, + std::shared_ptr candidate) const; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class Runtime; + friend class MeasurementSession; + friend class Control; + friend class TaskEngine; + friend class AcquisitionBuilder; + friend class PlaybackBuilder; + friend class PlayAndAcquireBuilder; + explicit Status(CryDaq::detail::LegacySession session); + std::shared_ptr session_; + bool hasSession_ = false; + }; +} +} + +#endif // CRYDAQ_WORKFLOW_STATUS_H +// END SDK HEADER: crydaq/workflow/status.h + +// BEGIN SDK HEADER: crydaq/workflow/task.h +#ifndef CRYDAQ_WORKFLOW_TASK_H +#define CRYDAQ_WORKFLOW_TASK_H + +#include +#include +#include +#include +#include +#include +#include + + + + + +// BEGIN SDK HEADER: crydaq/duplex_types.h +#ifndef CRYDAQ_DUPLEX_TYPES_H +#define CRYDAQ_DUPLEX_TYPES_H + + +namespace CryDaq +{ + + /** + * @brief 同时播放 + 采集请求 + */ + struct PlayAndRecordRequest + { + PlayRequest play; ///< 播放请求 + RecordRequest record; ///< 采集请求 + }; + +} // namespace CryDaq + +#endif // CRYDAQ_DUPLEX_TYPES_H +// END SDK HEADER: crydaq/duplex_types.h + +namespace CryDaq +{ +namespace workflow +{ + enum class RunMode : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + FiniteDuration = 0, + FiniteFrames = 1, + Continuous = 2, + FiniteFile = 3, + }; + + enum class StartPolicy : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Immediate = 0, + Synchronized = 1, + AtDeviceTime = 2, + AtHostTime = 3, + }; + + enum class TaskStatus : uint8_t + { + // Generated by tools/generate_workflow_contracts.py. + Created = 0, + Configured = 1, + Prepared = 2, + Running = 3, + Completed = 4, + Failed = 5, + Stopping = 6, + Stopped = 7, + }; + + struct TaskTimingSpec + { + int sampleRate = 0; + int64_t durationMs = 0; + int64_t finiteFrames = 0; + }; + + struct PlaybackStreamOptions + { + int startupBufferMs = 500; + int maxQueuedBufferMs = 5000; + int64_t startupOperationTimeoutMs = 15000; + }; + + struct AcquisitionTaskSpec + { + std::string name; + std::vector channels; + RunMode runMode = RunMode::FiniteDuration; + StartPolicy startPolicy = StartPolicy::Immediate; + int sampleRate = 0; + int64_t durationMs = 0; + int64_t finiteFrames = 0; + InputConfig input = InputConfig::voltage(); + SampleUnit outputUnit = SampleUnit::RawFs; + RecordOutput output; + std::vector alignGroups; + std::vector routes; + RouteProcessingOptions routeProcessing; + SampleUnit callbackUnit = SampleUnit::RawFs; + SampleCallback sampleCallback = nullptr; + AlignedSampleCallback alignedSampleCallback = nullptr; + DataCallback dataCallback = nullptr; + AlignedPcmCallback alignedPcmCallback = nullptr; + RouteBatchCallback routeBatchCallback = nullptr; + void* routeBatchCallbackHandle = nullptr; + void* dataCallbackHandle = nullptr; + }; + + struct PlaybackTaskSpec + { + std::string name; + std::vector channels; + RunMode runMode = RunMode::FiniteDuration; + StartPolicy startPolicy = StartPolicy::Immediate; + int sampleRate = 0; + int64_t durationMs = 0; + int64_t finiteFrames = 0; + std::vector items; + std::string filePath; ///< UTF-8 host file path. + SampleUnit inputUnit = SampleUnit::RawFs; + PlaybackTransport transport = PlaybackTransport::Zmq; + PlaybackStreamOptions stream; + std::vector rawSamples; + std::vector voltageSamples; + Optional playbackOptions; + }; + + struct PlaybackAnchorOptions + { + std::vector recordChannels; + std::vector recordAxisChannels; + bool resetReferenceTime = false; + ReferenceTimeResetPolicy referenceTimeResetPolicy = ReferenceTimeResetPolicy::Never; + bool acknowledgeDataLoss = false; + bool resetPlaybackDevicesReferenceTime = false; + int resetReferenceTimeMaxAttempts = 1; + int offsetCntForPlay = 0; + int maxAnchorWallDeltaMs = 45; + int64_t timeoutMs = -1; + }; + + using PlayAndAcquireAnchorOptions = PlaybackAnchorOptions; + + struct PlaybackResult + { + CryDaq::PlaybackStatus status; + Optional scheduledAnchor; + Optional selectedRecordAnchor; + }; + + struct PlaybackExecutionResult + { + PlaybackResult result; + }; + + struct PlaybackStartAlignedCaptureOptions + { + bool enabled = false; + int64_t preCaptureMs = 0; + bool cropToPlaybackStart = true; + // False preserves the legacy contract: duration is post-request + // capture time. True makes duration the total capture window, + // including pre-capture and blocking playback time. + bool captureDurationIncludesPlayback = false; + }; + + struct PlaybackStartAlignedCaptureChannelMetadata + { + CryDaq::ChannelRef channel; + bool playbackFirstFrameLocated = false; + bool cropped = false; + int64_t playbackFirstFrameSampleIndex = -1; + int64_t droppedSamples = 0; + long long playbackFirstFrameTimestamp = 0; + uint64_t recordAxisUtc100ms = 0; + uint32_t recordAxisFrameOffset = 0; + std::string errorInfo; + }; + + struct PlaybackStartAlignedCaptureMetadata + { + bool enabled = false; + bool captureCompleted = false; + bool playbackCompleted = false; + bool cropToPlaybackStart = false; + CryDaq::PlaybackRecordAnchorResult playback; + std::vector channels; + std::string errorInfo; + }; + + struct PlayAndAcquireResult + { + RecordResult acquisition; + AcquisitionResult acquisitionResult; + CryDaq::PlaybackStatus playbackStatus; + Optional scheduledAnchor; + Optional selectedRecordAnchor; + PlaybackStartAlignedCaptureMetadata playbackStartAlignedCapture; + }; + + struct PlayAndAcquireExecutionResult + { + PlayAndAcquireResult result; + }; + + struct PlayAndAcquireTaskSpec + { + std::string name; + AcquisitionTaskSpec acquisition; + PlaybackTaskSpec playback; + StartPolicy startPolicy = StartPolicy::Immediate; + std::vector anchorRecordChannels; + PlayAndAcquireAnchorOptions anchorOptions; + PlaybackStartAlignedCaptureOptions playbackStartAlignedCapture; + }; + + class AcquisitionTask + { + public: + DAQ_API_EXPORT AcquisitionTask(); + DAQ_API_EXPORT ~AcquisitionTask(); + DAQ_API_EXPORT AcquisitionTask(const AcquisitionTask& other); + DAQ_API_EXPORT AcquisitionTask& operator=(const AcquisitionTask& other); + DAQ_API_EXPORT AcquisitionTask(AcquisitionTask&& other) noexcept; + DAQ_API_EXPORT AcquisitionTask& operator=(AcquisitionTask&& other) noexcept; + + DAQ_API_EXPORT Result run(); + + DAQ_API_EXPORT Result run_routes(); + + DAQ_API_EXPORT Result scale_snapshot() const; + DAQ_API_EXPORT Result start(); + + DAQ_API_EXPORT Result stop(); + DAQ_API_EXPORT Result wait(int64_t timeoutMs = -1); + DAQ_API_EXPORT Result scale_snapshot(); + DAQ_API_EXPORT Result close(); + + DAQ_API_EXPORT TaskStatus status() const noexcept; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class TaskEngine; + friend class AcquisitionBuilder; + DAQ_API_EXPORT AcquisitionTask(CryDaq::detail::LegacySession session, AcquisitionTaskSpec spec); + Result start_impl(bool blockingRun); + struct Runtime; + + struct Impl; + std::unique_ptr impl_; + }; + + class PlaybackTask + { + public: + DAQ_API_EXPORT PlaybackTask(); + DAQ_API_EXPORT ~PlaybackTask(); + DAQ_API_EXPORT PlaybackTask(const PlaybackTask& other); + DAQ_API_EXPORT PlaybackTask& operator=(const PlaybackTask& other); + DAQ_API_EXPORT PlaybackTask(PlaybackTask&& other) noexcept; + DAQ_API_EXPORT PlaybackTask& operator=(PlaybackTask&& other) noexcept; + + DAQ_API_EXPORT Result run_result(); + + DAQ_API_EXPORT Result run(); + + DAQ_API_EXPORT Result start(const PlaybackAnchorOptions& anchorOptions = {}); + + DAQ_API_EXPORT Result write(const PlaybackStreamChunk& chunk, int64_t timeoutMs = -1); + + DAQ_API_EXPORT Result playback_status(); + + DAQ_API_EXPORT Result wait_for_anchor( + std::chrono::milliseconds timeout = std::chrono::seconds(30)); + + DAQ_API_EXPORT Result stop(PlaybackStopMode mode = PlaybackStopMode::Drain, + int64_t timeoutMs = 20000); + + DAQ_API_EXPORT Result wait(int64_t timeoutMs = -1); + DAQ_API_EXPORT Result close(); + DAQ_API_EXPORT TaskStatus status() const noexcept; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class TaskEngine; + friend class PlaybackBuilder; + DAQ_API_EXPORT PlaybackTask(CryDaq::detail::LegacySession session, PlaybackTaskSpec spec); + struct Execution; + + struct Impl; + std::unique_ptr impl_; + }; + + class PlayAndAcquireTask + { + public: + DAQ_API_EXPORT PlayAndAcquireTask(); + DAQ_API_EXPORT ~PlayAndAcquireTask(); + DAQ_API_EXPORT PlayAndAcquireTask(const PlayAndAcquireTask& other); + DAQ_API_EXPORT PlayAndAcquireTask& operator=(const PlayAndAcquireTask& other); + DAQ_API_EXPORT PlayAndAcquireTask(PlayAndAcquireTask&& other) noexcept; + DAQ_API_EXPORT PlayAndAcquireTask& operator=(PlayAndAcquireTask&& other) noexcept; + + DAQ_API_EXPORT Result run(); + + DAQ_API_EXPORT Result run_with_status(); + + DAQ_API_EXPORT Result run_with_playback_start_alignment(); + + DAQ_API_EXPORT Result start(); + + DAQ_API_EXPORT Result write_playback(const PlaybackStreamChunk& chunk, int64_t timeoutMs = -1); + + DAQ_API_EXPORT Result playback_status(); + + DAQ_API_EXPORT Result wait_for_anchor( + std::chrono::milliseconds timeout = std::chrono::seconds(30)); + + // Drain and close playback while acquisition remains active for post capture. + // Call stop() afterwards, including when this operation fails. + DAQ_API_EXPORT Result finish_playback(int64_t timeoutMs = 20000); + + DAQ_API_EXPORT Result stop(PlaybackStopMode mode = PlaybackStopMode::Drain, + int64_t timeoutMs = 20000); + + DAQ_API_EXPORT TaskStatus status() const noexcept; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class TaskEngine; + friend class PlayAndAcquireBuilder; + DAQ_API_EXPORT PlayAndAcquireTask(CryDaq::detail::LegacySession session, PlayAndAcquireTaskSpec spec); + struct StreamRuntime; + + struct Impl; + std::unique_ptr impl_; + }; + + class PlaybackStreamTask + { + public: + DAQ_API_EXPORT PlaybackStreamTask(); + DAQ_API_EXPORT ~PlaybackStreamTask(); + DAQ_API_EXPORT PlaybackStreamTask(const PlaybackStreamTask& other); + DAQ_API_EXPORT PlaybackStreamTask& operator=(const PlaybackStreamTask& other); + DAQ_API_EXPORT PlaybackStreamTask(PlaybackStreamTask&& other) noexcept; + DAQ_API_EXPORT PlaybackStreamTask& operator=(PlaybackStreamTask&& other) noexcept; + + DAQ_API_EXPORT Result write( + const std::vector& data, + int64_t timeoutMs = -1); + + DAQ_API_EXPORT Result stop( + const std::vector& connectionStrings, + bool abort = false); + + DAQ_API_EXPORT Result cancel(); + + DAQ_API_EXPORT Result close(); + + DAQ_API_EXPORT Result playback_status() const; + + DAQ_API_EXPORT TaskStatus status() const noexcept; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class TaskEngine; + DAQ_API_EXPORT explicit PlaybackStreamTask( + CryDaq::detail::LegacySession session, + std::string pid = "workflow-playback-stream", + PlaybackTransport transport = PlaybackTransport::Zmq); + struct Runtime; + + Result finish(PlaybackStopMode mode); + + static Result cached_cleanup_result( + const Runtime& runtime); + + CryDaq::PlaybackStatus cleanup_exception_status() const; + + Result cleanup( + PlaybackStopMode mode, + bool requireActive); + + struct Impl; + std::unique_ptr impl_; + }; + + class DAQ_API_EXPORT AcquisitionBuilder + { + public: + AcquisitionBuilder() = default; + + AcquisitionBuilder& channels(std::vector channels); + + AcquisitionBuilder& conditioning(InputConfig input); + + AcquisitionBuilder& input(InputConfig input); + + AcquisitionBuilder& unit(SampleUnit unit) noexcept; + + AcquisitionBuilder& output(RecordOutput output); + + AcquisitionBuilder& aligned(AlignGroupConfig group); + + AcquisitionBuilder& routes(std::vector routes); + + AcquisitionBuilder& add_route(RouteSpec route); + + AcquisitionBuilder& route_processing(RouteProcessingOptions options); + + AcquisitionBuilder& function_block_module_path(std::string path); + + AcquisitionBuilder& function_block_read_timeout_ms(int timeoutMs) noexcept; + + AcquisitionBuilder& finite_frames(int sampleRate, int64_t frameCount) noexcept; + + AcquisitionBuilder& finite_duration(int sampleRate, std::chrono::milliseconds duration) noexcept; + + AcquisitionBuilder& streaming(int sampleRate) noexcept; + + AcquisitionBuilder& on_frame(DataCallback callback) noexcept; + AcquisitionBuilder& on_frame(DataCallback callback, void* handle) noexcept; + + AcquisitionBuilder& on_aligned_pcm(AlignedPcmCallback callback) noexcept; + + AcquisitionBuilder& on_route_batch(RouteBatchCallback callback, void* handle = nullptr) noexcept; + + ValidationReport validate() const; + Result run() const; + + Result run_routes() const; + + Result start(); + + Result stop(); + + Result wait(int64_t timeoutMs = -1); + Result close(); + + TaskStatus status() const noexcept; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class MeasurementSession; + explicit AcquisitionBuilder(CryDaq::detail::LegacySession session); + AcquisitionTask create_task() const; + + std::shared_ptr session_; + AcquisitionTaskSpec spec_; + AcquisitionTask task_; + bool hasSession_ = false; + }; + + class DAQ_API_EXPORT PlaybackBuilder + { + public: + PlaybackBuilder() = default; + + PlaybackBuilder& channels(std::vector channels); + + PlaybackBuilder& source(PlaybackSource source); + + PlaybackBuilder& unit(SampleUnit unit) noexcept; + + PlaybackBuilder& transport(PlaybackTransport transport) noexcept; + + PlaybackBuilder& finite_frames(int sampleRate, int64_t frameCount) noexcept; + + PlaybackBuilder& finite_duration(int sampleRate, std::chrono::milliseconds duration) noexcept; + + PlaybackBuilder& streaming(int sampleRate) noexcept; + + PlaybackBuilder& startup_buffer(std::chrono::milliseconds duration) noexcept; + + PlaybackBuilder& max_queued_buffer(std::chrono::milliseconds duration) noexcept; + + PlaybackBuilder& synchronized(bool enabled = true) noexcept; + + PlaybackBuilder& anchor_record_channels(std::vector channels); + + PlaybackBuilder& anchor_options(PlaybackAnchorOptions options); + + ValidationReport validate() const; + Result run(); + + Result run_with_status(); + + Result start(); + + Result write(const PlaybackStreamChunk& chunk, int64_t timeoutMs = -1); + + Result playback_status(); + + Result wait_for_anchor( + std::chrono::milliseconds timeout = std::chrono::seconds(30)); + + Result stop(PlaybackStopMode mode = PlaybackStopMode::Drain, + int64_t timeoutMs = 20000); + + Result wait(int64_t timeoutMs = -1); + Result close(); + TaskStatus status() const noexcept; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class MeasurementSession; + explicit PlaybackBuilder(CryDaq::detail::LegacySession session); + std::shared_ptr session_; + PlaybackTaskSpec spec_; + PlaybackAnchorOptions anchorOptions_; + PlaybackTask task_; + bool hasSession_ = false; + }; + + class DAQ_API_EXPORT PlayAndAcquireBuilder + { + public: + PlayAndAcquireBuilder() = default; + + PlayAndAcquireBuilder& playback_channels(std::vector channels); + + PlayAndAcquireBuilder& playback_source(PlaybackSource source); + + PlayAndAcquireBuilder& playback_unit(SampleUnit unit) noexcept; + + PlayAndAcquireBuilder& playback_transport(PlaybackTransport transport) noexcept; + + PlayAndAcquireBuilder& acquisition_channels(std::vector channels); + + PlayAndAcquireBuilder& conditioning(InputConfig input); + + PlayAndAcquireBuilder& acquisition_unit(SampleUnit unit) noexcept; + + PlayAndAcquireBuilder& on_frame(DataCallback callback) noexcept; + PlayAndAcquireBuilder& on_frame(DataCallback callback, void* handle) noexcept; + + PlayAndAcquireBuilder& on_aligned_pcm(AlignedPcmCallback callback) noexcept; + + PlayAndAcquireBuilder& on_route_batch(RouteBatchCallback callback, void* handle = nullptr) noexcept; + + PlayAndAcquireBuilder& output(RecordOutput output); + + PlayAndAcquireBuilder& aligned(AlignGroupConfig group); + + PlayAndAcquireBuilder& acquisition_routes(std::vector routes); + + PlayAndAcquireBuilder& add_acquisition_route(RouteSpec route); + + PlayAndAcquireBuilder& acquisition_route_processing(RouteProcessingOptions options); + + PlayAndAcquireBuilder& acquisition_function_block_module_path(std::string path); + + PlayAndAcquireBuilder& acquisition_function_block_read_timeout_ms(int timeoutMs) noexcept; + + PlayAndAcquireBuilder& finite_frames(int sampleRate, int64_t frameCount) noexcept; + + PlayAndAcquireBuilder& finite_duration(int sampleRate, std::chrono::milliseconds duration) noexcept; + + PlayAndAcquireBuilder& streaming(int sampleRate) noexcept; + + PlayAndAcquireBuilder& playback_startup_buffer(std::chrono::milliseconds duration) noexcept; + + PlayAndAcquireBuilder& playback_max_queued_buffer(std::chrono::milliseconds duration) noexcept; + + PlayAndAcquireBuilder& synchronized(bool enabled = true) noexcept; + + PlayAndAcquireBuilder& anchor_record_channels(std::vector channels); + + PlayAndAcquireBuilder& anchor_options(PlayAndAcquireAnchorOptions options); + + Result run() const; + + Result run_with_status() const; + + Result start(); + + Result write_playback(const PlaybackStreamChunk& chunk, int64_t timeoutMs = -1); + + Result playback_status(); + + Result wait_for_anchor( + std::chrono::milliseconds timeout = std::chrono::seconds(30)); + + Result finish_playback(int64_t timeoutMs = 20000); + + Result stop(PlaybackStopMode mode = PlaybackStopMode::Drain, + int64_t timeoutMs = 20000); + + TaskStatus status() const noexcept; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class MeasurementSession; + explicit PlayAndAcquireBuilder(CryDaq::detail::LegacySession session); + std::shared_ptr session_; + PlayAndAcquireTaskSpec spec_; + PlayAndAcquireTask task_; + bool hasSession_ = false; + }; + + class DAQ_API_EXPORT TaskEngine + { + public: + TaskEngine() = default; + + AcquisitionTask create_acquisition(AcquisitionTaskSpec spec) const; + + PlaybackTask create_playback(PlaybackTaskSpec spec) const; + + PlayAndAcquireTask create_play_and_acquire(PlayAndAcquireTaskSpec spec) const; + + PlaybackStreamTask create_playback_stream( + std::string pid = "workflow-playback-stream", + PlaybackTransport transport = PlaybackTransport::Zmq) const; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class MeasurementSession; + explicit TaskEngine(CryDaq::detail::LegacySession session); + std::shared_ptr session_; + bool hasSession_ = false; + }; +} +} + +#endif // CRYDAQ_WORKFLOW_TASK_H +// END SDK HEADER: crydaq/workflow/task.h + +namespace CryDaq +{ +namespace workflow +{ + struct RuntimeOptions + { + LoggingConfig logging; + void* callbackHandle = nullptr; + }; + + class DAQ_API_EXPORT MeasurementSession + { + public: + MeasurementSession() = default; + + bool is_open() const noexcept; + + Result> devices() const; + + Result device_dates(const std::string& connectionString) const; + + Result> device_dates() const; + + Result close(); + + Result> device_modules() const; + Result signal_generator(const std::string& connectionString) const; + Result enable_can(const std::string& connectionString, bool enabled) const; + Result> can_ports(const std::string& connectionString) const; + Result can(const std::string& connectionString, const std::string& portId) const; + Capabilities capabilities() const; + + Configurator configurator() const; + + Sync sync() const; + + Status status() const; + + Control control() const; + + TaskEngine task_engine() const; + + AcquisitionBuilder acquisition() const; + + PlaybackBuilder playback() const; + + PlayAndAcquireBuilder play_and_acquire() const; + + private: + friend struct CryDaq::detail::SessionAccess; + friend class Runtime; + friend class Control; + friend class TaskEngine; + friend class AcquisitionBuilder; + friend class PlaybackBuilder; + friend class PlayAndAcquireBuilder; + explicit MeasurementSession(CryDaq::detail::LegacySession legacy); + std::shared_ptr legacy_; + bool hasLegacy_ = false; + }; + + class DAQ_API_EXPORT Runtime + { + public: + Runtime(); + + explicit Runtime(RuntimeOptions options); + + static Result create(RuntimeOptions options = RuntimeOptions()); + + static const char* version() noexcept { return VERSION; } + InstancePolicy instance_policy() const noexcept; + + Result> discover() const; + + Result discover_devices(const DiscoveryOptions& options = {}) const; + Result open_device(const std::string& deviceId, const DiscoveryResult& discovery, DeviceOpenMode mode = DeviceOpenMode::Exclusive) const; + Result open(const DeviceOpenRequest& request) const; + + Result open_many(const std::vector& requests) const; + + private: + RuntimeOptions options_; + std::shared_ptr legacy_; + }; +} +} + +#endif // CRYDAQ_WORKFLOW_RUNTIME_H +// END SDK HEADER: crydaq/workflow/runtime.h + +#endif // CRYDAQ_WORKFLOW_SDK_H +// END SDK HEADER: crydaq/workflow/sdk.h + +// Shared public utilities available from either domain entry. + +#endif // CRYDAQ_WORKFLOW_H +// END SDK HEADER: workflow.h + +#endif // SONODAQ_COMPACT_WORKFLOW_H diff --git a/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/lib/libcrydaqwrapper.dylib b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/lib/libcrydaqwrapper.dylib new file mode 100755 index 0000000..748fcf6 Binary files /dev/null and b/plugins/opentest_sonodaq_plugin/macos/sonodaq-sdk-1.4.0-macos-arm64-cpp/sdk/lib/libcrydaqwrapper.dylib differ diff --git a/plugins/opentest_sonodaq_plugin/package/publish-macos.py b/plugins/opentest_sonodaq_plugin/package/publish-macos.py new file mode 100644 index 0000000..24a3f54 --- /dev/null +++ b/plugins/opentest_sonodaq_plugin/package/publish-macos.py @@ -0,0 +1,42 @@ +"""Stage a macOS SonoDAQ runtime and publish the standard audio-device package.""" +import argparse +import json +from pathlib import Path +import shutil +import subprocess +import sys + + +def main(): + plugin = Path(__file__).resolve().parents[1] + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--library', type=Path, required=True) + parser.add_argument('--sdk', type=Path, default=plugin / 'macos/sonodaq-sdk-1.4.0-macos-arm64-cpp') + parser.add_argument('--stage', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--framework', type=Path, required=True) + args = parser.parse_args() + if args.stage.exists() and any(args.stage.iterdir()): + parser.error('--stage must be empty; existing outputs are not overwritten') + shutil.copytree(args.sdk / 'runtime', args.stage, dirs_exist_ok=True) + entry = 'libOpenTestSonoDaqDevicePlugin.dylib' + shutil.copy2(args.library, args.stage / entry) + # Strip only debug/local symbols from staging copies. Keep all dynamic exports, + # all SDK modules and the original SDK unchanged; the package limit is 128 MiB. + for library in sorted(args.stage.rglob('*.dylib')): + exports = subprocess.check_output(['nm', '-gjU', str(library)]) + subprocess.run(['strip', '-S', '-x', str(library)], check=True) + if subprocess.check_output(['nm', '-gjU', str(library)]) != exports: + raise RuntimeError('Stripping changed exported symbols: ' + library.name) + subprocess.run(['codesign', '--force', '--sign', '-', str(library)], check=True) + files = sorted(p.relative_to(args.stage).as_posix() for p in args.stage.rglob('*') if p.is_file()) + manifest = dict(schemaVersion=1, version='1.0.0', packageId='opentest.sonodaq.device', + pluginKind='audio-device', entry=entry, files=files) + (args.stage / 'plugin-package.json').write_text(json.dumps(manifest, indent=2) + '\n') + subprocess.run([sys.executable, str(args.framework / 'scripts/plugins/package/audio_otplugin.py'), + '--source', str(args.stage), '--output', str(args.output), + '--platform', 'macos-arm64'], check=True) + + +if __name__ == '__main__': + main() diff --git a/plugins/opentest_sonodaq_plugin/tests/CMakeLists.txt b/plugins/opentest_sonodaq_plugin/tests/CMakeLists.txt index 9b5d483..1c8bf11 100644 --- a/plugins/opentest_sonodaq_plugin/tests/CMakeLists.txt +++ b/plugins/opentest_sonodaq_plugin/tests/CMakeLists.txt @@ -22,6 +22,9 @@ foreach(entry IN LISTS _sonodaq_tests) if(SONODAQ_SDK_LIBRARY) target_link_libraries(${target} PRIVATE "${SONODAQ_SDK_LIBRARY}") endif() + if(APPLE AND SONODAQ_SDK_ROOT) + set_target_properties(${target} PROPERTIES BUILD_RPATH "${SONODAQ_SDK_ROOT}/runtime") + endif() add_test(NAME ${target} COMMAND ${target}) set_tests_properties(${target} PROPERTIES TIMEOUT 30) if(WIN32)