publish_gate.hpp 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // V2 PublishGate —— 与 Python `portcv/service/publish_gate.py` 同输入/同输出/同向量。
  2. //
  3. // 目标契约(docs/plc_interface.md §3A / §6A):
  4. // * PLC 结果区 state 只写 0/1/2,255 只存在于内部 Decision;
  5. // * 有效(0/1/2 + stable + conf>=min_conf)→ 状态 + RESULT_VALID + STABLE;
  6. // * 内部 255 / 低置信度 / 未稳定 / 帧超时 → 保持 last stable,清两个标志;
  7. // * cmd=2 复位 → 0 + flags 0/0,清 last stable;
  8. // * 冷启动 → 0 + flags 0/0(不是“已确认 0”)。
  9. //
  10. // 本类只做输出映射,不接 evidence_v2;P1a 先用合成 Decision 验证契约。
  11. #pragma once
  12. #include <cstdint>
  13. #include <optional>
  14. #include "portcv/schema.hpp"
  15. namespace portcv {
  16. /// 与 Python `DEFAULT_MIN_CONFIDENCE` 一致。
  17. inline constexpr double kPublishMinConfidence = 0.45;
  18. /// PublishGate 的输出;字段对应 PLC 结果区前三个字。
  19. struct PublishResult {
  20. uint16_t state = 0;
  21. bool result_valid = false;
  22. bool stable = false;
  23. uint16_t confidence = 0; ///< 千分比 0..1000
  24. std::optional<int> last_stable{};
  25. bool perception_uncertain = false; ///< P0-2:true 时 result_valid 必须为 false
  26. bool operator==(const PublishResult& other) const {
  27. return state == other.state && result_valid == other.result_valid &&
  28. stable == other.stable && confidence == other.confidence &&
  29. last_stable == other.last_stable &&
  30. perception_uncertain == other.perception_uncertain;
  31. }
  32. bool operator!=(const PublishResult& other) const { return !(*this == other); }
  33. };
  34. /// 纯函数版:`last_stable` 是上一稳定值,不是本帧内部状态;有效时才更新。
  35. /// 优先级:reset > frame_timeout > 有效结果 > 保持。
  36. PublishResult evaluate_publish_gate(const Decision& decision,
  37. bool frame_timeout = false,
  38. bool reset = false,
  39. std::optional<int> last_stable = std::nullopt,
  40. double min_conf = kPublishMinConfidence,
  41. bool perception_uncertain = false);
  42. /// 有状态版:内部保存 last stable;线程内使用,非线程安全。
  43. class PublishGate {
  44. public:
  45. explicit PublishGate(double min_conf = kPublishMinConfidence);
  46. PublishResult apply(const Decision& decision,
  47. bool frame_timeout = false,
  48. bool reset = false,
  49. bool perception_uncertain = false);
  50. void reset() { last_stable_.reset(); }
  51. /// PLC `min_conf` 覆盖(千分比 → 0..1);非法值忽略。
  52. void set_min_conf(double value) {
  53. if (value >= 0.0 && value <= 1.0) { min_conf_ = value; }
  54. }
  55. double min_conf() const { return min_conf_; }
  56. std::optional<int> last_stable() const { return last_stable_; }
  57. private:
  58. double min_conf_ = kPublishMinConfidence;
  59. std::optional<int> last_stable_{};
  60. };
  61. } // namespace portcv