69888621cd
v9.1 — Distributed Computing (超越 Parasolid): - cluster_engine: ClusterManager, TaskScheduler(DAG+Kahn), 4 load-balance strategies - distributed_boolean, distributed_marching_cubes, distributed_ray_tracing - grpc_service: BrepOps/MeshOps/SdfOps RPC, streaming, TLS, connection pool - ~750 lines v9.2 — Cloud-Native + KBE + WASM + Digital Twin (34/34 tests passing): - cloud_native: CloudSession, OperationalTransform, DeltaSync, Serverless, ObjectStorage - knowledge_engine: CheckMate(13 rules), RuleEngine, DesignTable, GA+Adam optimizer - vde_wasm: WasmBridge, WebWorkerPool, SharedArrayBuffer, IndexedDB - dt_engine: DigitalTwin, MQTT/OPC-UA, RealTimeSync, PredictiveMaintenance(RUL) - 3950 lines, 34 tests all passing Pending: AI/ML integration (retrying) 18 files, ~4700 lines
377 lines
13 KiB
C++
377 lines
13 KiB
C++
#pragma once
|
||
/// @file dt_engine.h 数字孪生引擎
|
||
/// @ingroup digital_twin
|
||
|
||
#include <string>
|
||
#include <vector>
|
||
#include <map>
|
||
#include <memory>
|
||
#include <functional>
|
||
#include <optional>
|
||
#include <chrono>
|
||
#include <cstdint>
|
||
#include <mutex>
|
||
#include <shared_mutex>
|
||
#include <deque>
|
||
|
||
namespace vde::dt {
|
||
|
||
// ═══════════════════════════════════════════════════════
|
||
// 基础类型
|
||
// ═══════════════════════════════════════════════════════
|
||
|
||
/// 传感器读数
|
||
struct SensorReading {
|
||
std::string sensor_id;
|
||
std::string sensor_type; // "temperature", "vibration", "pressure", "position" ...
|
||
double value = 0.0;
|
||
std::string unit;
|
||
std::chrono::system_clock::time_point timestamp;
|
||
double quality = 1.0; // 0.0 ~ 1.0 数据质量
|
||
};
|
||
|
||
/// 传感器定义
|
||
struct SensorDef {
|
||
std::string id;
|
||
std::string type;
|
||
std::string unit;
|
||
std::string location; // 在物理资产上的位置描述
|
||
double range_min = 0.0;
|
||
double range_max = 100.0;
|
||
double accuracy = 0.01; // 精度
|
||
int sample_rate_hz = 1;
|
||
};
|
||
|
||
/// 资产状态快照
|
||
struct AssetState {
|
||
std::string asset_id;
|
||
std::map<std::string, double> sensor_values; // sensor_id → value
|
||
std::chrono::system_clock::time_point timestamp;
|
||
uint64_t version = 0;
|
||
};
|
||
|
||
// ═══════════════════════════════════════════════════════
|
||
// DigitalTwin —— 物理资产数字映射
|
||
// ═══════════════════════════════════════════════════════
|
||
|
||
/**
|
||
* @brief 数字孪生 —— 物理资产数字映射
|
||
*
|
||
* 将物理设备的几何模型、材料属性、运行状态
|
||
* 同步到数字空间,实现虚实映射。
|
||
*
|
||
* @ingroup digital_twin
|
||
*/
|
||
class DigitalTwin {
|
||
public:
|
||
explicit DigitalTwin(std::string asset_id);
|
||
~DigitalTwin();
|
||
|
||
/// 配置数字孪生
|
||
void configure(const std::string& model_path, // 3D 模型路径
|
||
const std::string& material_db = "");
|
||
|
||
/// 注册传感器
|
||
void register_sensor(const SensorDef& sensor);
|
||
|
||
/// 获取传感器列表
|
||
[[nodiscard]] std::vector<SensorDef> sensors() const;
|
||
|
||
/// 更新传感器读数(来自 IoT)
|
||
void update_reading(const SensorReading& reading);
|
||
|
||
/// 批量更新传感器读数
|
||
void update_readings(const std::vector<SensorReading>& readings);
|
||
|
||
/// 获取最新读数
|
||
[[nodiscard]] std::optional<double> latest_reading(const std::string& sensor_id) const;
|
||
|
||
/// 获取当前资产状态
|
||
[[nodiscard]] AssetState current_state() const;
|
||
|
||
/// 获取历史读数(时间窗口内)
|
||
[[nodiscard]] std::vector<SensorReading> history(const std::string& sensor_id,
|
||
std::chrono::minutes window) const;
|
||
|
||
/// 资产 ID
|
||
[[nodiscard]] const std::string& asset_id() const { return asset_id_; }
|
||
|
||
/// 状态版本号
|
||
[[nodiscard]] uint64_t version() const { return version_; }
|
||
|
||
/// 设置可视化状态(颜色/透明度等)
|
||
void set_visual_state(const std::string& key, double value);
|
||
|
||
/// 获取可视化状态
|
||
[[nodiscard]] std::optional<double> visual_state(const std::string& key) const;
|
||
|
||
private:
|
||
std::string asset_id_;
|
||
std::string model_path_;
|
||
std::map<std::string, SensorDef> sensor_defs_;
|
||
std::map<std::string, SensorReading> latest_readings_;
|
||
std::map<std::string, std::deque<SensorReading>> history_;
|
||
std::map<std::string, double> visual_states_;
|
||
uint64_t version_ = 0;
|
||
size_t max_history_per_sensor_ = 10000;
|
||
mutable std::shared_mutex mutex_;
|
||
};
|
||
|
||
// ═══════════════════════════════════════════════════════
|
||
// IoT Sensor 数据接入 (MQTT / OPC-UA)
|
||
// ═══════════════════════════════════════════════════════
|
||
|
||
/// IoT 协议类型
|
||
enum class IoTProtocol {
|
||
MQTT,
|
||
OPC_UA,
|
||
MODBUS,
|
||
HTTP_REST,
|
||
COAP
|
||
};
|
||
|
||
/// IoT 连接配置
|
||
struct IoTConfig {
|
||
IoTProtocol protocol = IoTProtocol::MQTT;
|
||
std::string broker_url; // MQTT broker: tcp://192.168.1.100:1883
|
||
std::string opcua_endpoint; // OPC-UA: opc.tcp://192.168.1.100:4840
|
||
std::string client_id;
|
||
std::string username;
|
||
std::string password;
|
||
int qos = 1;
|
||
int keepalive_sec = 60;
|
||
bool use_tls = false;
|
||
};
|
||
|
||
/**
|
||
* @brief IoT 传感器数据接入层
|
||
*
|
||
* 支持 MQTT / OPC-UA / Modbus 等工业物联网协议。
|
||
* 从传感器网关采集实时数据并推送到 DigitalTwin。
|
||
*
|
||
* @ingroup digital_twin
|
||
*/
|
||
class IoTConnector {
|
||
public:
|
||
IoTConnector() = default;
|
||
~IoTConnector();
|
||
|
||
/// 配置连接
|
||
bool configure(const IoTConfig& config);
|
||
|
||
/// 连接到 IoT broker / server
|
||
bool connect();
|
||
|
||
/// 断开连接
|
||
void disconnect();
|
||
|
||
/// 是否已连接
|
||
[[nodiscard]] bool is_connected() const { return connected_; }
|
||
|
||
/// 订阅主题(MQTT)/ 节点(OPC-UA)
|
||
bool subscribe(const std::string& topic_or_node);
|
||
|
||
/// 取消订阅
|
||
bool unsubscribe(const std::string& topic_or_node);
|
||
|
||
/// 发布消息(MQTT)
|
||
bool publish(const std::string& topic, const std::vector<uint8_t>& payload);
|
||
|
||
/// 读取 OPC-UA 节点值
|
||
std::optional<double> read_opcua_node(const std::string& node_id);
|
||
|
||
/// 写入 OPC-UA 节点值
|
||
bool write_opcua_node(const std::string& node_id, double value);
|
||
|
||
/// 设置数据回调(推送模式)
|
||
using DataCallback = std::function<void(const SensorReading&)>;
|
||
void on_data(DataCallback callback);
|
||
|
||
/// 轮询拉取最新读数
|
||
std::vector<SensorReading> poll();
|
||
|
||
private:
|
||
IoTConfig config_;
|
||
bool connected_ = false;
|
||
DataCallback data_callback_;
|
||
|
||
// Buffer for incoming readings
|
||
std::vector<SensorReading> buffer_;
|
||
std::mutex buffer_mutex_;
|
||
};
|
||
|
||
// ═══════════════════════════════════════════════════════
|
||
// RealTimeSync —— 实时状态同步
|
||
// ═══════════════════════════════════════════════════════
|
||
|
||
/// 同步方向
|
||
enum class SyncDirection {
|
||
PHYSICAL_TO_DIGITAL, // 物理→数字(传感器→模型)
|
||
DIGITAL_TO_PHYSICAL, // 数字→物理(控制指令)
|
||
BIDIRECTIONAL // 双向
|
||
};
|
||
|
||
/// 同步策略
|
||
enum class SyncStrategy {
|
||
TIME_BASED, // 按时间间隔
|
||
EVENT_BASED, // 事件驱动(值变化超阈值)
|
||
HYBRID // 混合
|
||
};
|
||
|
||
/// 同步配置
|
||
struct SyncConfig {
|
||
SyncDirection direction = SyncDirection::PHYSICAL_TO_DIGITAL;
|
||
SyncStrategy strategy = SyncStrategy::TIME_BASED;
|
||
std::chrono::milliseconds interval{100}; // 时间间隔(TIME_BASED)
|
||
double change_threshold = 0.01; // 变化阈值(EVENT_BASED)
|
||
bool compress = true; // 是否压缩传输
|
||
bool batch = true; // 是否批量同步
|
||
size_t batch_size = 50; // 批量大小
|
||
};
|
||
|
||
/**
|
||
* @brief 实时同步引擎
|
||
*
|
||
* 维护物理资产与数字孪生之间的实时状态同步。
|
||
* 支持时间驱动和事件驱动两种同步策略。
|
||
*
|
||
* @ingroup digital_twin
|
||
*/
|
||
class RealTimeSync {
|
||
public:
|
||
RealTimeSync() = default;
|
||
|
||
/// 绑定数字孪生和 IoT 连接器
|
||
void bind(DigitalTwin* dt, IoTConnector* iot);
|
||
|
||
/// 启动同步
|
||
bool start(const SyncConfig& config);
|
||
|
||
/// 停止同步
|
||
void stop();
|
||
|
||
/// 是否在运行
|
||
[[nodiscard]] bool is_running() const { return running_; }
|
||
|
||
/// 手动触发一次同步
|
||
void sync_once();
|
||
|
||
/// 获取同步统计
|
||
struct Stats {
|
||
uint64_t sync_count = 0;
|
||
uint64_t bytes_synced = 0;
|
||
uint64_t errors = 0;
|
||
std::chrono::milliseconds last_sync_duration{0};
|
||
};
|
||
[[nodiscard]] Stats stats() const;
|
||
|
||
/// 获取最近同步的数据点
|
||
[[nodiscard]] std::vector<SensorReading> last_sync_data() const;
|
||
|
||
private:
|
||
DigitalTwin* dt_ = nullptr;
|
||
IoTConnector* iot_ = nullptr;
|
||
SyncConfig config_;
|
||
bool running_ = false;
|
||
Stats stats_;
|
||
|
||
std::vector<SensorReading> last_sync_data_;
|
||
mutable std::mutex mutex_;
|
||
|
||
void time_based_loop();
|
||
void event_based_check();
|
||
};
|
||
|
||
// ═══════════════════════════════════════════════════════
|
||
// PredictiveMaintenance —— 预测性维护
|
||
// ═══════════════════════════════════════════════════════
|
||
|
||
/// 预测结果
|
||
struct MaintenancePrediction {
|
||
std::string component_id;
|
||
double failure_probability; // 0.0 ~ 1.0
|
||
std::chrono::system_clock::time_point estimated_failure_time;
|
||
std::chrono::hours remaining_useful_life;
|
||
std::string recommendation;
|
||
int severity; // 1-5
|
||
};
|
||
|
||
/// 时序窗口配置
|
||
struct TimeWindow {
|
||
std::chrono::hours lookback{720}; // 回溯窗口(默认 30 天)
|
||
std::chrono::hours forecast_horizon{168}; // 预测窗口(默认 7 天)
|
||
int min_data_points = 100;
|
||
double anomaly_threshold = 3.0; // 异常检测 Z-score 阈值
|
||
};
|
||
|
||
/**
|
||
* @brief 预测性维护引擎
|
||
*
|
||
* 基于时序数据(振动、温度、压力等)进行故障预测。
|
||
* 提供 RUL(剩余使用寿命)估算和维护建议。
|
||
*
|
||
* @ingroup digital_twin
|
||
*/
|
||
class PredictiveMaintenance {
|
||
public:
|
||
PredictiveMaintenance() = default;
|
||
|
||
/// 添加历史传感器数据
|
||
void add_readings(const std::string& sensor_id,
|
||
const std::vector<SensorReading>& readings);
|
||
|
||
/// 训练模型
|
||
bool train(const std::string& sensor_id,
|
||
const TimeWindow& window = TimeWindow{});
|
||
|
||
/// 预测故障概率和 RUL
|
||
MaintenancePrediction predict(const std::string& component_id,
|
||
const std::string& sensor_id);
|
||
|
||
/// 批量预测所有组件
|
||
std::vector<MaintenancePrediction> predict_all();
|
||
|
||
/// 设置退化阈值
|
||
void set_degradation_threshold(const std::string& sensor_id,
|
||
double threshold);
|
||
|
||
/// 计算趋势(线性回归斜率)
|
||
[[nodiscard]] double compute_trend(const std::string& sensor_id,
|
||
std::chrono::hours lookback) const;
|
||
|
||
/// 计算移动平均
|
||
[[nodiscard]] std::vector<double> moving_average(const std::string& sensor_id,
|
||
size_t window_size) const;
|
||
|
||
/// 异常检测
|
||
[[nodiscard]] std::vector<std::chrono::system_clock::time_point>
|
||
detect_anomalies(const std::string& sensor_id,
|
||
const TimeWindow& window) const;
|
||
|
||
/// 获取传感器数据统计
|
||
struct SensorStats {
|
||
double mean = 0.0;
|
||
double stddev = 0.0;
|
||
double min_val = 0.0;
|
||
double max_val = 0.0;
|
||
size_t count = 0;
|
||
};
|
||
[[nodiscard]] SensorStats sensor_statistics(const std::string& sensor_id) const;
|
||
|
||
private:
|
||
std::map<std::string, std::vector<SensorReading>> data_;
|
||
std::map<std::string, double> degradation_thresholds_;
|
||
std::map<std::string, bool> trained_;
|
||
mutable std::shared_mutex mutex_;
|
||
|
||
// 时序预测内部方法
|
||
double compute_slope(const std::vector<double>& values) const;
|
||
double compute_rul(double current_value, double degradation_rate,
|
||
double failure_threshold) const;
|
||
std::vector<double> extract_values(const std::string& sensor_id,
|
||
std::chrono::hours lookback) const;
|
||
bool check_degradation(const std::string& sensor_id) const;
|
||
};
|
||
|
||
} // namespace vde::dt
|