snapshot.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // 线程安全"最新快照" —— 推理线程写、Modbus 线程读。
  2. //
  3. // 关键约束:PLC 读到的 12 个字必须来自同一次完整写入,不能出现"半个旧结果 + 半个新结果"。
  4. // 因此这里存的是已经编码好的完整字数组(含 CRC),读侧整体拷贝(12 个字,开销可忽略)。
  5. #pragma once
  6. #include <atomic>
  7. #include <cstdint>
  8. #include <mutex>
  9. #include <vector>
  10. #include "portcv/schema.hpp"
  11. namespace portcv {
  12. class LatestSnapshot {
  13. public:
  14. LatestSnapshot() : words_(VisionSnapshot{}.to_registers()) {}
  15. /// 写入一张新快照(编码 + CRC 在锁外完成,锁内只做一次指针交换级别的拷贝)。
  16. void store(const VisionSnapshot& snapshot) {
  17. std::vector<uint16_t> words = snapshot.to_registers();
  18. {
  19. std::lock_guard<std::mutex> lock(mu_);
  20. words_.swap(words);
  21. }
  22. version_.fetch_add(1, std::memory_order_release);
  23. }
  24. /// 读取当前快照的字数组(12 字)。
  25. std::vector<uint16_t> load() const {
  26. std::lock_guard<std::mutex> lock(mu_);
  27. return words_;
  28. }
  29. /// 写入次数(单调递增;用于判断"有没有新结果",与 seq 无关)。
  30. uint64_t version() const { return version_.load(std::memory_order_acquire); }
  31. void reset() { store(VisionSnapshot{}); }
  32. private:
  33. mutable std::mutex mu_;
  34. std::vector<uint16_t> words_;
  35. std::atomic<uint64_t> version_{0};
  36. };
  37. /// PLC → 视觉的指令槽:Modbus 线程写,推理线程读/取走。
  38. class CommandSlot {
  39. public:
  40. void set(const PlcCommand& command) {
  41. {
  42. std::lock_guard<std::mutex> lock(mu_);
  43. command_ = command;
  44. }
  45. version_.fetch_add(1, std::memory_order_release);
  46. }
  47. PlcCommand get() const {
  48. std::lock_guard<std::mutex> lock(mu_);
  49. return command_;
  50. }
  51. /// 取走指令(读后清零,模拟"PLC 写 1 → 视觉读走并清零"的握手)。
  52. PlcCommand take() {
  53. std::lock_guard<std::mutex> lock(mu_);
  54. PlcCommand out = command_;
  55. command_ = PlcCommand{};
  56. return out;
  57. }
  58. uint64_t version() const { return version_.load(std::memory_order_acquire); }
  59. private:
  60. mutable std::mutex mu_;
  61. PlcCommand command_{};
  62. std::atomic<uint64_t> version_{0};
  63. };
  64. } // namespace portcv