feat: update inference reporting and ffmpeg video merge

This commit is contained in:
gqc
2026-07-06 16:26:08 +08:00
parent 79490bd27b
commit 0842f555fd
10 changed files with 1430 additions and 990 deletions
+113 -45
View File
@@ -2,11 +2,9 @@ package httpreader
import (
"FireLeave_tool/connect"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"sync"
@@ -17,14 +15,31 @@ import (
// InferenceResult 推理结果
type InferenceResult struct {
Serial string `json:"serial"`
At int64 `json:"at"`
Type int `json:"type"`
Params []struct {
ClassIdx int `json:"class_idx"`
Name string `json:"name"`
Number int `json:"number"`
} `json:"params"`
MessageType string `json:"message_type"`
Serial string `json:"serial"`
At int64 `json:"at"`
Type int `json:"type"`
Params []InferenceParam `json:"params"`
}
type InferenceParam struct {
ClassIdx int `json:"class_idx"`
Name string `json:"name"`
Number int `json:"number"`
}
type HeartbeatMessage struct {
MessageType string `json:"message_type"`
SchemaVersion int `json:"schema_version"`
Serial string `json:"serial"`
ProcessUUID string `json:"process_uuid"`
Timestamp int64 `json:"timestamp"`
Status string `json:"status"`
}
type inferenceStats struct {
windowStart time.Time
count int
}
// InferenceServer 推理数据接收服务器
@@ -35,6 +50,8 @@ type InferenceServer struct {
dataChan chan InferenceResult
mu sync.RWMutex
running bool
statsMu sync.Mutex
stats inferenceStats
}
// NewInferenceServer 创建推理数据接收服务器
@@ -58,6 +75,7 @@ func (is *InferenceServer) Start() error {
mux := http.NewServeMux()
mux.HandleFunc("/video/post", is.handleVideoPost)
mux.HandleFunc("/heartbeat", is.handleHeartbeat)
mux.HandleFunc("/health", is.handleHealthCheck)
is.server = &http.Server{
@@ -91,41 +109,23 @@ func (is *InferenceServer) handleVideoPost(w http.ResponseWriter, r *http.Reques
return
}
// 读取原始 body
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
logger.Logger.Printf("Read request body failed: %v", err)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
// 重新设置 body 用于解析
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
var result InferenceResult
if err := json.NewDecoder(r.Body).Decode(&result); err != nil {
logger.Logger.Printf("Parse JSON failed: %v", err)
logger.Logger.Printf("Parse inference_result JSON failed: %v (DeviceUUID=%s)", err, is.deviceUUID)
http.Error(w, `{"error":"Invalid JSON"}`, http.StatusBadRequest)
return
}
// 验证必要字段
if result.Serial == "" {
logger.Logger.Printf("Data validation failed: Serial is empty")
http.Error(w, `{"error":"Missing serial field"}`, http.StatusBadRequest)
if result.MessageType != "inference_result" {
logger.Logger.Printf("Inference result validation failed: message_type=%q (DeviceUUID=%s)", result.MessageType, is.deviceUUID)
http.Error(w, `{"error":"Invalid message_type"}`, http.StatusBadRequest)
return
}
now := time.Now().Format("2006/01/02 15:04:05.000")
logger.Logger.Printf("推理心跳收到 | 时间: %s | UUID: %s | Serial: %s | 人数量: %d",
now, is.deviceUUID, result.Serial, getPersonCount(result))
// 这一行就是你缺失的救命稻草!
connect.UpdateInferenceHeartbeat(is.deviceUUID)
// 额外写一份永不丢失的独立心跳日志
if f, err := os.OpenFile("/data/heartbeat.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644); err == nil {
defer f.Close()
fmt.Fprintf(f, "[%s] HEARTBEAT OK | %s | person=%d\n", now, is.deviceUUID, getPersonCount(result))
if result.Serial == "" {
logger.Logger.Printf("Inference result validation failed: serial is empty (DeviceUUID=%s)", is.deviceUUID)
http.Error(w, `{"error":"Missing serial field"}`, http.StatusBadRequest)
return
}
// 发送到处理通道
@@ -135,13 +135,89 @@ func (is *InferenceServer) handleVideoPost(w http.ResponseWriter, r *http.Reques
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok", "message":"data received"}`))
// 使用 startTime 记录处理时间
logger.Logger.Printf("Inference data processed in %v", time.Since(startTime))
is.recordInferenceProcessed(time.Since(startTime))
default:
logger.Logger.Printf("Data channel full, discard data")
http.Error(w, `{"error":"Channel full"}`, http.StatusServiceUnavailable)
}
}
func (is *InferenceServer) recordInferenceProcessed(processCost time.Duration) {
is.statsMu.Lock()
defer is.statsMu.Unlock()
now := time.Now()
if is.stats.windowStart.IsZero() {
is.stats.windowStart = now
}
is.stats.count++
if now.Sub(is.stats.windowStart) >= 10*time.Second {
logger.Logger.Printf("Inference data processed summary | UUID=%s | count=%d | window=%v | last_cost=%v",
is.deviceUUID, is.stats.count, now.Sub(is.stats.windowStart).Round(time.Millisecond), processCost)
is.stats.windowStart = now
is.stats.count = 0
}
}
func (is *InferenceServer) handleHeartbeat(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var heartbeat HeartbeatMessage
if err := json.NewDecoder(r.Body).Decode(&heartbeat); err != nil {
logger.Logger.Printf("Parse heartbeat JSON failed: %v (DeviceUUID=%s)", err, is.deviceUUID)
http.Error(w, `{"error":"Invalid JSON"}`, http.StatusBadRequest)
return
}
if heartbeat.MessageType != "heartbeat" {
logger.Logger.Printf("Heartbeat validation failed: message_type=%q (DeviceUUID=%s)", heartbeat.MessageType, is.deviceUUID)
http.Error(w, `{"error":"Invalid message_type"}`, http.StatusBadRequest)
return
}
if heartbeat.SchemaVersion != 1 {
logger.Logger.Printf("Heartbeat validation failed: schema_version=%d (DeviceUUID=%s)", heartbeat.SchemaVersion, is.deviceUUID)
http.Error(w, `{"error":"Unsupported schema_version"}`, http.StatusBadRequest)
return
}
if heartbeat.Serial == "" {
logger.Logger.Printf("Heartbeat validation failed: serial is empty (DeviceUUID=%s)", is.deviceUUID)
http.Error(w, `{"error":"Missing serial field"}`, http.StatusBadRequest)
return
}
if heartbeat.ProcessUUID == "" {
logger.Logger.Printf("Heartbeat validation failed: process_uuid is empty (DeviceUUID=%s)", is.deviceUUID)
http.Error(w, `{"error":"Missing process_uuid field"}`, http.StatusBadRequest)
return
}
if heartbeat.ProcessUUID != is.deviceUUID {
logger.Logger.Printf("Heartbeat process_uuid mismatch: got=%s expected=%s", heartbeat.ProcessUUID, is.deviceUUID)
http.Error(w, `{"error":"process_uuid mismatch"}`, http.StatusBadRequest)
return
}
connect.UpdateInferenceHeartbeat(is.deviceUUID)
now := time.Now().Format("2006/01/02 15:04:05.000")
logger.Logger.Printf("Inference heartbeat received | Time: %s | UUID: %s | Serial: %s | Status: %s",
now, is.deviceUUID, heartbeat.Serial, heartbeat.Status)
if f, err := os.OpenFile("/data/heartbeat.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644); err == nil {
defer f.Close()
fmt.Fprintf(f, "[%s] HEARTBEAT OK | %s | serial=%s | status=%s | ts=%d\n", now, is.deviceUUID, heartbeat.Serial, heartbeat.Status, heartbeat.Timestamp)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok","message":"heartbeat received"}`))
}
func (is *InferenceServer) handleHealthCheck(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
@@ -178,11 +254,3 @@ func (s *InferenceServer) StopWithContext(ctx context.Context) {
logger.Logger.Printf("The HTTP server has been shut down (DeviceUUID=%s)", s.deviceUUID)
}
}
func getPersonCount(result InferenceResult) int {
for _, p := range result.Params {
if p.ClassIdx == 1 {
return p.Number
}
}
return 0
}