qixiaoning
20 小时以前 03880bf61cf059f063e252ef17dfea50c932c9dc
camera-service/controllers/camera.go
@@ -2,8 +2,12 @@
import (
   "bytes"
   "database/sql"
   "encoding/json"
   "fmt"
   "image"
   "path/filepath"
   "time"
   // "fmt"
   // "io/ioutil"
@@ -27,6 +31,7 @@
   "basic.com/valib/logger.git"
   //"vamicro/camera-common/service/uniquelCoordinate"
   commonModel "vamicro/api-gateway/models"
   "vamicro/config"
   "vamicro/extend/util"
   scs "vamicro/scene-service/controllers"
@@ -81,7 +86,39 @@
   }
   logger.Debug("update sensors:", camVo.Sensors)
   sv := service.CameraService{}
   ok, cam := sv.GetById(camVo.Id)
   if b, err := sv.CameraUpdate(camVo); b {
      //更新分辨率
      if ok {
         //
         logger.Debug("DoPostRequest:", camVo)
         if cam.IsRunning && (cam.ResolutionWidth != camVo.ResolutionWidth && cam.ResolutionHeight != camVo.ResolutionHeight) {
            header := map[string]string{}
            paramBody := map[string]interface{}{
               "isOpen":    1,
               "videoId":   camVo.Id,
               "videoType": 0,
            }
            res, err := util.DoPostRequest("http://127.0.0.1:8088/v1/task/openAnalysis", util.CONTENT_TYPE_JSON, paramBody, nil, header, time.Second*10)
            if err != nil {
               logger.Debug("DoPostRequest err:", err)
            }
            logger.Debug("DoPostRequest:", res)
         }
         //更新状态
         if cam.IsRunning {
            header := map[string]string{}
            paramBody := map[string]interface{}{
               "state": 1,
            }
            res, err := util.DoPostRequest("http://127.0.0.1:8088/v1/task/updateAllStatus?state=1", util.CONTENT_TYPE_JSON, paramBody, nil, header, time.Second*10)
            if err != nil {
               logger.Debug("DoPostRequest err:", err)
            }
            logger.Debug("DoPostRequest:", res)
         }
      }
      cc.addDbChangeMsg(h.Bk, protomsg.TableChanged_T_Camera, camVo.Id, protomsg.DbAction_Update, "")
      _, _ = service2.DoBusReq("/data/api-v/saas/syncCamera", config.Server.AnalyServerId, aiot.RequestMethod_Post, aiot.RequestContentType_ApplicationJson, map[string]interface{}{})
      return &bhomeclient.Reply{Success: true, Data: camVo.Copy2Camera()}
@@ -105,10 +142,26 @@
   if cid == "" {
      return &bhomeclient.Reply{Msg: "参数有误,摄像机id不能为空"}
   }
   //判断是否有配置任务
   // total, _ := models.GetTaskTotal(cid)
   // if total > 0 {
   //    return &bhomeclient.Reply{Success: false, Msg: "请先删除配置的任务"}
   // }
   rows, _ := cam.Delete(cid)
   if rows == 0 {
      return &bhomeclient.Reply{Success: true, Msg: "记录不存在"}
   }
   //删除任务
   items, _ := models.GetTaskTotal(cid)
   if len(items) > 0 {
      for _, item := range items {
         cam.DelLink(item.ID)
      }
   }
   pMsg := protomsg.DbChangeMessage{ //需要重新计算算力占用情况
      Table:  protomsg.TableChanged_T_Camera,
      Action: protomsg.DbAction_Delete,
@@ -162,10 +215,14 @@
   }
   m["resolutions"] = []models.Resolution{dRe0, dRe1, dRe2}
   //获取督查任务
   tasks := models.GetTasks()
   //处理摄像机的状态
   var crApi bhomedbapi.CameraRuleApi
   //var crApi bhomedbapi.CameraRuleApi
   if cam.RunType == models.TYPE_RUNTYPE_POLL || cam.RunType == models.TYPE_RUNTYPE_REALTIME {
      if crApi.ExistRunningTask(cam.Id) {
      //if crApi.ExistRunningTask(cam.Id) {
      if taskInfo, ok := tasks[cam.Id]; ok && taskInfo != nil && len(taskInfo) > 0 {
         if cam.IsRunning {
            m["status"] = models.Camera_Status_Doing
         } else {
@@ -319,9 +376,9 @@
   sv := service.CameraService{}
   if sv.ChangeRunType(ccrVo) {
      cIds := strings.Join(ccrVo.CameraIds, ",")
      cc.addDbChangeMsg(h.Bk, protomsg.TableChanged_T_Camera, cIds, protomsg.DbAction_Update, "")
      _, _ = service2.DoBusReq("/data/api-v/saas/syncCamera", config.Server.AnalyServerId, aiot.RequestMethod_Post, aiot.RequestContentType_ApplicationJson, map[string]interface{}{})
      //cIds := strings.Join(ccrVo.CameraIds, ",")
      //cc.addDbChangeMsg(h.Bk, protomsg.TableChanged_T_Camera, cIds, protomsg.DbAction_Update, "")
      //   _, _ = service2.DoBusReq("/data/api-v/saas/syncCamera", config.Server.AnalyServerId, aiot.RequestMethod_Post, aiot.RequestContentType_ApplicationJson, map[string]interface{}{})
      return &bhomeclient.Reply{Success: true, Msg: "更新成功"}
   } else {
      return &bhomeclient.Reply{Success: false, Msg: "更新失败"}
@@ -1000,3 +1057,300 @@
   _, _ = service2.DoBusReq("/data/api-v/saas/syncCamera", config.Server.AnalyServerId, aiot.RequestMethod_Post, aiot.RequestContentType_ApplicationJson, map[string]interface{}{})
   return &bhomeclient.Reply{Success: true, Msg: "保存成功"}
}
/**
 *  删除记录
 */
func (cc CameraController) DelRecord(h *bhomeclient.WrapperHandler, c *bhomeclient.Request) *bhomeclient.Reply {
   filter := " id > 0 "
   info := models.TimeRange{}
   if err := c.BindJSON(&info); err != nil {
      return &bhomeclient.Reply{Success: false, Msg: "参数有误"}
   }
   startTime := info.StartTime
   if len(startTime) > 0 && len(info.EndTime) > 0 {
      endTime, err1 := addDaySimple(info.EndTime)
      if err1 != nil {
         endTime = info.EndTime
      }
      filter += fmt.Sprintf(" and detect_time > '%s'", startTime)
      filter += fmt.Sprintf(" and detect_time < '%s'", endTime)
      deleteRecord, err := models.DeleteRecord("smartobject", filter)
      if err != nil {
         return &bhomeclient.Reply{Success: false, Msg: "删除失败" + err.Error(), Data: nil}
      } else {
         return &bhomeclient.Reply{Success: true, Msg: "删除成功", Data: deleteRecord}
      }
   } else {
      return &bhomeclient.Reply{Success: false, Msg: "删除失败", Data: nil}
   }
}
func addDaySimple(dateStr string) (string, error) {
   // 假设格式为 "2006-01-02"
   t, err := time.Parse("2006-01-02", dateStr)
   if err != nil {
      return "", err
   }
   t = t.AddDate(0, 0, 1)
   return t.Format("2006-01-02"), nil
}
/**
 *  获取抓拍记录
 */
func (cc CameraController) GetRecord(h *bhomeclient.WrapperHandler, c *bhomeclient.Request) *bhomeclient.Reply {
   //绑定json和结构体
   info := models.RecordReq{}
   if err := c.BindJSON(&info); err != nil {
      return &bhomeclient.Reply{Success: false, Msg: "参数有误"}
   }
   page := info.Page
   pageSize := info.PageSize
   idsStr := info.Ids
   TaskIds := info.TaskIds
   TaskName := info.TaskName
   videoIdStr := info.VideoIds
   Warning := info.Warning
   filter := "zh_desc_class != '' "
   //根据id获取记录
   var ids []string
   if len(idsStr) > 0 {
      for _, tmp := range idsStr {
         id, _ := strconv.ParseInt(tmp, 10, 64)
         if id > 0 {
            ids = append(ids, tmp)
         }
      }
      filter += fmt.Sprintf(" and %s in [%s]", "id", strings.Join(ids, ","))
   }
   //根据视频id查询
   var videoIds []string
   if len(videoIdStr) > 0 {
      for _, tmp := range videoIdStr {
         if len(tmp) > 0 {
            videoIds = append(videoIds, tmp)
         }
      }
      //根据id查询视频id
      var vids []int64
      cameras, _ := models.GetCameraIds(videoIds)
      for _, camera := range cameras {
         if len(camera.Id) > 0 {
            vids = append(vids, camera.VideoId)
         }
      }
      idStr := make([]string, len(vids))
      for i, id := range vids {
         idStr[i] = strconv.FormatInt(id, 10)
      }
      filter += fmt.Sprintf(" and %s in [%s]", "video_point_id", strings.Join(idStr, ","))
   }
   //根据任务查询
   if len(TaskIds) > 0 {
      filter += fmt.Sprintf(" and array_contains(task_id, %d)", TaskIds[0])
   }
   //根据任务名称
   if len(TaskName) > 0 {
      quotedNames := make([]string, len(TaskName))
      for i, name := range TaskName {
         quotedNames[i] = " task_name like '%%" + name + "%%' " // 每个元素加单引号
      }
      filter += " and (" + strings.Join(quotedNames, "or") + ")"
   } else {
      if Warning > 0 {
         return &bhomeclient.Reply{Success: true, Msg: "获取成功", Data: nil}
      }
   }
   //是否预警
   if Warning > 0 {
      filter += fmt.Sprintf(" and is_waning == %d", Warning)
   }
   //filter += " ORDER BY detect_time DESC"
   if len(filter) > 0 {
      logger.Error("filter err:", filter)
   }
   result, err := models.GetWithPage("smartobject", int64(page), int64(pageSize), filter)
   // 通用响应
   if err != nil {
      if err == sql.ErrNoRows {
         return &bhomeclient.Reply{Success: false, Msg: "数据为空"}
      } else {
         return &bhomeclient.Reply{Success: false, Msg: "获取列表失败"}
      }
   }
   //组织数据
   //重新组织数据
   basePath := commonModel.GetBasePath()
   tmpAllDate := make(map[string]interface{})
   tmpDate := make(map[string][]interface{})
   for _, v := range result.Items {
      sources := make(map[string]interface{}, 0)
      temp := models.StaticRecord{
         Id:              v.Id,
         TaskId:          v.TaskId,
         RuleId:          v.RuleId,
         EventLevelId:    v.EventLevelId,
         VideoPointId:    v.VideoPointId,
         DetectId:        v.DetectId,
         ImagePath:       v.ImagePath,
         VideoPath:       v.VideoPath,
         DetectTime:      v.DetectTime,
         IsWarning:       v.IsWarning,
         DetectNum:       v.DetectNum,
         TaskName:        v.TaskName,
         WarnTaskName:    v.WarnTaskName,
         ZhDescClass:     v.ZhDescClass,
         EventLevelName:  v.EventLevelName,
         KnowledgeId:     v.KnowledgeId,
         Suggestion:      v.Suggestion,
         RiskDescription: v.RiskDescription,
         IsDesc:          v.IsDesc,
         PicMaxUrl:       []string{v.ImagePath},
         PicSrcUrl:       []string{v.ImagePath},
         PicWH:           models.PicWidHei{PicH: 720, PicW: 1280},
         VideoUrl:        v.VideoPath,
         AnalyServerName: "智能服务节点",
         Content:         v.CameraName,
         PicDate:         v.PicDate,
         LikeDate:        v.LikeDate,
         VideoName:       v.CameraName,
         CameraAddr:      v.CameraName,
         CameraName:      v.CameraName,
      }
      var taskId []int64
      //任务id重新赋值
      if len(v.WarnTaskName) > 0 {
         v.TaskId = []int64{}
         taskId = []int64{}
         arr := strings.Split(v.WarnTaskName, ";")
         for _, temp := range arr {
            if len(temp) > 0 {
               tempId, _ := strconv.ParseInt(strings.TrimSpace(temp), 10, 64)
               taskId = append(taskId, tempId)
            }
         }
         v.TaskId = taskId
      }
      items, _ := models.GetTaskByIds(v.TaskId)
      temp.TaskNames = items
      //任务名称重新赋值
      var result string
      if len(taskId) > 0 && len(items) > 0 {
         v.EventLevelId = []int64{}
         for index, item := range items {
            v.EventLevelId = append(v.EventLevelId, item.EventLevel)
            if index > 0 {
               result += ","
            }
            result += item.TaskName
         }
         temp.TaskName = result
      }
      //视频内容
      // items4, _ := models.GetVideoById(v.VideoPointId)
      // temp.VideoName = items4.Name
      // temp.CameraAddr = items4.Addr
      //检查内容
      items2, _ := models.GetCheckByIds(v.DetectId)
      temp.CheckNames = items2
      //规则内容
      items3, _ := models.GetRuleByIds(v.RuleId)
      temp.RuleNames = items3
      //事件
      items5, _ := models.GetEventByIds(v.EventLevelId)
      temp.EventLevels = items5
      //事件等级重新赋值
      var result2 string
      if len(taskId) > 0 && len(items5) > 0 {
         for i, item5 := range items5 {
            if i > 0 {
               result2 += ","
            }
            result2 += item5.DictValue
         }
         temp.EventLevelName = result2
      }
      //知识库
      items6, _ := models.GetKnowledgeDocumentByIds(v.KnowledgeId)
      // 知识库路径
      var KnowledgePath = "/txt/zs/"
      for i := range items6 {
         filePath := filepath.Join(basePath + KnowledgePath + items6[i].Title)
         newPath := filepath.ToSlash(filePath)
         items6[i].FileUrl = newPath
      }
      temp.KnowledgeDocuments = items6
      sources["list"] = []interface{}{
         temp,
      }
      sources["activeObject"] = temp
      tmpDate["datalist"] = append(tmpDate["datalist"], sources)
   }
   tmpAllDate["datalist"] = tmpDate["datalist"]
   var pageRes = &models.PaginatedResult2{
      Pagination: result.Pagination,
      Items:      tmpAllDate,
   }
   return &bhomeclient.Reply{Success: true, Msg: "获取成功", Data: pageRes}
}
/**
 *获取督查任务
 */
func (cc CameraController) GetTasks(h *bhomeclient.WrapperHandler, c *bhomeclient.Request) *bhomeclient.Reply {
   //绑定json和结构体
   info := models.Video{}
   if err := c.BindJSON(&info); err != nil {
      return &bhomeclient.Reply{Success: false, Msg: "参数有误"}
   }
   var tasks []models.Task
   if len(info.VideoIds) > 0 {
      tasks, _ = models.GetListTask(info.VideoIds)
   }
   return &bhomeclient.Reply{Success: true, Msg: "获取成功", Data: tasks}
}
// 获取所有
func (cc CameraController) GetAllTasks(h *bhomeclient.WrapperHandler, c *bhomeclient.Request) *bhomeclient.Reply {
   //绑定json和结构体
   var tasks []models.TaskAggregate
   tasks, _ = models.GetAllTask()
   return &bhomeclient.Reply{Success: true, Msg: "获取成功", Data: tasks}
}