sunty
2019-06-28 88d229d880079db1d31af1d4cbed3b8eb12fd47d
Merge branch 'master' of http://192.168.1.14:10010/r/webserver

# Conflicts:
# router/router.go
3个文件已添加
6个文件已修改
745 ■■■■■ 已修改文件
controllers/camera.go 137 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/dictionary.go 32 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/eventPush.go 191 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/fileController.go 18 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/pollConfig.go 110 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
main.go 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
middlewares/auth/jwt.go 47 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
router/router.go 27 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
service/FaceSdkService.go 180 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/camera.go
@@ -3,6 +3,7 @@
import (
    "encoding/json"
    "fmt"
    "strconv"
    "github.com/gin-gonic/gin"
@@ -14,20 +15,25 @@
type CameraController struct{}
type CameraVo struct {
    Id        string       `json:"id"`
    Name      string       `json:"name"`
    Type      int          `json:"type" `
    Addr      string       `json:"addr"`
    Areaid    uint         `json:"areaid"`
    Longitude float64      `json:"longitude"`
    Latitude  float64      `json:"latitude"`
    Rtsp      string       `json:"rtsp"`
    Ip        string       `json:"ip"`
    Port      int          `json:"port"`
    Username  string       `json:"username"`
    Password  string       `json:"password"`
    Brand     string       `json:"brand"`
    Reserved  string       `json:"reserved"`
    Id        string  `json:"id"`
    Name      string  `json:"name"`
    Type      int     `json:"type" `
    Addr      string  `json:"addr"`
    Areaid    uint    `json:"areaid"`
    Longitude float64 `json:"longitude"`
    Latitude  float64 `json:"latitude"`
    Rtsp      string  `json:"rtsp"`
    Ip        string  `json:"ip"`
    Port      int     `json:"port"`
    Username  string  `json:"username"`
    Password  string  `json:"password"`
    Brand     string  `json:"brand"`
    Reserved  string  `json:"reserved"`
    IsRunning   bool   `json:"is_running"`    //是否正在解码
    RunEnable   bool   `json:"run_enable"`    //控制实时处理或轮询处理的开关
    RunType     int    `json:"run_type"`      //处理类型:0:轮询,1:实时
    RunServerId string `json:"run_server_id"` //当前正在处理的分析服务器id
}
// @Summary 添加摄像机
@@ -49,7 +55,7 @@
        return
    }
    cam.Id = util.PseudoUuid()
    paramBody :=util.Struct2Map(cam)
    paramBody := util.Struct2Map(cam)
    if api.CameraAdd(paramBody) {
        util.ResponseFormat(c, code.Success, cam)
        return
@@ -76,7 +82,7 @@
        util.ResponseFormat(c, code.RequestParamError, "参数错误")
        return
    }
    paramBody :=util.Struct2Map(cam)
    paramBody := util.Struct2Map(cam)
    if api.CameraAdd(paramBody) {
        util.ResponseFormat(c, code.Success, cam)
        return
@@ -97,11 +103,11 @@
    var api dbapi.CameraApi
    cid := c.Param("cid")
    if api.CameraDelete(cid){
    if api.CameraDelete(cid) {
        util.ResponseFormat(c, code.Success, "删除成功")
        return
    }
    util.ResponseFormat(c, code.ComError,"删除失败")
    util.ResponseFormat(c, code.ComError, "删除失败")
}
// @Summary 显示摄像机
@@ -115,9 +121,9 @@
func (ac CameraController) CameraSel(c *gin.Context) {
    var api dbapi.CameraApi
    cid := c.Param("cid")
    camera,err := api.GetCameraById(cid)
    if err !=nil {
        util.ResponseFormat(c,code.ComError,"查询失败")
    camera, err := api.GetCameraById(cid)
    if err != nil {
        util.ResponseFormat(c, code.ComError, "查询失败")
        return
    }
@@ -187,3 +193,92 @@
    fmt.Println(cameraId)
    fmt.Println(areaId)
}
// @Summary 获取运行类型获取摄像机列表
// @Description 获取运行类型获取摄像机列表
// @Produce json
// @Tags camera
// @Param runType query int true "0:查轮询,1:查实时"
// @Param cameraName query string false "查询条件"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/camera/getCamerasByRunType [get]
func (cc CameraController) GetCamerasByRunType(c *gin.Context) {
    runTypeStr := c.Query("runType")
    cameraName := c.Query("cameraName")
    fmt.Println("runType:", runTypeStr)
    fmt.Println("cameraName:", cameraName)
    runType, err := strconv.Atoi(runTypeStr)
    if err != nil || (runType != 0 && runType != 1) {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.CameraApi
    b, list := api.GetCamerasByRunType(runType, cameraName)
    if b {
        dataBytes, _ := json.Marshal(list)
        var cams []CameraVo
        json.Unmarshal(dataBytes, &cams)
        util.ResponseFormat(c, code.Success, cams)
    } else {
        util.ResponseFormat(c, code.ComError, err)
    }
}
// @Summary 切换摄像机运行实时或轮询的开关
// @Description 切换摄像机运行实时或轮询的开关
// @Produce json
// @Tags camera
// @Param cameraId query string true "摄像机id"
// @Param runEnable query bool true "开启:true,关闭:false"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/camera/updateRunEnable [post]
func (cc CameraController) UpdateRunEnable(c *gin.Context) {
    cameraId := c.PostForm("cameraId")
    enableStr := c.PostForm("runEnable")
    runEnable, err := strconv.ParseBool(enableStr)
    if cameraId == "" || err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.CameraApi
    b, data := api.UpdateRunEnable(cameraId, runEnable)
    fmt.Println("data:", data)
    if b {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, "更新失败")
    }
}
type CameraChangeRunVo struct {
    CameraIds []string `json:"camera_ids"`
    RunType   int      `json:"run_type"`
}
// @Summary 摄像机轮询和实时状态切换
// @Description 摄像机轮询和实时状态切换
// @Produce json
// @Tags camera
// @Param changeRunBody body controllers.CameraChangeRunVo true "参数结构体,0:实时切轮询,1:轮询切实时"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/camera/changeRunType [post]
func (cc CameraController) ChangeRunType(c *gin.Context) {
    var ccrVo CameraChangeRunVo
    if err := c.BindJSON(&ccrVo); err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    paramBody := util.Struct2Map(ccrVo)
    var api dbapi.CameraApi
    b, data := api.ChangeRunType(paramBody)
    if b {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, "更新失败")
    }
}
controllers/dictionary.go
@@ -2,13 +2,12 @@
import (
    "basic.com/dbapi.git"
    "github.com/gin-gonic/gin"
    "webserver/extend/code"
    "webserver/extend/util"
    "github.com/gin-gonic/gin"
)
type DictionaryController struct {
}
// @Summary 根据类型查找字典
@@ -23,8 +22,31 @@
    var api dbapi.DicApi
    flag, data := api.FindByType("")
    if flag {
        util.ResponseFormat(c,code.Success,data)
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c,code.ComError,data)
        util.ResponseFormat(c, code.ComError, data)
    }
}
}
// @Summary 根据父ID查找字典
// @Description  根据父ID查找字典
// @Produce json
// @Tags 字典
// @Param parentId query string false "parentId"
// @Success 200 {string} json "{"code":200, success:true, msg:"请求处理成功", data:"成功信息"}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:"错误信息内容"}"
// @Router /data/api-v/dictionary/findByParentId [get]
func (controller DictionaryController) FindByParentId(c *gin.Context) {
    parentId := c.Query("parentId")
    if parentId == "" {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.DicApi
    flag, data := api.FindByParentId(parentId)
    if flag {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, "查询失败")
    }
}
controllers/eventPush.go
New file
@@ -0,0 +1,191 @@
package controllers
import (
    "basic.com/dbapi.git"
    "github.com/gin-gonic/gin"
    "webserver/extend/code"
    "webserver/extend/util"
)
type EventPushController struct {
}
type EventPushVo struct {
    Id           string `json:"id"`
    Name         string `json:"name"`
    TimeStart    string `json:"time_start"`
    TimeEnd      string `json:"time_end"`
    IsSatisfyAll bool   `json:"is_satisfy_all"`
    RuleText     string `json:"rule_text"`
    Enable       bool   `json:"enable"`
    LinkType     string `json:"link_type"`
    LinkDevice   string `json:"link_device"`
    IpPorts []EventPushServerPortVo `json:"ip_ports"`
    Urls    []EventUrlVo            `json:"urls"`
    Rules   []EventPushRuleVo       `json:"rules"`
}
type EventPushRuleVo struct {
    Id           string `json:"id"`
    TopicType    string `json:"topic_type"` //参数主题,目前分为五类(摄像机、底库、任务、人员、报警等级)
    TopicArg     string `json:"topic_arg"`  //主题对应的具体参数
    Operator     string `json:"operator"`
    OperatorType string `json:"operator_type"`
    RuleValue    string `json:"rule_value"`
    EventPushId  string `json:"event_push_id"`
}
type EventPushServerPortVo struct {
    ServerIp string `json:"server_ip"`
    Port     int    `json:"port"`
    Enable   bool   `json:"enable"`
}
type EventUrlVo struct {
    Url    string `json:"url"`
    Enable bool   `json:"enable"`
}
// @Summary 事件推送保存
// @Description 事件推送保存
// @Tags 事件推送
// @Param SaveArgs body controllers.EventPushVo true "时间推送保存参数"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/eventPush/save [post]
func (epc EventPushController) Save(c *gin.Context) {
    var saveBody EventPushVo
    if err := c.BindJSON(&saveBody); err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.EventPushApi
    paramBody := util.Struct2Map(saveBody)
    flag, data := api.Save(paramBody)
    if flag {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, data)
    }
}
// @Summary 根据事件推送主题的一级和二级选项获取最后下拉菜单列表
// @Description  根据事件推送主题的一级和二级选项获取最后下拉菜单列表
// @Produce json
// @Tags 事件推送
// @Param topic query string true "一级主题选项,例如:camera(摄像机)"
// @Param type query string true "子选项类型,例如:name(名称)或addr(位置)"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/eventPush/findByEventTopic [get]
func (epc EventPushController) FindByEventTopic(c *gin.Context) {
    topic := c.Query("topic")
    childType := c.Query("type")
    if topic == "" {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.EventPushApi
    flag, data := api.FindByEventTopic(topic, childType)
    if flag {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, data)
    }
}
// @Summary 查全部
// @Description  查全部
// @Produce json
// @Tags 事件推送
// @Param name query string false "事件名称"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/eventPush/findAll [get]
func (controller EventPushController) FindAll(c *gin.Context) {
    name := c.Query("name")
    var api dbapi.EventPushApi
    flag, data := api.FindAll(name)
    if flag {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, "")
    }
}
// @Summary 事件推送编辑
// @Description  事件推送编辑
// @Produce json
// @Tags 事件推送
// @Param id query string true "id"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/eventPush/getById [get]
func (controller EventPushController) GetById(c *gin.Context) {
    id := c.Query("id")
    if id == "" {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.EventPushApi
    flag, data := api.GetById(id)
    if flag {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, "")
    }
}
type ChangeStatusVo struct {
    Id     string `json:"id"`
    Enable bool   `json:"enable"`
}
// @Summary 改变enable状态
// @Description  改变enable状态
// @Produce json
// @Tags 事件推送
// @Param statusBody body controllers.ChangeStatusVo true "参数结构"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/eventPush/changeStatus [post]
func (controller EventPushController) ChangeStatus(c *gin.Context) {
    var statusBody ChangeStatusVo
    err := c.BindJSON(&statusBody)
    if err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.EventPushApi
    flag, data := api.ChangeStatus(statusBody.Id, statusBody.Enable)
    if flag {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, data)
    }
}
// @Summary 根据id删除
// @Description  根据id删除
// @Accept x-www-form-urlencoded
// @Produce json
// @Tags 事件推送
// @Param id query string true "id"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/eventPush/delete [post]
func (controller EventPushController) Delete(c *gin.Context) {
    id := c.PostForm("id")
    if id == "" {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.EventPushApi
    flag, data := api.Delete(id)
    if flag {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, data)
    }
}
controllers/fileController.go
@@ -85,6 +85,24 @@
    }
}
// @Description 人员照片上传并获取特征值
// @Router /data/api-v/dbperson/fileUploadTest [POST]
func (controller FileController) UploadPersonTest(c *gin.Context) {
    file, header, err := c.Request.FormFile("file") //image这个是uplaodify参数定义中的   'fileObjName':'image'
    if err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    //文件的名称
    filename := header.Filename
    fmt.Println(file, err, filename)
    if err != nil {
        log.Fatal(err)
        filename = uuid.NewV4().String()
    }
}
/*// 对上面的编码结果进行base64解码
decodeBytes, err := base64.StdEncoding.DecodeString(encodeString)
if err != nil {
controllers/pollConfig.go
New file
@@ -0,0 +1,110 @@
package controllers
import (
    "basic.com/dbapi.git"
    "github.com/gin-gonic/gin"
    "strconv"
    "webserver/extend/code"
    "webserver/extend/util"
)
type PollConfigController struct {
}
type PollConfig struct {
    ServerId   string `json:"server_id"`   //服务器id
    PollPeriod int    `json:"poll_period"` //轮询周期
    Delay      int    `json:"delay"`       //延时时间
    Enable     bool   `json:"enable"`      //是否启用轮询
}
// @Summary 保存轮询周期
// @Description 保存轮询周期
// @Produce json
// @Tags 轮询配置
// @Param period query int true "轮询周期"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/pollConfig/savePollPeriod [post]
func (controller PollConfigController) SavePollPeriod(c *gin.Context) {
    periodStr := c.PostForm("period")
    period, err := strconv.Atoi(periodStr)
    if periodStr == "" || err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.SysSetApi
    b, data := api.SavePollPeriod(period)
    if b {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, "保存失败")
    }
}
// @Summary 保存轮询延时
// @Description 保存轮询延时
// @Produce json
// @Tags 轮询配置
// @Param delay query int true "轮询延时时间"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/pollConfig/savePollDelay [post]
func (controller PollConfigController) SavePollDelay(c *gin.Context) {
    delayStr := c.PostForm("delay")
    delay, err := strconv.Atoi(delayStr)
    if delayStr == "" || err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.SysSetApi
    b, data := api.SavePollDelay(delay)
    if b {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, "保存失败")
    }
}
// @Summary 获取本机轮询配置
// @Description 获取本机轮询配置
// @Produce json
// @Tags 轮询配置
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/pollConfig/getPollConfig [get]
func (controller PollConfigController) GetPollConfig(c *gin.Context) {
    var api dbapi.SysSetApi
    b, data := api.GetPollConfig()
    if b {
        util.ResponseFormat(c, code.Success, data)
    } else {
        util.ResponseFormat(c, code.ComError, "查询失败")
    }
}
type PollEnableVo struct {
    Enable bool `json:"enable"`
}
// @Summary 切换轮询开关
// @Description 切换轮询开关
// @Produce json
// @Tags 轮询配置
// @Param argBody body controllers.PollEnableVo true "开关参数"
// @Success 200 {string} json "{"code":200, success:true, msg:"", data:""}"
// @Failure 500 {string} json "{"code":500, success:false, msg:"",data:""}"
// @Router /data/api-v/pollConfig/updateEnable [post]
func (controller PollConfigController) UpdateEnable(c *gin.Context) {
    var argBody PollEnableVo
    if err := c.BindJSON(&argBody); err != nil {
        util.ResponseFormat(c, code.RequestParamError, "参数有误")
        return
    }
    var api dbapi.SysSetApi
    if api.UpdatePollEnable(argBody.Enable) {
        util.ResponseFormat(c, code.Success, "修改成功")
    } else {
        util.ResponseFormat(c, code.ComError, "修改失败")
    }
}
main.go
@@ -6,10 +6,13 @@
    "webserver/extend/config"
    "webserver/models"
    "webserver/router"
    "webserver/service"
)
func main() {
    service.TestPushImgMsg()
    envirment := flag.String("e", "dev", "")
    flag.Usage = func() {
        glog.Exit("flag parse usage !")
middlewares/auth/jwt.go
@@ -2,7 +2,6 @@
import (
    "encoding/json"
    "errors"
    jwtLib "github.com/dgrijalva/jwt-go"
    "github.com/dgrijalva/jwt-go/request"
    "github.com/gin-gonic/gin"
@@ -14,14 +13,14 @@
type jwtAuthManager struct {
    secret string
    expire time.Duration
    alg string
    alg    string
}
func NewJwtAuthDriver() *jwtAuthManager{
func NewJwtAuthDriver() *jwtAuthManager {
    return &jwtAuthManager{
        secret:TokenKey,
        expire:time.Hour*8,
        alg:"HS256",
        secret: TokenKey,
        expire: time.Hour * 8,
        alg:    "HS256",
    }
}
@@ -35,44 +34,44 @@
    if len(t) < 2 {
        return false
    }
    var keyFunc = func(token *jwtLib.Token) (interface{},error) {
    var keyFunc = func(token *jwtLib.Token) (interface{}, error) {
        b := []byte(jwtAuth.secret)
        return b,nil
        return b, nil
    }
    authJwtToken, err:= request.ParseFromRequest(c.Request,request.OAuth2Extractor,keyFunc)
    if err !=nil {
    authJwtToken, err := request.ParseFromRequest(c.Request, request.OAuth2Extractor, keyFunc)
    if err != nil {
        return false
    }
    c.Set("User",map[string]interface{}{
        "token":authJwtToken,
    c.Set("User", map[string]interface{}{
        "token": authJwtToken,
    })
    return authJwtToken.Valid
}
func (jwtAuth *jwtAuthManager) User(c *gin.Context) interface{}{
func (jwtAuth *jwtAuthManager) User(c *gin.Context) interface{} {
    var jwtToken *jwtLib.Token
    if jwtUser, exist := c.Get("User");!exist{
        tokenStr :=strings.Replace(c.Request.Header.Get("Authorization"),"Bearer ","",-1)
        if tokenStr == ""{
    if jwtUser, exist := c.Get("User"); !exist {
        tokenStr := strings.Replace(c.Request.Header.Get("Authorization"), "Bearer ", "", -1)
        if tokenStr == "" {
            return map[interface{}]interface{}{}
        }
        var err error
        jwtToken,err = jwtLib.Parse(tokenStr, func(token *jwtLib.Token) (interface{}, error) {
            b :=[]byte(jwtAuth.secret)
            return b,nil
        jwtToken, err = jwtLib.Parse(tokenStr, func(token *jwtLib.Token) (interface{}, error) {
            b := []byte(jwtAuth.secret)
            return b, nil
        })
        if err !=nil {
            panic(err)
        if err != nil {
            return nil
        }
    } else {
        jwtToken = jwtUser.(map[string]interface{})["token"].(*jwtLib.Token)
    }
    if claims,ok :=jwtToken.Claims.(jwtLib.MapClaims);ok && jwtToken.Valid{
    if claims, ok := jwtToken.Claims.(jwtLib.MapClaims); ok && jwtToken.Valid {
        var user map[string]interface{}
        if err := json.Unmarshal([]byte(claims["user"].(string)), &user); err != nil {
            panic(err)
            return nil
        }
        c.Set("User", map[string]interface{}{
            "token": jwtToken,
@@ -80,7 +79,7 @@
        })
        return user
    } else {
        panic(errors.New("decode jwt user claims fail"))
        return nil
    }
}
router/router.go
@@ -7,6 +7,8 @@
    "github.com/szuecs/gin-glog"
    "time"
    "webserver/controllers"
    _ "webserver/docs"
)
func NewRouter() *gin.Engine {
@@ -32,6 +34,9 @@
    cameraTaskArgsController := new(controllers.CameraTaskArgsController)
    dicController := new(controllers.DictionaryController)
    userController := new(controllers.UserController)
    eventPushController := new(controllers.EventPushController)
    pollConfigController := new(controllers.PollConfigController)
    fileController := new(controllers.FileController)
    urlPrefix := "/data/api-v" // wp 添加 路径 前缀
    userApi := r.Group(urlPrefix + "/user")
@@ -63,6 +68,9 @@
        camera.GET("/delTask/:cameraId/:taskId", cameraController.CameraDelTask)
        camera.POST("/saveTask", cameraController.CameraTaskSave)
        camera.GET("/getRulesByCameraAndTask", cameraTaskArgsController.FindByCameraAndTask)
        camera.GET("/getCamerasByRunType", cameraController.GetCamerasByRunType)
        camera.POST("/updateRunEnable", cameraController.UpdateRunEnable)
        camera.POST("/changeRunType", cameraController.ChangeRunType)
    }
    cameraTaskArgsApi := r.Group(urlPrefix + "/cameraTaskArgs")
@@ -133,6 +141,8 @@
        vdbperson.POST("/deleteDbPersonById/:uuid", dbPersonCont.DeleteDbPerson)
        vdbperson.POST("/deleteMoreDbPerson", dbPersonCont.DeleteMoreDbPerson)
        vdbperson.PUT("/addDbPerson", dbPersonCont.AddDbPerson)
        vdbperson.POST("/fileUploadTest", fileController.UploadPersonTest)
    }
    // 系统设置 操作
@@ -166,6 +176,23 @@
    dicApi := r.Group(urlPrefix + "/dictionary")
    {
        dicApi.GET("/findByType", dicController.FindByType)
        dicApi.GET("/findByParentId", dicController.FindByParentId)
    }
    eventPushApi := r.Group(urlPrefix + "/eventPush")
    {
        eventPushApi.POST("/save", eventPushController.Save)
        eventPushApi.GET("/findByEventTopic", eventPushController.FindByEventTopic)
        eventPushApi.GET("/findAll", eventPushController.FindAll)
        eventPushApi.GET("/getById", eventPushController.GetById)
        eventPushApi.POST("/changeStatus", eventPushController.ChangeStatus)
        eventPushApi.POST("/delete", eventPushController.Delete)
    }
    pollCApi := r.Group(urlPrefix + "/pollConfig")
    {
        pollCApi.POST("/savePollPeriod", pollConfigController.SavePollPeriod)
        pollCApi.POST("/savePollDelay", pollConfigController.SavePollDelay)
        pollCApi.GET("/getPollConfig", pollConfigController.GetPollConfig)
        pollCApi.POST("/updateEnable", pollConfigController.UpdateEnable)
    }
    // 文件 上传
service/FaceSdkService.go
New file
@@ -0,0 +1,180 @@
package service
import (
    "basic.com/pubsub/protomsg.git"
    "basic.com/valib/deliver.git"
    "encoding/base64"
    "fmt"
    "github.com/gogo/protobuf/proto"
    "github.com/pierrec/lz4"
    "github.com/satori/go.uuid"
    "gocv.io/x/gocv"
    "time"
)
const (
    Ipc_Push_Ext       = "_2.ipc"
    Ipc_Pull_Ext       = "_1.ipc"
    Ipc_Url_Pre        = "ipc:///tmp///"
    Virtual_FaceTaskId = "92496BDF-2BFA-98F2-62E8-96DD9866ABD2"
    Virtual_FaceSdkId  = "virtual-faceextract-sdk-pull"
    Url_Service_PUSH   = Ipc_Url_Pre + Virtual_FaceSdkId + Ipc_Push_Ext
    Url_Service_PULL   = Ipc_Url_Pre + Virtual_FaceSdkId + Ipc_Pull_Ext
)
var imgPushChan chan []byte
var client_push deliver.Deliver
var client_pull deliver.Deliver
func TestPushImgMsg() {
    InitService()
    i := readImgFile()
    fmt.Printf("width:%d,height:%d,data.length:%d,timestamp:%s,id:%d\n", i.Width, i.Height, len(i.Data), i.Timestamp, i.Id)
    if b, err := proto.Marshal(&i); err != nil {
        fmt.Println("protoImage marshal err")
        return
    } else {
        bc := make([]byte, len(b))
        ht := make([]int, 64<<10)
        n, err := lz4.CompressBlock(b, bc, ht)
        if err != nil {
            fmt.Println(err)
        }
        if n >= len(b) {
            fmt.Println("image is not compressible")
        }
        bc = bc[:n]
        for {
            PushImgMsg(bc)
            fmt.Println("pushed img")
            time.Sleep(5 * time.Second)
        }
    }
}
func readImgFile() protomsg.Image {
    var i protomsg.Image
    timeUnix := time.Now().Unix()
    formatTimeStr := time.Unix(timeUnix, 0).Format("2006-01-02 15:04:05")
    filePath := "/home/user/workspace/timg.jpg"
    picMat := gocv.IMRead(filePath, gocv.IMReadColor)
    defer picMat.Close()
    if picMat.Empty() {
        fmt.Println("file not exist")
        return i
    }
    height := int32(picMat.Rows())
    width := int32(picMat.Cols())
    data := picMat.ToBytes()
    //wrMat,_ := gocv.NewMatFromBytes(picMat.Rows(),picMat.Cols(),gocv.MatTypeCV8UC3,data)
    //
    //gocv.IMWrite("xxx.jpg", wrMat)
    i = protomsg.Image{
        Width:     width,
        Height:    height,
        Timestamp: formatTimeStr,
        Data:      data,
        Id:        timeUnix,
    }
    i.Cid = uuid.NewV4().String() //数据唯一id
    fmt.Println("gocv read img completed")
    return i
}
func PushImgMsg(is []byte) {
    imgPushChan <- is
}
var resultMap map[string]protomsg.SdkMessage
func InitService() {
    fmt.Println("service init!")
    imgPushChan = make(chan []byte)
    resultMap = make(map[string]protomsg.SdkMessage, 0)
    client_push = deliver.NewClient(deliver.PushPull, Url_Service_PUSH)
    client_pull = deliver.NewClient(deliver.PushPull, Url_Service_PULL)
    defer func() {
        client_push.Close()
        client_pull.Close()
    }()
    go thSend()
    go thRecv()
}
func thSend() {
    for {
        select {
        case d := <-imgPushChan:
            fmt.Println("imgPushChan in")
            err := client_push.Send(d)
            if err != nil {
                fmt.Println("img Send err:", err)
            }
        default:
            //fmt.Println("no img in")
        }
    }
}
func thRecv() {
    for {
        resultBytes, err := client_pull.Recv()
        if err != nil {
            fmt.Println("pull err:", err)
            continue
        }
        rMsg := protomsg.SdkMessage{}
        if err := proto.Unmarshal(resultBytes, &rMsg); err == nil {
            fmt.Println("received MSG:", rMsg.Cid)
            perId := rMsg.Cid //数据id
            if rMsg.Tasklab != nil && rMsg.Tasklab.Taskid == Virtual_FaceTaskId {
                sdkInfos := rMsg.Tasklab.Sdkinfos
                fmt.Println("Len(sdkInfos)=", len(sdkInfos))
                for _, swt := range sdkInfos {
                    fmt.Println("sdkName:", swt.SdkName)
                    if swt.Sdktype == "FaceDetect" {
                        fmt.Println("人脸检测结果")
                        var pfp protomsg.ParamFacePos
                        err := proto.Unmarshal(swt.Sdkdata, &pfp)
                        if err != nil {
                            fmt.Println("faceDetect result unmarshal err:", err)
                        } else {
                            for _, face := range pfp.Faces {
                                fmt.Println("FacePos:", face.Pos)
                                fmt.Println("ThftResult:", face.Result)
                            }
                        }
                    }
                    if swt.Sdktype == "FaceExtract" {
                        fmt.Println("sdkData.len:", len(swt.Sdkdata))
                        var pff protomsg.ParamFaceFeature
                        if err := proto.Unmarshal(swt.Sdkdata, &pff); err != nil {
                            //fmt.Println("ParamFaceFeature unmarshal err:",err)
                        } else {
                            fmt.Println("目标数:", len(pff.ExtComp))
                            for _, fea := range pff.ExtComp {
                                base64Fea := base64.StdEncoding.EncodeToString(fea.Feats)
                                fmt.Println("perId:", perId)
                                fmt.Println("faceFeature:", base64Fea)
                            }
                        }
                        break
                    }
                }
            }
            //resultMap[rMsg.Cid] = rMsg
        } else {
            fmt.Println("recv msg Err:", err)
        }
    }
}