Compare commits

...

13 Commits

6 changed files with 186 additions and 75 deletions

2
go.sum
View File

@ -108,6 +108,8 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
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.40.0 h1:kGBu/UVj+dO6A9dhQmGOnCICSL7ke7b5YtX3R3azdXI=
gocv.io/x/gocv v0.40.0/go.mod h1:zYdWMj29WAEznM3Y8NsU3A0TRq/wR/cy75jeUypThqU=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=

View File

@ -10,6 +10,7 @@ import (
"github.com/gorilla/websocket"
"gocv.io/x/gocv"
"io"
"log"
"net/http"
"strconv"
"time"
@ -143,11 +144,11 @@ func GetRealTimeImage(c *gin.Context) {
}
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
fmt.Println("connect wss err:", err)
log.Printf("connect wss err:%v", err)
return
}
worker.SetRedisWithExpire(strconv.Itoa(int(device.ID))+"_is_play", "1", time.Minute*5)
fmt.Println("device_id:", device_id_int, " has set is_play to 1")
log.Printf("device_id:%d has set is_play to 1", device_id_int)
go subscribeAndHandleMessagesV3(ws, device_id_int)
}
@ -163,25 +164,40 @@ func subscribeAndHandleMessagesV3(ws *websocket.Conn, device_id int) {
t_count := 0
for {
//从service获取当前帧
img, c := service.GetDeviceCurrentFrame(device_id)
var img gocv.Mat
c := service.GetDeviceCurrentFrameV2(&img, device_id)
if c != count {
//将img转[]byte
buf, _ := gocv.IMEncode(".jpg", img)
if img.Empty() {
log.Printf("device:%d img is empty!", device_id)
} else {
//gocv.Matrix转为jpeg
buf, err := gocv.IMEncode(".jpg", img)
if err != nil {
log.Printf("img encode err:%v", err)
worker.SetRedisSetRemove(online_conn_key, con_id)
goto end
}
buf1 := buf.GetBytes()
err2 := ws.WriteMessage(websocket.BinaryMessage, buf1)
if err2 != nil {
fmt.Println("send message to client err:", err2)
log.Printf("send message to client err:%v", err2)
worker.SetRedisSetRemove(online_conn_key, con_id)
goto end
}
c = count
err4 := img.Close()
if err4 != nil {
log.Printf("close img err:%v", err)
}
}
} else {
//每秒发送一次心跳检测
if t_count%10 == 0 {
err := ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(time.Second))
if err != nil {
fmt.Println("Connection check failed:", err)
log.Printf("Connection check failed:%v", err)
worker.SetRedisSetRemove(online_conn_key, con_id)
goto end
}
@ -195,6 +211,6 @@ end:
// 查看是否还有其他连接,没有则设置 is_play 为 0
if worker.IsContainKey(online_conn_key) == false {
worker.SetRedisWithExpire(strconv.Itoa(device_id)+"_is_play", "1", time.Minute*5)
fmt.Println("device_id:", device_id, " has set is_play to 0")
log.Printf("device_id: %d has set is_play to 0", device_id)
}
}

19
main.go
View File

@ -12,12 +12,16 @@ import (
"github.com/robfig/cron/v3"
"gocv.io/x/gocv"
"log"
"runtime"
"strconv"
"strings"
"sync"
)
var configPath string
func main() {
fmt.Println("start server")
gin.SetMode(gin.DebugMode) //设置为debug模式
r := gin.Default()
//数据库初始
@ -46,7 +50,7 @@ func main() {
log.Fatal("添加定时任务失败: ", err2)
}
c.Start()
fmt.Println("定时任务已启动")
err3 := r.Run(":" + proto.Config.SERVER_PORT)
if err3 != nil {
panic("failed to run server:" + err3.Error())
@ -56,7 +60,12 @@ func main() {
func init() {
//读取配置文件
//文件地址/home/videoplayer/vp.conf
configPath := "/home/videoplayer/vp_stream.conf"
os := runtime.GOOS
if os == "windows" {
configPath = "D:/File/vp_stream.conf"
} else {
configPath = "/home/videoplayer/vp_stream.conf"
}
//读取配置文件
err := proto.ReadConfig(configPath)
if err != nil {
@ -74,12 +83,11 @@ func init() {
}
func myTask() {
log.Println("每10秒执行一次")
ReadConfigAndSetSystem()
}
func ReadConfigAndSetSystem() {
configPath := "/home/videoplayer/vp_stream.conf"
//configPath := "/home/videoplayer/vp_stream.conf"
//读取配置文件
err := proto.ReadConfig(configPath)
if err != nil {
@ -97,9 +105,10 @@ func ReadConfigAndSetSystem() {
}
if is_get == false && device.NextStop == false { //如果设备流已经停止且不暂停,则开启
go service.GetVideoStream(device.ID)
fmt.Println("device:", device.ID, " has started!")
log.Printf("device:%d has started!\n", device.ID)
}
}
log.Println("每10秒执行一次,当前设备:", proto.Config.DeviceInfo)
}
func JWTAuthMiddleware() gin.HandlerFunc {

View File

@ -3,6 +3,8 @@ package proto
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
)
@ -39,50 +41,40 @@ type DeviceInfo struct {
// 读取配置文件
func ReadConfig(path string) error {
//查看配置文件是否存在,不存在则创建
_, err := os.Stat(path)
// 查看配置文件是否存在,不存在则创建
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
fmt.Println("Config file not found!")
//写入json文件
file, err := os.Create(path)
if err != nil {
fmt.Println("Error creating config file")
log.Printf("Error opening or creating config file: %v", err)
return err
}
defer file.Close()
defer func() {
if err := file.Close(); err != nil {
log.Printf("Error closing config file: %v\n", err)
}
}()
// 尝试读取文件内容
decoder := json.NewDecoder(file)
if err := decoder.Decode(&Config); err != nil && err != io.EOF {
log.Printf("Error decoding config: %v \n", err)
// 如果文件为空或解码错误,写入默认配置
Config.SERVER_PORT = "5002"
encoder := json.NewEncoder(file)
err = encoder.Encode(&Config)
if err != nil {
fmt.Println("Error encoding config")
}
if err := encoder.Encode(&Config); err != nil {
log.Printf("Error encoding config: %v", err)
return err
}
}
//读json文件
file, err := os.Open(path)
if err != nil {
fmt.Println("Error opening config file")
return err
}
defer file.Close()
decoder := json.NewDecoder(file)
err = decoder.Decode(&Config)
if err != nil {
fmt.Println("Error decoding config:", err)
return err
} else {
if Config.SERVER_PORT == "" {
Config.SERVER_PORT = "5002" // 默认端口
}
}
// 将配置写入 redis
jsonData, err2 := json.Marshal(Config)
if err2 != nil {
fmt.Println("ReadConfigToSetSystem Error encoding config,err :", err2)
jsonData, err := json.Marshal(Config)
if err != nil {
log.Printf("ReadConfigToSetSystem Error encoding config,err :%v\n", err)
return err
}
SigningKey = []byte(Config.TOKEN_SECRET)
if Config.TOKEN_SECRET == "" {
err = fmt.Errorf("token secret is empty: %s", string(jsonData))
return fmt.Errorf("token secret is empty: %s", string(jsonData))
}
return err
return nil
}

View File

@ -28,6 +28,17 @@ func SetDeviceCurrentFrame(frame gocv.Mat, device_id int) error {
mutex := mutex_.(*sync.RWMutex)
mutex.Lock()
defer mutex.Unlock()
//获取前一帧,将前一帧释放
framePrev, ok := DeviceCurrentFrameMap.Load(device_id)
if ok {
frame_, ok2 := framePrev.(gocv.Mat)
if ok2 {
err2 := frame_.Close()
if err2 != nil {
log.Printf("设备:%d, 错误: 无法关闭帧\n", device_id)
}
}
}
//设置当前帧
DeviceCurrentFrameMap.Store(device_id, frame)
frame_count, ok := DeviceFrameCount.Load(device_id)
@ -40,28 +51,106 @@ func SetDeviceCurrentFrame(frame gocv.Mat, device_id int) error {
return nil
}
func GetDeviceCurrentFrame(device_id int) (gocv.Mat, int) {
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(device_id)
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()
var frame_ gocv.Mat
//获取当前帧
frameIface, ok := DeviceCurrentFrameMap.Load(deviceId)
if !ok {
return -1
}
frame_, ok = frameIface.(gocv.Mat)
if !ok {
log.Printf("DeviceCurrentFrameMap 存储的不是 gocv.Mat 类型device_id: %d \n", deviceId)
}
*frame = frame_
frame_countIface, ok := DeviceFrameCount.Load(deviceId)
if !ok {
return -1
}
frame_count, ok := frame_countIface.(int)
if !ok {
log.Printf("DeviceFrameCount 存储的不是 int 类型device_id: %d", deviceId)
}
return frame_count
}
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 := mutex_.(*sync.RWMutex)
mutex.RLock()
defer mutex.RUnlock()
//获取当前帧
frame, ok := DeviceCurrentFrameMap.Load(device_id)
frame_count, ok := DeviceFrameCount.Load(device_id)
return frame.(gocv.Mat), frame_count.(int)
frameIface, ok := DeviceCurrentFrameMap.Load(deviceId)
if !ok {
return gocv.NewMat(), -1
}
frame, ok := frameIface.(gocv.Mat)
if !ok {
log.Printf("DeviceCurrentFrameMap 存储的不是 gocv.Mat 类型device_id: %d \n", deviceId)
}
frame_countIface, ok := DeviceFrameCount.Load(deviceId)
if !ok {
return gocv.NewMat(), -1
}
frame_count, ok := frame_countIface.(int)
if !ok {
log.Printf("DeviceFrameCount 存储的不是 int 类型device_id: %d", deviceId)
}
return frame, frame_count
}
func getVideoFrame(device proto.DeviceInfo) {
//捕获异常
defer func() {
if err := recover(); err != nil {
log.Printf("设备:%d 错误: %v\n", device.ID, err)
}
}()
webcam, err := gocv.OpenVideoCapture(device.Stream)
if err != nil {
fmt.Printf("设备:%s 错误: 无法打开视频流err: %v\n", device.ID, err)
log.Printf("设备:%d 错误: 无法打开视频流err: %v\n", device.ID, err)
return
}
defer webcam.Close()
defer func(webcam *gocv.VideoCapture) {
err2 := webcam.Close()
if err2 != nil {
log.Printf("设备:%d 错误: 无法关闭视频流,%s \n", device.ID, err2.Error())
}
}(webcam)
// 字体相关设置对应OpenCV默认字体等这里简化处理实际可按需求调整
font := gocv.FontHersheySimplex
fontScale := 0.5
@ -70,7 +159,7 @@ func getVideoFrame(device proto.DeviceInfo) {
z := 0
for {
if device.LogFrame > 0 && z%device.LogFrame == 0 {
fmt.Printf("设备:%d 当前帧: %d\n", device.ID, z)
log.Printf("设备:%d 当前帧: %d\n", device.ID, z)
}
if device.NextStop {
break
@ -78,11 +167,11 @@ func getVideoFrame(device proto.DeviceInfo) {
frame := gocv.NewMat()
ok := webcam.Read(&frame)
if !ok {
fmt.Printf("设备 错误: 无法从视频流中读取帧:", device, "\n")
log.Printf("设备:%v 错误: 无法从视频流中读取帧\n", device)
break
}
if frame.Empty() {
fmt.Printf("设备:%s 错误: 无法从视频流中读取帧\n", device)
log.Printf("设备:%s 错误: 无法从视频流中读取帧\n", device)
//等待50ms
time.Sleep(50 * time.Millisecond)
continue
@ -90,7 +179,7 @@ func getVideoFrame(device proto.DeviceInfo) {
height := frame.Rows()
width := frame.Cols()
if height < device.CheckFrameHeight || width < device.CheckFrameWidth {
fmt.Printf("设备:%s 帧尺寸已改变\n", device)
log.Printf("设备:%s 帧尺寸已改变\n", device)
break
}
currentTime := time.Now().Format("2006-01-02 15:04:05")
@ -98,13 +187,9 @@ func getVideoFrame(device proto.DeviceInfo) {
//需要将帧付给全局变量
err3 := SetDeviceCurrentFrame(frame, device.ID)
if err3 != nil {
fmt.Printf("设备:%d 错误: 无法设置当前帧,err:%s \n", device.ID, err3.Error())
log.Printf("设备:%d 错误: 无法设置当前帧,err:%s \n", device.ID, err3.Error())
}
z++
err2 := frame.Close()
if err2 != nil {
fmt.Println("设备:%d,计数z=%d, 错误: 无法关闭帧", device.ID, z)
}
}
}
@ -123,13 +208,18 @@ func Get(url string) int {
}
func GetVideoStream(id int) {
defer func() {
if err := recover(); err != nil {
log.Printf("设备:%d 错误: %v\n", id, err)
}
}()
is_get, ok := DeviceIsGettingFrame.Load(id)
if !ok {
fmt.Println("device:", id, " not found")
log.Printf("device: %d not found", id)
return
}
if is_get == true {
fmt.Println("device:", id, " is running!")
log.Printf("device: %d is running!", id)
return
}
for {
@ -145,12 +235,12 @@ func GetVideoStream(id int) {
}
if index == len(proto.Config.DeviceInfo) {
//设备不存在
log.Println("device:", id, " not found")
log.Printf("device: %d not found", id)
break
}
is_get, ok = DeviceIsGettingFrame.Load(id)
if is_get == true {
log.Println("for device:", id, " is running!")
log.Printf("for device:%d is running!", id)
break
}
@ -161,7 +251,7 @@ func GetVideoStream(id int) {
//设置设备控制信息
status := Get(device.Control)
DeviceIsGettingFrame.Store(id, true)
log.Println("device:", device.ID, " set control info status:", status)
log.Printf("device: %d set control info status: %d", device.ID, status)
getVideoFrame(device)
DeviceIsGettingFrame.Store(id, false)
//等待1s

View File

@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"github.com/go-redis/redis/v8"
"log"
"strconv"
"time"
)
@ -42,6 +43,7 @@ func CloseRedis() {
if err := RedisClient.Close(); err != nil {
fmt.Println("Error closing Redis client: %v", err)
}
log.Printf("Redis has closed")
}
func IsContainKey(key string) bool {