// 线程安全"最新快照" —— 推理线程写、Modbus 线程读。 // // 关键约束:PLC 读到的 12 个字必须来自同一次完整写入,不能出现"半个旧结果 + 半个新结果"。 // 因此这里存的是已经编码好的完整字数组(含 CRC),读侧整体拷贝(12 个字,开销可忽略)。 #pragma once #include #include #include #include #include "portcv/schema.hpp" namespace portcv { class LatestSnapshot { public: LatestSnapshot() : words_(VisionSnapshot{}.to_registers()) {} /// 写入一张新快照(编码 + CRC 在锁外完成,锁内只做一次指针交换级别的拷贝)。 void store(const VisionSnapshot& snapshot) { std::vector words = snapshot.to_registers(); { std::lock_guard lock(mu_); words_.swap(words); } version_.fetch_add(1, std::memory_order_release); } /// 读取当前快照的字数组(12 字)。 std::vector load() const { std::lock_guard lock(mu_); return words_; } /// 写入次数(单调递增;用于判断"有没有新结果",与 seq 无关)。 uint64_t version() const { return version_.load(std::memory_order_acquire); } void reset() { store(VisionSnapshot{}); } private: mutable std::mutex mu_; std::vector words_; std::atomic version_{0}; }; /// PLC → 视觉的指令槽:Modbus 线程写,推理线程读/取走。 class CommandSlot { public: void set(const PlcCommand& command) { { std::lock_guard lock(mu_); command_ = command; } version_.fetch_add(1, std::memory_order_release); } PlcCommand get() const { std::lock_guard lock(mu_); return command_; } /// 取走指令(读后清零,模拟"PLC 写 1 → 视觉读走并清零"的握手)。 PlcCommand take() { std::lock_guard lock(mu_); PlcCommand out = command_; command_ = PlcCommand{}; return out; } uint64_t version() const { return version_.load(std::memory_order_acquire); } private: mutable std::mutex mu_; PlcCommand command_{}; std::atomic version_{0}; }; } // namespace portcv