schema.hpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // 公共数据结构 —— 与 Python 侧 portcv/schema.py 一一对应(字段名、语义、字宽都一致)。
  2. //
  3. // 约定:
  4. // * 检测框使用像素坐标,原点左上角,y 向下增大;
  5. // * SceneState 的枚举值就是最终写给 PLC 的编码(0/1/2/255),改前先确认 PLC 侧;
  6. // * VisionSnapshot 是"视觉 → PLC"的唯一载体,Modbus/TCP 服务端只从它取数。
  7. #pragma once
  8. #include <cstdint>
  9. #include <cstring>
  10. #include <stdexcept>
  11. #include <string>
  12. #include <utility>
  13. #include <vector>
  14. #include "portcv/crc16.hpp"
  15. namespace portcv {
  16. /// 反馈给 PLC 的场景编码(与 Python SceneState 完全一致)。
  17. enum class SceneState : int {
  18. NOT_ON_TRAIN = 0, ///< 集装箱不在车上
  19. BED = 1, ///< 车斗(敞车)
  20. FLATBED = 2, ///< 平板车(平车)
  21. UNKNOWN = 255, ///< 视觉未就绪 / 结果不可信
  22. };
  23. inline const char* scene_state_label(int state) {
  24. switch (state) {
  25. case 0: return "not_on_train";
  26. case 1: return "bed";
  27. case 2: return "flatbed";
  28. default: return "unknown";
  29. }
  30. }
  31. /// 反馈指令的取值(PLC → 视觉)。
  32. enum : uint16_t {
  33. CMD_IDLE = 0,
  34. CMD_REQUEST = 1,
  35. CMD_RESET = 2,
  36. CMD_CLEAR_STATS = 3,
  37. };
  38. /// VisionSnapshot::flags 的位定义(与 Python StatusBits 一致,不可随意改位)。
  39. enum class StatusBits : uint16_t {
  40. READY = 1u << 0, ///< 模型已加载且完成预热
  41. FRAME_OK = 1u << 1, ///< 最近一帧是新的(未超过 stale 时限)
  42. STABLE = 1u << 2, ///< 状态稳定,可用于联锁/自动落箱
  43. LOW_FPS = 1u << 3, ///< 帧率低于下限
  44. FRAME_TIMEOUT = 1u << 4, ///< 长时间拿不到帧(相机/网络异常)
  45. ON_DEMAND = 1u << 5, ///< 当前处于 PLC 请求触发的按需识别
  46. RESULT_VALID = 1u << 6, ///< 置信度达到阈值,结果有效
  47. PUBLISH_OK = 1u << 7, ///< 最近一次向 PLC 发布成功(服务端模式恒为 1)
  48. PERCEPTION_UNCERTAIN = 1u << 8, ///< 感知不确定;与 RESULT_VALID 互斥
  49. MRC_REQUEST = 1u << 9, ///< 请求 PLC 进入最小风险状态
  50. SENSOR_DEGRADED = 1u << 10, ///< 图像质量/传感器退化
  51. CALIB_STALE = 1u << 11, ///< 标定过期或漂移
  52. DATA_LOSS = 1u << 12, ///< 数据链中断(取帧超时/丢流)
  53. };
  54. inline uint16_t bit_mask(StatusBits bit) { return static_cast<uint16_t>(bit); }
  55. /// 一个检测框(像素坐标)。
  56. struct Box {
  57. float x1 = 0.0f;
  58. float y1 = 0.0f;
  59. float x2 = 0.0f;
  60. float y2 = 0.0f;
  61. float score = 0.0f;
  62. int class_id = -1;
  63. std::string class_name;
  64. Box() = default;
  65. Box(float a, float b, float c, float d, float s = 0.0f, int cid = -1,
  66. std::string name = std::string())
  67. : x1(a), y1(b), x2(c), y2(d), score(s), class_id(cid), class_name(std::move(name)) {
  68. normalize();
  69. }
  70. void normalize() {
  71. if (x2 < x1) { float t = x1; x1 = x2; x2 = t; }
  72. if (y2 < y1) { float t = y1; y1 = y2; y2 = t; }
  73. }
  74. float width() const { return (x2 - x1) > 0.0f ? (x2 - x1) : 0.0f; }
  75. float height() const { return (y2 - y1) > 0.0f ? (y2 - y1) : 0.0f; }
  76. float area() const { return width() * height(); }
  77. float cx() const { return (x1 + x2) * 0.5f; }
  78. float cy() const { return (y1 + y2) * 0.5f; }
  79. float top() const { return y1 < y2 ? y1 : y2; }
  80. float bottom() const { return y1 > y2 ? y1 : y2; }
  81. };
  82. /// 单帧观测(未经时序滤波)。
  83. struct Observation {
  84. double ts = 0.0;
  85. int state = static_cast<int>(SceneState::UNKNOWN);
  86. double confidence = 0.0;
  87. std::vector<Box> boxes;
  88. std::string reason;
  89. long frame_id = 0;
  90. bool is_valid() const { return state != static_cast<int>(SceneState::UNKNOWN); }
  91. };
  92. /// 时序滤波后的判决,可直接发布给 PLC。
  93. struct Decision {
  94. int state = static_cast<int>(SceneState::UNKNOWN);
  95. double confidence = 0.0;
  96. bool stable = false;
  97. uint32_t seq = 0; ///< 状态每变化一次 +1,PLC 用它判断"有新结果"
  98. double since_ts = 0.0; ///< 当前状态的起始时间(秒)
  99. std::string reason = "init";
  100. bool changed = false; ///< 本次 update 是否发生了状态变化
  101. const char* label() const { return scene_state_label(state); }
  102. };
  103. // ------------------------------------------------------------------ 字/字节
  104. /// 16bit 字数组 → 大端字节流。
  105. inline std::vector<uint8_t> words_to_bytes(const std::vector<uint16_t>& words) {
  106. std::vector<uint8_t> out(words.size() * 2, 0);
  107. for (std::size_t i = 0; i < words.size(); ++i) {
  108. out[i * 2] = static_cast<uint8_t>((words[i] >> 8) & 0xFF);
  109. out[i * 2 + 1] = static_cast<uint8_t>(words[i] & 0xFF);
  110. }
  111. return out;
  112. }
  113. /// 大端字节流 → 16bit 字数组(奇数长度时忽略最后一个字节,与 Python 行为一致)。
  114. inline std::vector<uint16_t> bytes_to_words(const uint8_t* data, std::size_t len) {
  115. std::vector<uint16_t> out;
  116. out.reserve(len / 2);
  117. for (std::size_t i = 0; i + 1 < len; i += 2) {
  118. out.push_back(static_cast<uint16_t>((static_cast<uint16_t>(data[i]) << 8) |
  119. static_cast<uint16_t>(data[i + 1])));
  120. }
  121. return out;
  122. }
  123. /// 寄存器布局条目:字段名 + 16bit 字宽。
  124. struct RegisterField {
  125. const char* name;
  126. int width;
  127. };
  128. /// 视觉 → PLC 的结果快照(输入寄存器,FC4 只读;共 12 字,末字为 CRC)。
  129. struct VisionSnapshot {
  130. uint16_t state = static_cast<uint16_t>(SceneState::UNKNOWN);
  131. uint16_t confidence = 0; ///< 千分比 0..1000
  132. uint16_t flags = 0;
  133. uint32_t seq = 0; ///< 32bit,状态变化计数
  134. uint32_t ts_s = 0; ///< unix 秒(32bit)
  135. uint16_t heartbeat = 0; ///< 每个心跳周期 +1
  136. uint16_t fps_x10 = 0; ///< 帧率 x10
  137. uint16_t latency_ms = 0; ///< 单帧端到端耗时
  138. uint16_t reserved = 0;
  139. /// 字段布局(与 Python VisionSnapshot.REGISTER_LAYOUT 逐项一致)。
  140. static constexpr RegisterField kLayout[] = {
  141. {"state", 1}, {"confidence", 1}, {"flags", 1}, {"seq", 2}, {"ts_s", 2},
  142. {"heartbeat", 1}, {"fps_x10", 1}, {"latency_ms", 1}, {"reserved", 1},
  143. };
  144. static constexpr int kFieldCount = 9;
  145. /// 布局字宽之和 + 1(CRC)。
  146. static constexpr int register_count() {
  147. int n = 0;
  148. for (int i = 0; i < kFieldCount; ++i) { n += kLayout[i].width; }
  149. return n + 1;
  150. }
  151. std::vector<uint16_t> to_registers() const {
  152. std::vector<uint16_t> words = {
  153. state,
  154. confidence,
  155. flags,
  156. static_cast<uint16_t>((seq >> 16) & 0xFFFF),
  157. static_cast<uint16_t>(seq & 0xFFFF),
  158. static_cast<uint16_t>((ts_s >> 16) & 0xFFFF),
  159. static_cast<uint16_t>(ts_s & 0xFFFF),
  160. heartbeat,
  161. fps_x10,
  162. latency_ms,
  163. reserved,
  164. };
  165. words.push_back(crc16_modbus(words_to_bytes(words)));
  166. return words;
  167. }
  168. /// 字数组 → 快照;verify=true 时校验 CRC(与 Python from_registers 一致)。
  169. static VisionSnapshot from_registers(const std::vector<uint16_t>& words, bool verify = false) {
  170. if (static_cast<int>(words.size()) < register_count()) {
  171. throw std::invalid_argument("寄存器数量不足");
  172. }
  173. if (verify) {
  174. std::vector<uint16_t> payload(words.begin(), words.begin() + words.size() - 1);
  175. if (crc16_modbus(words_to_bytes(payload)) != words[words.size() - 1]) {
  176. throw std::invalid_argument("CRC 校验失败,数据可能不完整");
  177. }
  178. }
  179. VisionSnapshot snap;
  180. snap.state = words[0];
  181. snap.confidence = words[1];
  182. snap.flags = words[2];
  183. snap.seq = (static_cast<uint32_t>(words[3]) << 16) | static_cast<uint32_t>(words[4]);
  184. snap.ts_s = (static_cast<uint32_t>(words[5]) << 16) | static_cast<uint32_t>(words[6]);
  185. snap.heartbeat = words[7];
  186. snap.fps_x10 = words[8];
  187. snap.latency_ms = words[9];
  188. snap.reserved = words[10];
  189. return snap;
  190. }
  191. bool has_flag(StatusBits bit) const { return (flags & bit_mask(bit)) != 0; }
  192. void set_flag(StatusBits bit, bool on) {
  193. if (on) {
  194. flags = static_cast<uint16_t>(flags | bit_mask(bit));
  195. } else {
  196. flags = static_cast<uint16_t>(flags & static_cast<uint16_t>(~bit_mask(bit)));
  197. }
  198. }
  199. };
  200. /// PLC → 视觉的指令块(保持寄存器 FC3/FC6/FC16;共 4 字)。
  201. struct PlcCommand {
  202. uint16_t cmd = CMD_IDLE;
  203. uint16_t preset = 0;
  204. uint16_t min_conf = 0; ///< 千分比,0 = 用配置值
  205. uint16_t reserved = 0;
  206. static constexpr int register_count() { return 4; }
  207. std::vector<uint16_t> to_registers() const { return {cmd, preset, min_conf, reserved}; }
  208. static PlcCommand from_registers(const std::vector<uint16_t>& words) {
  209. PlcCommand c;
  210. if (words.size() > 0) { c.cmd = words[0]; }
  211. if (words.size() > 1) { c.preset = words[1]; }
  212. if (words.size() > 2) { c.min_conf = words[2]; }
  213. if (words.size() > 3) { c.reserved = words[3]; }
  214. return c;
  215. }
  216. bool is_request() const { return cmd == CMD_REQUEST; }
  217. bool is_reset() const { return cmd == CMD_RESET; }
  218. };
  219. } // namespace portcv