schema.hpp 9.5 KB

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