554325746@qq.com
2019-06-29 e1a60b6255da756308cf68cc4640868cdda428c5
add updatesnopshotUrl
1个文件已添加
1个文件已修改
166 ■■■■■ 已修改文件
controllers/camera.go 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
service/CamraUpdatesnashot.go 145 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/camera.go
@@ -10,6 +10,7 @@
    "basic.com/dbapi.git"
    "webserver/extend/code"
    "webserver/extend/util"
    "webserver/service"
)
type CameraController struct{}
@@ -254,6 +255,24 @@
    }
}
// @Summary  更新底图
// @Description 刷新底图
// @Produce json
// @Tags camera
// @Param cid path 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/camera/updateSnapshotUrl/{cid} [get]
func(cc CameraController) UpdateSnapshotUrl(c *gin.Context){
    cid := c.Param("cid")
    filename, err := service.UpdateSnapshotUrl(cid)
    if err != nil {
        util.ResponseFormat(c, code.ComError, "更新失败")
        return
    }
    util.ResponseFormat(c, code.Success, filename)
}
type CameraChangeRunVo struct {
    CameraIds []string `json:"camera_ids"`
    RunType   int      `json:"run_type"`
@@ -282,3 +301,5 @@
        util.ResponseFormat(c, code.ComError, "更新失败")
    }
}
service/CamraUpdatesnashot.go
New file
@@ -0,0 +1,145 @@
package service
import (
        "fmt"
        "time"
        "flag"
        "os/exec"
        "bytes"
        "encoding/json"
        "errors"
        "io"
        "log"
        "mime/multipart"
        "net/http"
        "gocv.io/x/gocv"
        "path/filepath"
        "basic.com/dbapi.git"
   )
func PostFormBufferData(uri string, filepath string, fileName string) (maps map[string]interface{}, err0 error) {
          // 要指定转byte的格式
            picMat := gocv.IMRead(filepath, gocv.IMReadColor)
            defer picMat.Close()
            if picMat.Empty() {
                     return nil, errors.New("file not exist")
            }
            pheight := picMat.Rows()
            pwidth := picMat.Cols()
            pdata := picMat.ToBytes()
          imgs := gocv.NewMat()
          imgs, _ = gocv.NewMatFromBytes(pheight, pwidth, gocv.MatTypeCV8UC3, pdata)
          fdata,_ := gocv.IMEncode(".jpg",imgs)
          body := &bytes.Buffer{}
          writer := multipart.NewWriter(body)
            _, err := writer.CreateFormFile("file", fileName)
            if err != nil {
                return nil, err
            }
           boundary := writer.Boundary()
              //close_string := fmt.Sprintf("\r\n--%s--\r\n", boundary)
              close_buf := bytes.NewBufferString(fmt.Sprintf("\r\n--%s--\r\n", boundary))
              file := bytes.NewBuffer(fdata)
              request_reader := io.MultiReader(body, file, close_buf)
              //_, err = io.Copy(part, file)
              //writer.WriteField(key, val)
              request, err := http.NewRequest("POST", uri, request_reader)
              request.Header.Add("Content-Type", writer.FormDataContentType())
              timeout := time.Duration(5 * time.Second) //超时时间50ms
              client := &http.Client{Timeout: timeout}
          resp, err := client.Do(request)
              if err != nil {
                  log.Fatal(err)
                      return nil, err
              }
          defer func() {
              if r := recover(); r != nil {
                  fmt.Printf("panic的内容%v\n", r)
                      msg := "上传图片服务器异常"
                      if _, ok := r.(error); ok {
                          msg = r.(error).Error()
                              fmt.Println("panic--recover()得到的是error类型")
                      }
                  if _, ok := r.(string); ok {
                      msg = r.(string)
                          fmt.Println("panic--recover()得到的是string类型")
                  }
                  err0 = errors.New(msg)
              }
          }()
          defer resp.Body.Close()
          {
     body := &bytes.Buffer{}
      _, err := body.ReadFrom(resp.Body)
          if err != nil {
              log.Fatal(err)
          }
      fmt.Println(resp.StatusCode)
          //fmt.Println(resp.Header)
          fmt.Println(body)
          //decoder := json.NewDecoder(strings.NewReader(body.String()))
          decoder := make(map[string]interface{})
          if err := json.Unmarshal([]byte(body.String()), &decoder); err != nil {
              return nil, err
          }
      return decoder, nil
          }
}
func processphoto(cid string) (local string, err error) {
    var camApi dbapi.CameraApi
    caminfo, err := camApi.GetCameraById(cid)
    _ = caminfo
    if err != nil {
       return  "", err
    }
    _, err = exec.LookPath("ffmpeg")
    if err != nil {
        return "", nil
    }
    piclocal := fmt.Sprintf("%s%s.jpg",*storelocal,time.Now().String())
    cmd := exec.Command("ffmpeg", "-i",caminfo.Rtsp, "-y", "-f", "image2","-t", "0.001","-vf","select='eq(pict_type\\,I)',setpts='N/(25*TB)'", "-s","1920*1080", piclocal)
    err = cmd.Run()
    if err != nil {
        return "",  err
    }
    return piclocal, nil
}
var storelocal = flag.String("storelcoal","/home/user/workspace/gitblit/", "address of picture produce.")
var fileurl    = flag.String("fileurl","http://192.168.1.182:6333/submit", "url of file server.")
func UpdateSnapshotUrl(cid string)(filename string, err error) {
    var camApi dbapi.CameraApi
    flag.Parse()
     piclocal, err := processphoto(cid)
     if err != nil {
        return "", err
     }
    resp, err := PostFormBufferData(*fileurl, piclocal, piclocal )
    if err != nil {
        fmt.Println(err)
        return "", err
    }
    fileurl := resp["fileUrl"].(string)
    filename = filepath.Base(fileurl)
    ok := camApi.UpdateSnapshotUrl(cid, filename))
    if !ok {
        return "",errors.New("update filelocal to camera fail")
    }
    return filename, nil
}