初始提交

This commit is contained in:
gqc
2025-11-18 17:30:28 +08:00
commit 7a9d103943
19 changed files with 2797 additions and 0 deletions
+181
View File
@@ -0,0 +1,181 @@
package httpreader
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"FireLeave_tool/logger"
)
// 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"`
}
// InferenceServer 推理数据接收服务器
type InferenceServer struct {
port int
deviceUUID string
server *http.Server
dataChan chan InferenceResult
mu sync.RWMutex
running bool
}
// NewInferenceServer 创建推理数据接收服务器
func NewInferenceServer(deviceUUID string, port int) *InferenceServer {
return &InferenceServer{
port: port,
deviceUUID: deviceUUID,
dataChan: make(chan InferenceResult, 100), // 缓冲通道,避免阻塞
running: false,
}
}
// Start 启动HTTP服务器
func (is *InferenceServer) Start() error {
is.mu.Lock()
defer is.mu.Unlock()
if is.running {
return fmt.Errorf("服务器已在运行")
}
mux := http.NewServeMux()
mux.HandleFunc("/video/post", is.handleVideoPost)
mux.HandleFunc("/health", is.handleHealthCheck)
is.server = &http.Server{
Addr: fmt.Sprintf(":%d", is.port),
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
go func() {
logger.Logger.Printf("Start the inference data receiving server (DeviceUUID=%s, Port=%d)", is.deviceUUID, is.port)
if err := is.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Logger.Printf("The inference data receiving server failed to start (DeviceUUID=%s): %v", is.deviceUUID, err)
}
}()
// 等待服务器启动
time.Sleep(100 * time.Millisecond)
is.running = true
logger.Logger.Printf("The inference data receiving server has been successfully started (DeviceUUID=%s, Port=%d)", is.deviceUUID, is.port)
return nil
}
// handleVideoPost 处理视频数据POST请求
func (is *InferenceServer) handleVideoPost(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
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)
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)
return
}
// 只在人员数量变化或重要事件时记录详细日志
if len(result.Params) > 0 {
hasPerson := false
for _, param := range result.Params {
if param.ClassIdx == 1 && param.Number > 0 {
hasPerson = true
break
}
}
if hasPerson {
logger.Logger.Printf("Inference data: Serial=%s, Person detected, ParamsCount=%d",
result.Serial, len(result.Params))
}
}
// 发送到处理通道
select {
case is.dataChan <- result:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok", "message":"data received"}`))
// 使用 startTime 记录处理时间
logger.Logger.Printf("Inference data processed in %v", time.Since(startTime))
default:
logger.Logger.Printf("Data channel full, discard data")
http.Error(w, `{"error":"Channel full"}`, http.StatusServiceUnavailable)
}
}
func (is *InferenceServer) handleHealthCheck(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
is.mu.RLock()
running := is.running
is.mu.RUnlock()
if running {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{
"status": "healthy",
"device_uuid": "` + is.deviceUUID + `",
"port": ` + fmt.Sprintf("%d", is.port) + `,
"timestamp": "` + time.Now().Format(time.RFC3339) + `"
}`))
} else {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(`{"status": "unavailable"}`))
}
}
func (is *InferenceServer) GetDataChan() <-chan InferenceResult {
return is.dataChan
}
// StopWithContext 带上下文的停止方法
func (s *InferenceServer) StopWithContext(ctx context.Context) {
if s.server != nil {
// 使用带超时的关闭
shutdownCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
s.server.Shutdown(shutdownCtx)
logger.Logger.Printf("The HTTP server has been shut down (DeviceUUID=%s)", s.deviceUUID)
}
}
+121
View File
@@ -0,0 +1,121 @@
package httpreader
import (
"fmt"
"net"
"net/http"
"time"
"FireLeave_tool/logger"
)
// CheckHTTPService 检查HTTP服务是否可用
func CheckHTTPService(port int, timeout time.Duration) bool {
client := &http.Client{
Timeout: timeout,
}
url := fmt.Sprintf("http://127.0.0.1:%d/health", port)
resp, err := client.Get(url)
if err != nil {
logger.Logger.Printf("HTTP服务健康检查失败 (Port=%d): %v", port, err)
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// CheckPortAvailable 检查端口是否可用
func CheckPortAvailable(port int) bool {
address := fmt.Sprintf(":%d", port)
listener, err := net.Listen("tcp", address)
if err != nil {
return false
}
listener.Close()
return true
}
// WaitForHTTPService 等待HTTP服务启动
func WaitForHTTPService(port int, timeout time.Duration) bool {
deadline := time.Now().Add(timeout)
logger.Logger.Printf("等待HTTP服务启动 (Port=%d, Timeout=%v)", port, timeout)
attempt := 0
for time.Now().Before(deadline) {
attempt++
if CheckHTTPService(port, 2*time.Second) {
logger.Logger.Printf("HTTP服务启动成功 (Port=%d, 尝试次数=%d)", port, attempt)
return true
}
if attempt == 1 || attempt%5 == 0 {
logger.Logger.Printf("等待HTTP服务... (Port=%d, 尝试次数=%d)", port, attempt)
}
time.Sleep(1 * time.Second)
}
logger.Logger.Printf("HTTP服务启动超时 (Port=%d, 总尝试次数=%d)", port, attempt)
return false
}
// ValidateInferenceResult 验证推理结果数据
func ValidateInferenceResult(result *InferenceResult) error {
if result.Serial == "" {
return fmt.Errorf("serial字段不能为空")
}
if result.At <= 0 {
return fmt.Errorf("at时间戳无效")
}
// 验证参数数据
for i, param := range result.Params {
if param.Number < 0 {
return fmt.Errorf("参数[%d]的number不能为负数", i)
}
if param.ClassIdx < 0 {
return fmt.Errorf("参数[%d]的class_idx不能为负数", i)
}
}
return nil
}
// GetPersonCountFromResult 从推理结果中获取人员数量
func GetPersonCountFromResult(result *InferenceResult) int {
if result == nil || len(result.Params) == 0 {
return 0
}
// 查找人员类别的参数(假设 class_idx=1 表示人员)
for _, param := range result.Params {
if param.ClassIdx == 1 { // 人员类别
return param.Number
}
}
return 0
}
// CreateTestInferenceResult 创建测试用的推理结果(用于调试)
func CreateTestInferenceResult(deviceUUID string, personCount int) InferenceResult {
return InferenceResult{
Serial: deviceUUID,
At: time.Now().Unix(),
Type: 1,
Params: []struct {
ClassIdx int `json:"class_idx"`
Name string `json:"name"`
Number int `json:"number"`
}{
{
ClassIdx: 1,
Name: "person",
Number: personCount,
},
},
}
}