Compare commits

..

7 Commits

5 changed files with 243 additions and 222 deletions

3
go.mod
View File

@ -11,8 +11,7 @@ require (
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
github.com/robfig/cron/v3 v3.0.1 github.com/robfig/cron/v3 v3.0.1
github.com/ulule/deepcopier v0.0.0-20200430083143-45decc6639b6 gocv.io/x/gocv v0.39.0
gocv.io/x/gocv v0.40.0
gorm.io/driver/mysql v1.5.7 gorm.io/driver/mysql v1.5.7
gorm.io/driver/postgres v1.5.11 gorm.io/driver/postgres v1.5.11
gorm.io/gorm v1.25.12 gorm.io/gorm v1.25.12

2
go.sum
View File

@ -106,8 +106,6 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/ulule/deepcopier v0.0.0-20200430083143-45decc6639b6 h1:TtyC78WMafNW8QFfv3TeP3yWNDG+uxNkk9vOrnDu6JA=
github.com/ulule/deepcopier v0.0.0-20200430083143-45decc6639b6/go.mod h1:h8272+G2omSmi30fBXiZDMkmHuOgonplfKIKjQWzlfs=
gocv.io/x/gocv v0.39.0 h1:vWHupDE22LebZW6id2mVeT767j1YS8WqGt+ZiV7XJXE= gocv.io/x/gocv v0.39.0 h1:vWHupDE22LebZW6id2mVeT767j1YS8WqGt+ZiV7XJXE=
gocv.io/x/gocv v0.39.0/go.mod h1:zYdWMj29WAEznM3Y8NsU3A0TRq/wR/cy75jeUypThqU= gocv.io/x/gocv v0.39.0/go.mod h1:zYdWMj29WAEznM3Y8NsU3A0TRq/wR/cy75jeUypThqU=
gocv.io/x/gocv v0.40.0 h1:kGBu/UVj+dO6A9dhQmGOnCICSL7ke7b5YtX3R3azdXI= gocv.io/x/gocv v0.40.0 h1:kGBu/UVj+dO6A9dhQmGOnCICSL7ke7b5YtX3R3azdXI=

View File

@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"gocv.io/x/gocv"
"io" "io"
"log" "log"
"net/http" "net/http"
@ -64,151 +65,139 @@ type videoStreamReq struct {
} }
func GetVideoStream(c *gin.Context) { func GetVideoStream(c *gin.Context) {
var req videoStreamReq
id, _ := c.Get("id") id, _ := c.Get("id")
id1 := id.(int) id1 := id.(int)
deviceIDSTR := c.Query("id") //将query参数绑定到结构体
deviceID, err := strconv.Atoi(deviceIDSTR) if err := c.ShouldBind(&req); err != nil {
if err != nil { c.JSON(400, gin.H{"error": err.Error()})
c.JSON(400, gin.H{"error": "device_id error"})
return return
} } else {
key := c.Query("key") //校验权限
//校验权限 device := service.GetDevice(req.ID, id1)
device := service.GetDevice(deviceID, id1) if device.ID == 0 {
if device.ID == 0 { c.JSON(400, gin.H{"error": "device not exist"})
c.JSON(400, gin.H{"error": "device not exist"}) return
return
}
rKey := worker.GetRedis("video_stream_get_stream_key")
if rKey == "" {
rKey = "123456"
}
//查看id是否存在
index := -1
for _, device_ := range proto.Config.DeviceInfo {
if device_.ID == deviceID {
index = deviceID
break
} }
} //查看id是否存在
if index == -1 { index := -1
c.JSON(400, gin.H{"error": "id config not exist"}) for _, device := range proto.Config.DeviceInfo {
return if device.ID == req.ID {
} index = req.ID
//查看key是否正确 break
if key != rKey {
c.JSON(400, gin.H{"error": "key error"})
return
}
//查看设备是否在获取
isGetting := worker.GetRedis(fmt.Sprintf("device_%d_is_getting", deviceID))
if isGetting != "true" {
c.JSON(400, gin.H{"error": "device is not getting or not exist"})
log.Printf("stream device_id:%d is not getting or not exist", deviceID)
return
}
//设备流
c.Stream(func(w io.Writer) bool {
var count int
errCount := 0
for {
if errCount > 10 {
log.Printf("stream device:%d errCount > 10", deviceID)
return false
} }
buf := make([]byte, 1024*1024)
cnt := -1
if cnt == count || cnt == -1 {
time.Sleep(50 * time.Millisecond)
log.Printf("stream device:%d,cnt =%d,count=%d,errCount=%d", deviceID, cnt, count, errCount)
errCount++
continue
}
count = cnt
_, err = w.Write([]byte("--frame\r\nContent-Type: image/jpeg\r\n\r\n"))
if err != nil {
fmt.Printf("写入头部信息错误: %v\n", err)
buf = nil
return false
}
_, err = w.Write(buf)
if err != nil {
fmt.Printf("写入帧数据错误: %v\n", err)
buf = nil
return false
}
_, err = w.Write([]byte("\r\n"))
if err != nil {
fmt.Printf("写入帧结束标记错误: %v\n", err)
buf = nil
return false
}
time.Sleep(50 * time.Millisecond) // 控制帧率模拟每秒约20帧可按实际调整
buf = nil
} }
}) if index == -1 {
c.JSON(400, gin.H{"error": "id not exist"})
return
}
//查看key是否正确
if req.Key != "123456" {
c.JSON(400, gin.H{"error": "key error"})
return
}
//设备流
c.Stream(func(w io.Writer) bool {
var count int
var frame gocv.Mat
for {
cnt := service.GetDeviceCurrentFrameV2(&frame, req.ID)
if cnt == count {
time.Sleep(50 * time.Millisecond)
continue
}
//gocv.Matrix转为jpeg
img, err2 := gocv.IMEncode(".jpg", frame)
if err2 != nil {
fmt.Printf("img encode err:%v", err2)
time.Sleep(50 * time.Millisecond)
continue
}
frame_ := img.GetBytes()
_, err = w.Write([]byte("--frame\r\nContent-Type: image/jpeg\r\n\r\n"))
if err != nil {
fmt.Printf("写入头部信息错误: %v\n", err)
return false
}
_, err = w.Write(frame_)
if err != nil {
fmt.Printf("写入帧数据错误: %v\n", err)
return false
}
_, err = w.Write([]byte("\r\n"))
if err != nil {
fmt.Printf("写入帧结束标记错误: %v\n", err)
return false
}
time.Sleep(50 * time.Millisecond) // 控制帧率模拟每秒约20帧可按实际调整
}
})
}
} }
// 发送实时视频流 // 发送实时视频流
func GetRealTimeImage(c *gin.Context) { func GetRealTimeImage(c *gin.Context) {
id, _ := c.Get("id") id, _ := c.Get("id")
id1 := id.(int) id1 := id.(int)
deviceId := c.Query("device_id") device_id := c.Query("device_id")
deviceIdInt, _ := strconv.Atoi(deviceId) device_id_int, _ := strconv.Atoi(device_id)
device := service.GetDevice(deviceIdInt, id1) device := service.GetDevice(device_id_int, id1)
if device.ID == 0 { if device.ID == 0 {
c.JSON(http.StatusOK, gin.H{"code": 4, "message": "device not found"}) c.JSON(http.StatusOK, gin.H{"code": 4, "message": "device not found"})
return return
} }
//查看设备是否在获取
isGetting := worker.GetRedis(fmt.Sprintf("device_%d_is_getting", device.ID))
if isGetting != "true" {
c.JSON(http.StatusOK, gin.H{"code": 4, "message": "device is not getting or not exist"})
log.Printf("device_id:%d is not getting or not exist", deviceIdInt)
return
}
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil) ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil { if err != nil {
log.Printf("connect wss err:%v", err) log.Printf("connect wss err:%v", err)
return return
} }
worker.SetRedisWithExpire(strconv.Itoa(int(device.ID))+"_is_play", "1", time.Minute*5) worker.SetRedisWithExpire(strconv.Itoa(int(device.ID))+"_is_play", "1", time.Minute*5)
isGetting = worker.GetRedis(fmt.Sprintf("device_%d_is_getting", device.ID)) log.Printf("device_id:%d has set is_play to 1", device_id_int)
if isGetting != "true" { go subscribeAndHandleMessagesV3(ws, device_id_int)
c.JSON(http.StatusOK, gin.H{"code": 5, "message": "device is not getting or not exist"})
log.Printf("device_id:%d is not getting or not exist", deviceIdInt)
return
}
subscribeAndHandleMessagesV6(ws, deviceIdInt)
} }
func subscribeAndHandleMessagesV6(ws *websocket.Conn, deviceId int) { func subscribeAndHandleMessagesV3(ws *websocket.Conn, device_id int) {
// 生成唯一连接 uuid // 生成唯一连接 uuid
con_id := uuid.New().String() con_id := uuid.New().String()
online_conn_key := "device_" + strconv.Itoa(deviceId) + "_online_conn_ids" online_conn_key := "device_" + strconv.Itoa(device_id) + "_online_conn_ids"
// 加入设备在线连接集合 // 加入设备在线连接集合
worker.SetRedisSetAddWithExpire(online_conn_key, con_id, time.Minute*5) worker.SetRedisSetAddWithExpire(online_conn_key, con_id, time.Minute*5)
//图片计数器 //图片计数器
count := 0 count := 0
//定时器,发送计数器 //定时器,发送计数器
tCount := 0 tCount := 0
//计算帧率 //从service获取当前帧
var img gocv.Mat
for { for {
//从service获取当前帧 c := service.GetDeviceCurrentFrameV2(&img, device_id)
c := service.DeviceFrameCount[deviceId]
if c != count { if c != count {
count = c //将img转[]byte
buf := service.Device1CurrentFrame if img.Empty() {
err2 := ws.WriteMessage(websocket.BinaryMessage, buf) log.Printf("device:%d img is empty! count=%d", device_id, c)
if err2 != nil { } else {
log.Printf("send message to client err:%v", err2) //gocv.Matrix转为jpeg
worker.SetRedisSetRemove(online_conn_key, con_id) buf, err := gocv.IMEncode(".jpg", img)
break if err != nil {
log.Printf("img encode err:%v", err)
worker.SetRedisSetRemove(online_conn_key, con_id)
break
}
buf1 := buf.GetBytes()
err2 := ws.WriteMessage(websocket.BinaryMessage, buf1)
if err2 != nil {
log.Printf("send message to client err:%v", err2)
worker.SetRedisSetRemove(online_conn_key, con_id)
break
}
c = count
err4 := img.Close()
if err4 != nil {
log.Printf("close img err:%v", err)
}
} }
c = count
} else { } else {
//每秒发送一次心跳检测 //每秒发送一次心跳检测
if tCount%10 == 0 { if tCount%10 == 0 {
@ -217,8 +206,6 @@ func subscribeAndHandleMessagesV6(ws *websocket.Conn, deviceId int) {
log.Printf("Connection check failed:%v", err) log.Printf("Connection check failed:%v", err)
worker.SetRedisSetRemove(online_conn_key, con_id) worker.SetRedisSetRemove(online_conn_key, con_id)
break break
} else {
log.Printf("Connection check success")
} }
} }
} }
@ -226,9 +213,15 @@ func subscribeAndHandleMessagesV6(ws *websocket.Conn, deviceId int) {
tCount++ tCount++
} }
//关闭img
err := img.Close()
if err != nil {
log.Printf("img close err:%v", err)
}
// 查看是否还有其他连接,没有则设置 is_play 为 0 // 查看是否还有其他连接,没有则设置 is_play 为 0
if worker.IsContainKey(online_conn_key) == false { if worker.IsContainKey(online_conn_key) == false {
worker.SetRedisWithExpire(strconv.Itoa(deviceId)+"_is_play", "1", time.Minute*5) worker.SetRedisWithExpire(strconv.Itoa(device_id)+"_is_play", "1", time.Minute*5)
log.Printf("device_id: %d has set is_play to 0", deviceId) log.Printf("device_id: %d has set is_play to 0", device_id)
} }
} }

59
main.go
View File

@ -10,7 +10,6 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
"gocv.io/x/gocv"
"log" "log"
"runtime" "runtime"
"strconv" "strconv"
@ -19,11 +18,10 @@ import (
) )
var configPath string var configPath string
var logCount int
func main() { func main() {
fmt.Println("start server") fmt.Println("start server")
gin.SetMode(gin.ReleaseMode) //设置为debug模式 gin.SetMode(gin.DebugMode) //设置为debug模式
r := gin.Default() r := gin.Default()
//数据库初始 //数据库初始
err0 := dao.Init() err0 := dao.Init()
@ -52,7 +50,6 @@ func main() {
} }
c.Start() c.Start()
fmt.Println("定时任务已启动") fmt.Println("定时任务已启动")
initDeviceGettingStatus()
err3 := r.Run(":" + proto.Config.SERVER_PORT) err3 := r.Run(":" + proto.Config.SERVER_PORT)
if err3 != nil { if err3 != nil {
panic("failed to run server:" + err3.Error()) panic("failed to run server:" + err3.Error())
@ -68,7 +65,6 @@ func init() {
} else { } else {
configPath = "/home/videoplayer/vp_stream.conf" configPath = "/home/videoplayer/vp_stream.conf"
} }
logCount = 0
//读取配置文件 //读取配置文件
err := proto.ReadConfig(configPath) err := proto.ReadConfig(configPath)
if err != nil { if err != nil {
@ -80,7 +76,7 @@ func init() {
//service.DeviceCurrentFrameMap[device.ID] = gocv.NewMat() //service.DeviceCurrentFrameMap[device.ID] = gocv.NewMat()
//service.DeviceIsGettingFrame[device.ID] = false //service.DeviceIsGettingFrame[device.ID] = false
service.DeviceRWMap.Store(device.ID, &sync.RWMutex{}) service.DeviceRWMap.Store(device.ID, &sync.RWMutex{})
service.DeviceCurrentFrameMap.Store(device.ID, gocv.NewMat()) //service.DeviceCurrentFrameMap.Store(device.ID, gocv.NewMat())
service.DeviceFrameCount[device.ID] = 0 service.DeviceFrameCount[device.ID] = 0
service.DeviceIsGettingFrame.Store(device.ID, false) service.DeviceIsGettingFrame.Store(device.ID, false)
} }
@ -90,20 +86,7 @@ func myTask() {
ReadConfigAndSetSystem() ReadConfigAndSetSystem()
} }
func initDeviceGettingStatus() {
for _, device := range proto.Config.DeviceInfo {
if device.NextStop == false {
worker.SetRedis(fmt.Sprintf("device_%d_is_getting", device.ID), "false")
}
if device.NextStop == true {
worker.DelRedis(fmt.Sprintf("device_%d_is_getting", device.ID))
}
}
}
func ReadConfigAndSetSystem() { func ReadConfigAndSetSystem() {
logCount++
//configPath := "/home/videoplayer/vp_stream.conf" //configPath := "/home/videoplayer/vp_stream.conf"
//读取配置文件 //读取配置文件
err := proto.ReadConfig(configPath) err := proto.ReadConfig(configPath)
@ -112,31 +95,20 @@ func ReadConfigAndSetSystem() {
} }
//检测是否需要获取设备流,如果需要则开启 //检测是否需要获取设备流,如果需要则开启
for _, device := range proto.Config.DeviceInfo { for _, device := range proto.Config.DeviceInfo {
//isGet, ok := service.DeviceIsGettingFrame.Load(device.ID) is_get, ok := service.DeviceIsGettingFrame.Load(device.ID)
//isGet_ := isGet.(bool) if !ok {
isGetting := worker.GetRedis(fmt.Sprintf("device_%d_is_getting", device.ID))
if isGetting == "" {
//说明没有这个设备,需初始化添加 //说明没有这个设备,需初始化添加
service.DeviceRWMap.Store(device.ID, &sync.RWMutex{}) service.DeviceRWMap.Store(device.ID, &sync.RWMutex{})
service.DeviceCurrentFrameMap.Store(device.ID, gocv.NewMat()) //service.DeviceCurrentFrameMap.Store(device.ID, gocv.NewMat())
service.DeviceFrameCount[device.ID] = 0 service.DeviceFrameCount[device.ID] = 0
service.DeviceIsGettingFrame.Store(device.ID, false) service.DeviceIsGettingFrame.Store(device.ID, false)
worker.SetRedis(fmt.Sprintf("device_%d_is_getting", device.ID), "false")
} }
if isGetting == "false" && device.NextStop == false { //如果设备流已经停止且不暂停,则开启 if is_get == false && device.NextStop == false { //如果设备流已经停止且不暂停,则开启
switch device.ID {
case 50:
service.Device50CurrentFrame = gocv.NewMat()
case 73:
service.Device73CurrentFrame = gocv.NewMat()
}
go service.GetVideoStream(device.ID) go service.GetVideoStream(device.ID)
log.Printf("device:%d has started!\n", device.ID) log.Printf("device:%d has started!\n", device.ID)
} }
} }
if logCount%3600 == 0 { log.Println("每10秒执行一次,当前设备:", proto.Config.DeviceInfo)
log.Printf("每%d秒执行一次,当前设备:%v", logCount*10, proto.Config.DeviceInfo)
}
} }
func JWTAuthMiddleware() gin.HandlerFunc { func JWTAuthMiddleware() gin.HandlerFunc {
@ -181,16 +153,13 @@ func JWTAuthMiddleware() gin.HandlerFunc {
if worker.IsContainSet("super_permission_tokens", tokenString) { if worker.IsContainSet("super_permission_tokens", tokenString) {
s_id := c.Request.Header.Get("super_id") s_id := c.Request.Header.Get("super_id")
if s_id == "" { if s_id == "" {
s_id = c.Query("super_id") c.AbortWithStatus(200)
if s_id == "" { c.JSON(200, gin.H{
c.AbortWithStatus(200) "message": "NOT_LOGIN",
c.JSON(200, gin.H{ "error": "super_id is empty",
"message": "NOT_LOGIN", "code": 3,
"error": "super_id is empty", })
"code": 3, return
})
return
}
} }
id, _ := strconv.Atoi(s_id) id, _ := strconv.Atoi(s_id)
//查看s_id类型 //查看s_id类型

View File

@ -15,45 +15,15 @@ import (
) )
var DeviceRWMap = &sync.Map{} var DeviceRWMap = &sync.Map{}
var DeviceCurrentFrameMap = &sync.Map{}
// var DeviceCurrentFrameMap = &sync.Map{}
var DeviceFrameCount map[int]int var DeviceFrameCount map[int]int
var DeviceIsGettingFrame = &sync.Map{} var DeviceIsGettingFrame = &sync.Map{}
var Device1CurrentFrame []byte var Device1CurrentFrame gocv.Mat
var Device50CurrentFrame gocv.Mat var Device50CurrentFrame gocv.Mat
var Device73CurrentFrame gocv.Mat var Device73CurrentFrame gocv.Mat
func SetDeviceCurrentFrame(frame gocv.Mat, deviceId int) error { func SetDeviceCurrentFrame(frame *gocv.Mat, deviceId int) error {
//获取读写锁
mutex_, ok := DeviceRWMap.Load(deviceId)
if !ok {
return fmt.Errorf("设备:%s 读写锁不存在", deviceId)
}
mutex := mutex_.(*sync.RWMutex)
mutex.Lock()
defer mutex.Unlock()
//获取前一帧,将前一帧释放
framePrev, ok := DeviceCurrentFrameMap.Load(deviceId)
if ok {
frame_, ok2 := framePrev.(gocv.Mat)
if ok2 {
err2 := frame_.Close()
if err2 != nil {
log.Printf("设备:%d, 错误: 无法关闭帧\n", deviceId)
}
}
}
//设置当前帧
DeviceCurrentFrameMap.Store(deviceId, frame)
frameCount, ok := DeviceFrameCount[deviceId]
if !ok {
return fmt.Errorf("设备:%s 当前帧计数不存在", deviceId)
}
frameCount++
DeviceFrameCount[deviceId] = frameCount
return nil
}
func SetDeviceCurrentFrameV2(frame *gocv.Mat, deviceId int) error {
//获取读写锁 //获取读写锁
mutex_, ok := DeviceRWMap.Load(deviceId) mutex_, ok := DeviceRWMap.Load(deviceId)
if !ok { if !ok {
@ -65,7 +35,10 @@ func SetDeviceCurrentFrameV2(frame *gocv.Mat, deviceId int) error {
//设置当前帧 //设置当前帧
switch deviceId { switch deviceId {
case 1: case 1:
Device1CurrentFrame = (*frame).ToBytes() if Device1CurrentFrame.Empty() {
Device1CurrentFrame = gocv.NewMatWithSize((*frame).Rows(), (*frame).Cols(), (*frame).Type())
}
(*frame).CopyTo(&Device1CurrentFrame)
case 50: case 50:
if Device50CurrentFrame.Empty() { if Device50CurrentFrame.Empty() {
Device50CurrentFrame = gocv.NewMatWithSize((*frame).Rows(), (*frame).Cols(), (*frame).Type()) Device50CurrentFrame = gocv.NewMatWithSize((*frame).Rows(), (*frame).Cols(), (*frame).Type())
@ -76,20 +49,113 @@ func SetDeviceCurrentFrameV2(frame *gocv.Mat, deviceId int) error {
Device73CurrentFrame = gocv.NewMatWithSize((*frame).Rows(), (*frame).Cols(), (*frame).Type()) Device73CurrentFrame = gocv.NewMatWithSize((*frame).Rows(), (*frame).Cols(), (*frame).Type())
} }
(*frame).CopyTo(&Device73CurrentFrame) (*frame).CopyTo(&Device73CurrentFrame)
} }
frameCount, ok := DeviceFrameCount[deviceId] frameCount, ok := DeviceFrameCount[deviceId]
if !ok { if !ok {
return fmt.Errorf("设备:%s 当前帧计数不存在", deviceId) return fmt.Errorf("设备:%s 当前帧计数不存在", deviceId)
} }
if frameCount%10 == 0 {
log.Printf("设备:%d 当前帧: %d 已更新\n", deviceId, frameCount)
}
frameCount++ frameCount++
DeviceFrameCount[deviceId] = frameCount DeviceFrameCount[deviceId] = frameCount
return nil return nil
} }
func GetDeviceCurrentFrameV2(frame *gocv.Mat, deviceId int) int {
defer func() {
if err := recover(); err != nil {
log.Printf("设备:%d 错误: %v\n", deviceId, err)
}
}()
//获取读写锁
mutex_, ok := DeviceRWMap.Load(deviceId)
if !ok {
log.Printf("DeviceRWMap 读写锁不存在device_id: %d \n", deviceId)
return -1
}
mutex, ok := mutex_.(*sync.RWMutex)
if !ok {
log.Printf("DeviceRWMap 存储的不是 *sync.RWMutex 类型device_id: %d \n", deviceId)
return -1
}
mutex.RLock()
defer mutex.RUnlock()
//获取当前帧
switch deviceId {
case 1:
if frame.Empty() {
*frame = gocv.NewMatWithSize(Device1CurrentFrame.Rows(), Device1CurrentFrame.Cols(), Device1CurrentFrame.Type())
}
Device1CurrentFrame.CopyTo(frame)
case 50:
if frame.Empty() {
*frame = gocv.NewMatWithSize(Device50CurrentFrame.Rows(), Device50CurrentFrame.Cols(), Device50CurrentFrame.Type())
}
Device50CurrentFrame.CopyTo(frame)
case 73:
if frame.Empty() {
*frame = gocv.NewMatWithSize(Device73CurrentFrame.Rows(), Device73CurrentFrame.Cols(), Device73CurrentFrame.Type())
}
Device73CurrentFrame.CopyTo(frame)
}
frameCount, ok := DeviceFrameCount[deviceId]
if !ok {
return -1
}
return frameCount
}
func GetDeviceCurrentFrame(deviceId int) (gocv.Mat, int) {
defer func() {
if err := recover(); err != nil {
log.Printf("设备:%d 错误: %v\n", deviceId, err)
}
}()
//获取读写锁
mutex_, ok := DeviceRWMap.Load(deviceId)
if !ok {
log.Printf("DeviceRWMap 读写锁不存在device_id: %d \n", deviceId)
return gocv.NewMat(), -1
}
mutex, ok := mutex_.(*sync.RWMutex)
if !ok {
log.Printf("DeviceRWMap 存储的不是 *sync.RWMutex 类型device_id: %d \n", deviceId)
return gocv.NewMat(), -1
}
mutex.RLock()
defer mutex.RUnlock()
var ret gocv.Mat
if ret.Empty() {
}
//获取当前帧
switch deviceId {
case 1:
if ret.Empty() {
ret = gocv.NewMatWithSize(Device1CurrentFrame.Rows(), Device1CurrentFrame.Cols(), Device1CurrentFrame.Type())
}
Device1CurrentFrame.CopyTo(&ret)
case 50:
if ret.Empty() {
ret = gocv.NewMatWithSize(Device50CurrentFrame.Rows(), Device50CurrentFrame.Cols(), Device50CurrentFrame.Type())
}
Device50CurrentFrame.CopyTo(&ret)
case 73:
if ret.Empty() {
ret = gocv.NewMatWithSize(Device73CurrentFrame.Rows(), Device73CurrentFrame.Cols(), Device73CurrentFrame.Type())
}
Device73CurrentFrame.CopyTo(&ret)
}
frameCount, ok := DeviceFrameCount[deviceId]
if !ok {
log.Printf("设备:%d 当前帧计数不存在\n", deviceId)
frameCount = -1
}
return ret, frameCount
}
func getVideoFrame(device proto.DeviceInfo) { func getVideoFrame(device proto.DeviceInfo) {
//捕获异常 //捕获异常
defer func() { defer func() {
@ -116,6 +182,7 @@ func getVideoFrame(device proto.DeviceInfo) {
lineType := 2 lineType := 2
z := 0 z := 0
var frame gocv.Mat var frame gocv.Mat
frame = gocv.NewMat()
for { for {
if device.LogFrame > 0 && z%device.LogFrame == 0 { if device.LogFrame > 0 && z%device.LogFrame == 0 {
log.Printf("设备:%d 当前帧: %d\n", device.ID, z) log.Printf("设备:%d 当前帧: %d\n", device.ID, z)
@ -123,7 +190,6 @@ func getVideoFrame(device proto.DeviceInfo) {
if device.NextStop { if device.NextStop {
break break
} }
frame = gocv.NewMat()
ok := webcam.Read(&frame) ok := webcam.Read(&frame)
if !ok { if !ok {
log.Printf("设备:%v 错误: 无法从视频流中读取帧\n", device) log.Printf("设备:%v 错误: 无法从视频流中读取帧\n", device)
@ -142,23 +208,17 @@ func getVideoFrame(device proto.DeviceInfo) {
break break
} }
currentTime := time.Now().Format("2006-01-02 15:04:05") currentTime := time.Now().Format("2006-01-02 15:04:05")
gocv.PutText(&frame, currentTime, image.Point{10, 20}, font, fontScale, fontColor, lineType) gocv.PutText(&frame, currentTime, image.Point{X: 10, Y: 20}, font, fontScale, fontColor, lineType)
//需要将帧付给全局变量 //需要将帧付给全局变量
err3 := SetDeviceCurrentFrameV2(&frame, device.ID) err3 := SetDeviceCurrentFrame(&frame, device.ID)
if err3 != nil { if err3 != nil {
log.Printf("设备:%d 错误: 无法设置当前帧,err:%s \n", device.ID, err3.Error()) log.Printf("设备:%d 错误: 无法设置当前帧,err:%s \n", device.ID, err3.Error())
} }
z++ z++
//关闭帧
err4 := frame.Close()
if err4 != nil {
log.Printf("设备:%d 错误: 无法关闭帧,err:%s \n", device.ID, err4.Error())
}
} }
//关闭帧 err2 := frame.Close()
err4 := frame.Close() if err2 != nil {
if err4 != nil { log.Printf("设备:%d 错误: 无法释放帧资源,err:%s \n", device.ID, err.Error())
log.Printf("设备:%d 错误: 无法关闭帧,err:%s \n", device.ID, err4.Error())
} }
} }
@ -182,9 +242,13 @@ func GetVideoStream(id int) {
log.Printf("设备:%d 错误: %v\n", id, err) log.Printf("设备:%d 错误: %v\n", id, err)
} }
}() }()
isGetting := worker.GetRedis(fmt.Sprintf("device_%d_is_getting", id)) is_get, ok := DeviceIsGettingFrame.Load(id)
if isGetting == "true" || isGetting == "" { if !ok {
log.Printf("设备:%d 正在运行,isGetting:%s", id, isGetting) log.Printf("device: %d not found", id)
return
}
if is_get == true {
log.Printf("device: %d is running!", id)
return return
} }
for { for {
@ -203,9 +267,9 @@ func GetVideoStream(id int) {
log.Printf("device: %d not found", id) log.Printf("device: %d not found", id)
break break
} }
isGetting = worker.GetRedis(fmt.Sprintf("device_%d_is_getting", id)) is_get, ok = DeviceIsGettingFrame.Load(id)
if isGetting == "true" { if is_get == true {
log.Printf("设备:%d 正在运行,isGetting:%s", id, isGetting) log.Printf("for device:%d is running!", id)
break break
} }
@ -216,11 +280,9 @@ func GetVideoStream(id int) {
//设置设备控制信息 //设置设备控制信息
status := Get(device.Control) status := Get(device.Control)
DeviceIsGettingFrame.Store(id, true) DeviceIsGettingFrame.Store(id, true)
worker.SetRedis(fmt.Sprintf("device_%d_is_getting", id), "true")
log.Printf("device: %d set control info status: %d", device.ID, status) log.Printf("device: %d set control info status: %d", device.ID, status)
getVideoFrame(device) getVideoFrame(device)
DeviceIsGettingFrame.Store(id, false) DeviceIsGettingFrame.Store(id, false)
worker.SetRedis(fmt.Sprintf("device_%d_is_getting", id), "false")
//等待1s //等待1s
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
} }