fix(intrusion): 修复代码质量问题 - 空值检查和常量提取

修复内容:
1. 添加 state_start_time 空值检查(CONFIRMING_INTRUSION 和 CONFIRMING_CLEAR 状态)
2. 移除 get_state() 未使用的 roi_id 参数
3. get_state() 接受 current_time 参数,避免直接调用 datetime.now()
4. 提取魔法数字:ALARM_LEVEL_INTRUSION = 3

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-14 10:23:14 +08:00
parent 2d90f00b11
commit 37fc48e34d

View File

@@ -389,6 +389,9 @@ class IntrusionAlgorithm:
STATE_ALARMED = "ALARMED" # 已告警(等待入侵消失)
STATE_CONFIRMING_CLEAR = "CONFIRMING_CLEAR" # 入侵消失确认中
# 告警级别常量
ALARM_LEVEL_INTRUSION = 3
def __init__(
self,
cooldown_seconds: int = 300,
@@ -472,6 +475,11 @@ class IntrusionAlgorithm:
elif self.state == self.STATE_CONFIRMING_INTRUSION:
# 入侵确认中:需要持续检测到人
if self.state_start_time is None:
# 防御性编程如果状态时间为空重置到IDLE
self.state = self.STATE_IDLE
logger.error(f"ROI {roi_id}: CONFIRMING_INTRUSION 状态异常state_start_time为None重置到IDLE")
else:
elapsed = (current_time - self.state_start_time).total_seconds()
if not roi_has_person:
@@ -493,7 +501,7 @@ class IntrusionAlgorithm:
"camera_id": camera_id,
"bbox": bbox,
"alert_type": "intrusion",
"alarm_level": 3,
"alarm_level": self.ALARM_LEVEL_INTRUSION,
"message": "检测到周界入侵",
"first_frame_time": self._intrusion_start_time.strftime('%Y-%m-%d %H:%M:%S'),
})
@@ -518,6 +526,11 @@ class IntrusionAlgorithm:
elif self.state == self.STATE_CONFIRMING_CLEAR:
# 入侵消失确认中:需要持续未检测到人
if self.state_start_time is None:
# 防御性编程如果状态时间为空重置到IDLE
self.state = self.STATE_IDLE
logger.error(f"ROI {roi_id}: CONFIRMING_CLEAR 状态异常state_start_time为None重置到IDLE")
else:
elapsed = (current_time - self.state_start_time).total_seconds()
if roi_has_person:
@@ -564,8 +577,10 @@ class IntrusionAlgorithm:
self.alert_triggered.clear()
self.detection_start.clear()
def get_state(self, roi_id: str) -> Dict[str, Any]:
def get_state(self, current_time: Optional[datetime] = None) -> Dict[str, Any]:
"""获取当前状态(用于调试和监控)"""
current_time = current_time or datetime.now()
state_info = {
"state": self.state,
"state_start_time": self.state_start_time.isoformat() if self.state_start_time else None,
@@ -573,7 +588,7 @@ class IntrusionAlgorithm:
# 添加状态特定信息
if self.state == self.STATE_ALARMED and self._intrusion_start_time:
total_intrusion_sec = (datetime.now() - self._intrusion_start_time).total_seconds()
total_intrusion_sec = (current_time - self._intrusion_start_time).total_seconds()
state_info["total_intrusion_sec"] = total_intrusion_sec
state_info["alarm_id"] = self._last_alarm_id