tcp server 用于给andriod 客户端定时发送消息
liuxiaolong
2021-04-07 a5e6ddc46a0306f630ac53a8e0e3843bf8c17a05
esutil/EsClient.go
@@ -1,6 +1,7 @@
package esutil
import (
   "bytes"
   "encoding/json"
   "errors"
   "fmt"
@@ -13,6 +14,35 @@
   log "andriodServer/log"
)
func EsReq(method string, url string, parama []byte) (buf []byte, err error) {
   //defer elapsed("page")()
   timeout := time.Duration(100 * time.Second)
   client := http.Client{
      Timeout: timeout,
   }
   request, err := http.NewRequest(method, url, bytes.NewBuffer(parama))
   request.Header.Set("Content-type", "application/json")
   if err != nil {
      fmt.Println("build request fail !")
      return nil, err
   }
   resp, err := client.Do(request)
   if err != nil {
      fmt.Println("request error: ", err)
      return nil, err
   }
   defer resp.Body.Close()
   body, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      fmt.Println(err)
      return nil, err
   }
   return body, nil
}
func GetEsDataReq(url string, param string, isSource bool) (error, map[string]interface{}) {
   req, err := http.NewRequest("POST", url, strings.NewReader(param))
@@ -27,7 +57,7 @@
   resp, err := client.Do(req)
   if err != nil {
      return err, nil
        return err, nil
   }
   defer resp.Body.Close()
@@ -47,7 +77,7 @@
   }
   // 是否需要 解析 es 返回的 source
   if isSource {
      dat, ok := dat["hits"].(map[string]interface{})
        dat, ok := dat["hits"].(map[string]interface{})
      if !ok {
         return errors.New("data is not type of  map[string]interface{}"), nil
      }
@@ -63,47 +93,82 @@
         }
         d["id"] = value.(map[string]interface{})["_id"]
         d["picDate"] = source["picDate"]
         pmax, exist := source["picMaxUrl"]
         if !exist {
            continue
         }
         pmArr := pmax.([]string)
         alarmRules, exist := source["alarmRules"]
         if exist {
            if alarmB,ae := json.Marshal(alarmRules);ae ==nil {
               var alarmRArr []AlarmRule
               if ae = json.Unmarshal(alarmB, &alarmRArr);ae ==nil && len(alarmRArr) >0 {
                  d["alarmLevel"] = alarmRArr[0].AlarmLevel
               }
            }
         } else {
            d["alarmLevel"] = ""
         }
         pmArr := pmax.([]interface{})
         if len(pmArr) > 0 {
            d["picMaxUrl"] = pmArr[0]
         } else {
            d["picMaxUrl"] = ""
         }
         d["picAddress"] = source["cameraAddr"]
         tB, err := json.Marshal(source["targetInfo"])
         if err != nil {
            continue
             log.Log.Infoln("err:", err)
                continue
         }
         ti := TargetInfo{}
         err = json.Unmarshal(tB, &ti)
         tiArr := []TargetInfo{}
         err = json.Unmarshal(tB, &tiArr)
         if err !=nil {
             log.Log.Infoln("err:", err)
            continue
         }
         d["picSmUrl"] = ti.PicSmUrl
         if ti.TargetType == "face" {
            sLabelStr, ok := source["showLabels"]
            if ok {
               labelArr := strings.Split(sLabelStr.(string), "/")
               if len(labelArr) == 3 {
                  d["gender"] = labelArr[0]
                  d["ageDescription"] = labelArr[1]
                  d["race"] = labelArr[2]
         if len(tiArr) > 0 {
            ti := tiArr[0]
            d["picSmUrl"] = ti.PicSmUrl
            d["targetType"] = ti.TargetType
            if ti.TargetType == "FaceDetect" {
               sLabelStr, ok := source["showLabels"]
               if ok {
                  //labelArr := strings.Split(sLabelStr.(string), "/")
                  //if len(labelArr) == 3 {
                  //   d["gender"] = labelArr[0]
                  //   d["ageDescription"] = labelArr[1]
                  //   d["race"] = labelArr[2]
                  //}
                  d["showLabels"] = sLabelStr
               } else {
                  d["showLabels"] = ""
               }
            }
            if bInfos,ok := source["baseInfo"]; ok && bInfos != nil {
               d["baseInfo"] = getSourceBaseInfo(bInfos)
               if bInfos,ok := source["baseInfo"]; ok && bInfos != nil {
                  bd := getSourceBaseInfo(bInfos)
                  d["baseInfo"] = bd //比对到的底库的人
               } else {
                  d["baseInfo"] = []interface{}{}
               }
               d["sdkType"] = source["taskName"]
            } else {
               d["baseInfo"] = []interface{}{}
               d["sdkType"] = source["taskName"]
               d["picSmUrl"] = d["picMaxUrl"]
            }
         } else {
            d["picSmUrl"] = d["picMaxUrl"]
         }
         d["videoNum"] = source["videoUrl"]
         vUri := source["videoUrl"]
         if vUri != nil && vUri.(string) != "" {
            d["videoNum"] = "http://"+vUri.(string)
         } else {
            d["videoNum"] = ""
         }
         sources = append(sources, d)
      }
@@ -112,6 +177,11 @@
   } else {
      return nil, dat
   }
}
type AlarmRule struct {
   GroupId          string          `json:"groupId"`
   AlarmLevel          string          `json:"alarmLevel"`
}
type TargetInfo struct {
@@ -124,7 +194,7 @@
type BaseInfo struct {
   TaskId          string       `json:"taskId"`
   TaskName       string       `json:"taskName"`
   LikePer       string       `json:"likePer"`
   LikePer       float32    `json:"likePer"`
   TableId       string       `json:"tableId"`
   TableName       string       `json:"tableName"`
   PersonId       string       `json:"personId"`
@@ -143,7 +213,7 @@
   TargetName       string       `json:"targetName"`
   TargetId       string       `json:"targetId"`
   TableId       string       `json:"tableId"`
   CompareScore    string       `json:"compareScore"`
   CompareScore    float32    `json:"compareScore"`
   MonitorLevel    string       `json:"monitorLevel"`
   Content       string       `json:"content"`
   TableName       string       `json:"tableName"`
@@ -192,7 +262,11 @@
               Content: t.Content,
            })
         }
      } else {
         fmt.Println("unmarshal bInfos err:", err)
      }
   } else {
      fmt.Println("marshal bInfos err:", err)
   }
   return baseInfoArr
@@ -215,36 +289,29 @@
      preSec = strconv.Itoa(sec)
   }
   var filterArr []string
   var mustNotArr []string
   //是否查报警数据
   if ishub == "hub" {
      filterArr = append(filterArr,"{\"term\":{\"alarmRules.alarmLevel.raw\":\"一级\"}}")
      mustNotArr = append(mustNotArr,"{\"term\":{\"alarmRules.alarmLevel.raw\":\"五级\"}}")
   }
   filterArr = append(filterArr, "{\"range\":{\"picDate\":{\"gte\":\"now+8h-"+preSec+"s\",\"lt\":\"now+8h\"}}}")
   filterStr := ""
   mustNotStr := ""
   if len(filterArr) >0 {
      filterStr = strings.Join(filterArr, ",")
   }
   sourceArr := []string{
      "baseInfo",
      "targetInfo",
      "content",
      "id",
      "picMaxUrl",
      "picDate",
      "showLabels",
      "taskName",
   if len(mustNotArr) > 0 {
      mustNotStr = strings.Join(mustNotArr, ",")
   }
   sourceStr := strings.Join(sourceArr, ",")
   log.Log.Infoln("filterArr:", filterStr)
   param := "{\"query\":{\"bool\":{\"filter\":["+filterStr+"]}},\"size\":\""+sizeStr+"\",\"sort\":[{\"picDate\":{\"order\":\"desc\"}}]," +
      "\"_source\":{\"includes\":["+sourceStr+"],\"excludes\":[\"*.feature\",\"*.attachTarget\",\"*.targetLocation\",\"alarmRules\"]}" +
   param := "{\"query\":{\"bool\":{\"filter\":["+filterStr+"],\"must_not\":["+mustNotStr+"]}},\"size\":\""+sizeStr+"\",\"sort\":[{\"picDate\":{\"order\":\"desc\"}}]," +
      "\"_source\":{\"includes\":[\"cameraAddr\",\"baseInfo\",\"targetInfo\",\"content\",\"id\",\"picMaxUrl\",\"picDate\",\"showLabels\",\"taskName\",\"sdkName\",\"videoUrl\",\"alarmRules\"],\"excludes\":[\"*.feature\",\"*.attachTarget\",\"*.targetLocation\"]}" +
      "}"
   err, tokenRes := GetEsDataReq(url, param, true)
   if err != nil {
      log.Log.Errorln(err)
      log.Log.Errorln("GetEsDataReq err:", err)
      return nil
   }
   jsonstring, _ := json.Marshal(tokenRes)