tcp server 用于给andriod 客户端定时发送消息
liuxiaolong
2020-07-28 ec38af9a2f4ab06b202d88c0ab29235645551df8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package esutil
 
import (
    "bytes"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "strconv"
    "strings"
    "time"
 
    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))
 
    if err != nil {
        return err, nil
    }
 
    req.Header.Add("Content-Type", "application/json")
    timeout := time.Duration(10 * time.Second) //超时时间50ms
    client := &http.Client{Timeout: timeout}
    resp, err := client.Do(req)
 
    if err != nil {
        return err, nil
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return err, nil
    }
 
    jsonStr := string(body)
    var dat map[string]interface{}
    dec := json.NewDecoder(strings.NewReader(jsonStr))
 
    if err := dec.Decode(&dat); err == io.EOF {
        return err, nil
    } else if err != nil {
        return err, nil
    }
    // 是否需要 解析 es 返回的 source
    if isSource {
        dat, ok := dat["hits"].(map[string]interface{})
        if !ok {
            return errors.New("data is not type of  map[string]interface{}"), nil
        }
 
        var data = make(map[string]interface{}, 2)
        data["total"] = dat["total"]
        sources := []interface{}{}
        for _, value := range dat["hits"].([]interface{}) {
            d := make(map[string]interface{})
            source, ok := value.(map[string]interface{})["_source"].(map[string]interface{})
            if !ok {
                return errors.New("value is not type of map[string]interface{}"), nil
            }
 
            d["id"] = value.(map[string]interface{})["_id"]
            d["picDate"] = source["picDate"]
            pmax, exist := source["picMaxUrl"]
            if !exist {
                continue
            }
            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 {
                log.Log.Infoln("err:", err)
                continue
            }
 
            tiArr := []TargetInfo{}
            err = json.Unmarshal(tB, &tiArr)
            if err !=nil {
                log.Log.Infoln("err:", err)
                continue
            }
            if len(tiArr) > 0 {
                ti := tiArr[0]
                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 bInfos,ok := source["baseInfo"]; ok && bInfos != nil {
                        d["baseInfo"] = getSourceBaseInfo(bInfos)
                    } else {
                        d["baseInfo"] = []interface{}{}
                    }
                    d["sdkType"] = "人脸"
                } else {
                    d["sdkType"] = source["taskName"]
                    d["picSmUrl"] = d["picMaxUrl"]
                }
            } else {
                d["picSmUrl"] = d["picMaxUrl"]
            }
 
            vUri := source["videoUrl"]
            if vUri != nil && vUri.(string) != "" {
                d["videoNum"] = "http://"+vUri.(string)
            } else {
                d["videoNum"] = ""
            }
 
            sources = append(sources, d)
        }
        data["datalist"] = sources
        return nil, data
    } else {
        return nil, dat
    }
}
 
type AlarmRule struct {
    GroupId             string             `json:"groupId"`
    AlarmLevel             string             `json:"alarmLevel"`
}
 
type TargetInfo struct {
    TargetId         string          `json:"targetId"`
    TargetType         string             `json:"targetType"`
    PicSmUrl         string             `json:"picSmUrl"`
    TargetScore     float32         `json:"targetScore"`
}
 
type BaseInfo struct {
    TaskId             string         `json:"taskId"`
    TaskName         string         `json:"taskName"`
    LikePer         string         `json:"likePer"`
    TableId         string         `json:"tableId"`
    TableName         string         `json:"tableName"`
    PersonId         string         `json:"personId"`
    PersonPicUrl     string         `json:"personPicUrl"`
    PersonName         string         `json:"personName"`
    Gender             string         `json:"gender"`
    PhoneNum         string         `json:"phoneNum"`
    IDCard             string         `json:"IDCard"`
    MonitorLevel     string         `json:"monitorLevel"`
    Content         string         `json:"content"`
}
 
type TI struct {
    BwType           string      `json:"bwType"`
    TargetPicUrl     string         `json:"targetPicUrl"`
    TargetName         string         `json:"targetName"`
    TargetId         string         `json:"targetId"`
    TableId         string         `json:"tableId"`
    CompareScore     string         `json:"compareScore"`
    MonitorLevel     string         `json:"monitorLevel"`
    Content         string         `json:"content"`
    TableName         string         `json:"tableName"`
    Labels             string         `json:"labels"`
}
 
func getSourceBaseInfo(bInfos interface{}) []BaseInfo {
    baseInfoArr := make([]BaseInfo,0)
 
    b, err := json.Marshal(bInfos)
    if err == nil {
        var targetArr []TI
        if err = json.Unmarshal(b, &targetArr); err == nil && len(targetArr) >0 {
            for _,t := range targetArr {
                idCard,sex := "",""
                if t.Labels != "" {
                    arr := strings.Split(t.Labels, "/")
                    if len(arr) > 0 {
                        for _,str := range arr {
                            if str == "男" || str == "女" {
                                sex = str
                                break
                            }
                        }
                        for _,str := range arr {
                            if len(str) == 18 {
                                idCard = str
                                break
                            }
                        }
                    }
                }
                baseInfoArr = append(baseInfoArr, BaseInfo{
                    TaskId: "",//2.0新字段
                    TaskName: "",//2.0新字段
                    LikePer: t.CompareScore,
                    TableId: "",//2.0新字段
                    TableName: t.TableName,
                    PersonId: t.TargetId,
                    PersonName: t.TargetName,//人员姓名,从管理平台获取
                    PersonPicUrl: t.TargetPicUrl,
                    Gender: sex,
                    PhoneNum: "",//手机号,从管理平台获取
                    IDCard: idCard,
                    MonitorLevel: t.MonitorLevel,//2.0新字段
                    Content: t.Content,
                })
            }
        }
    }
 
    return baseInfoArr
}
 
func PostAction(sec int, Eurl string, ishub string, size int, lastT time.Time, curTime time.Time) []byte {
    index := "ai_ocean"
    url := fmt.Sprintf("%s%s%s", Eurl, index, "/_search")
 
    sizeStr :=""
    if size <=0 {
        sizeStr = "1000"
    } else {
        sizeStr = strconv.Itoa(size)
    }
    preSec := "10"
    if sec <=0 {
        preSec = "10"
    } else {
        preSec = strconv.Itoa(sec)
    }
    var filterArr []string
    var mustNotArr []string
    //是否查报警数据
    if ishub == "hub" {
        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, ",")
    }
    if len(mustNotArr) > 0 {
        mustNotStr = strings.Join(mustNotArr, ",")
    }
    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\"],\"excludes\":[\"*.feature\",\"*.attachTarget\",\"*.targetLocation\",\"alarmRules\"]}" +
        "}"
    err, tokenRes := GetEsDataReq(url, param, true)
 
    if err != nil {
        log.Log.Errorln("GetEsDataReq err:", err)
        return nil
    }
    jsonstring, _ := json.Marshal(tokenRes)
    if len(jsonstring) <= 26 {
        return nil
    }
    return jsonstring
}