日志输出,空指针导致程序出错

This commit is contained in:
lijun 2025-01-15 23:31:50 +08:00
parent 00a04ff287
commit 7c8b0843a0
4 changed files with 37 additions and 24 deletions

View File

@ -10,6 +10,7 @@ import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"gocv.io/x/gocv" "gocv.io/x/gocv"
"io" "io"
"log"
"net/http" "net/http"
"strconv" "strconv"
"time" "time"
@ -143,11 +144,11 @@ func GetRealTimeImage(c *gin.Context) {
} }
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil) ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil { if err != nil {
fmt.Println("connect wss err:", err) log.Fatalf("connect wss err:", 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)
fmt.Println("device_id:", device_id_int, " has set is_play to 1") log.Fatalf("device_id:", device_id_int, " has set is_play to 1")
go subscribeAndHandleMessagesV3(ws, device_id_int) go subscribeAndHandleMessagesV3(ws, device_id_int)
} }
@ -167,12 +168,12 @@ func subscribeAndHandleMessagesV3(ws *websocket.Conn, device_id int) {
if c != count { if c != count {
//将img转[]byte //将img转[]byte
if img.Empty() { if img.Empty() {
fmt.Println("device:%d img is empty!", device_id) log.Fatalf("device:%d img is empty!", device_id)
} else { } else {
//gocv.Matrix转为jpeg //gocv.Matrix转为jpeg
buf, err := gocv.IMEncode(".jpg", img) buf, err := gocv.IMEncode(".jpg", img)
if err != nil { if err != nil {
fmt.Println("img encode err:", err) log.Fatalf("img encode err:", err)
worker.SetRedisSetRemove(online_conn_key, con_id) worker.SetRedisSetRemove(online_conn_key, con_id)
goto end goto end
} }
@ -180,7 +181,7 @@ func subscribeAndHandleMessagesV3(ws *websocket.Conn, device_id int) {
err2 := ws.WriteMessage(websocket.BinaryMessage, buf1) err2 := ws.WriteMessage(websocket.BinaryMessage, buf1)
if err2 != nil { if err2 != nil {
fmt.Println("send message to client err:", err2) log.Fatalf("send message to client err:", err2)
worker.SetRedisSetRemove(online_conn_key, con_id) worker.SetRedisSetRemove(online_conn_key, con_id)
goto end goto end
} }
@ -191,7 +192,7 @@ func subscribeAndHandleMessagesV3(ws *websocket.Conn, device_id int) {
if t_count%10 == 0 { if t_count%10 == 0 {
err := ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(time.Second)) err := ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(time.Second))
if err != nil { if err != nil {
fmt.Println("Connection check failed:", err) log.Fatalf("Connection check failed:", err)
worker.SetRedisSetRemove(online_conn_key, con_id) worker.SetRedisSetRemove(online_conn_key, con_id)
goto end goto end
} }
@ -201,7 +202,7 @@ func subscribeAndHandleMessagesV3(ws *websocket.Conn, device_id int) {
t_count++ t_count++
err := img.Close() err := img.Close()
if err != nil { if err != nil {
fmt.Println("close img err:", err) log.Fatalf("close img err:", err)
} }
} }
@ -209,6 +210,6 @@ end:
// 查看是否还有其他连接,没有则设置 is_play 为 0 // 查看是否还有其他连接,没有则设置 is_play 为 0
if worker.IsContainKey(online_conn_key) == false { if worker.IsContainKey(online_conn_key) == false {
worker.SetRedisWithExpire(strconv.Itoa(device_id)+"_is_play", "1", time.Minute*5) 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.Fatalf("device_id:", device_id, " has set is_play to 0")
} }
} }

View File

@ -6,7 +6,6 @@ import (
"VideoStream/proto" "VideoStream/proto"
"VideoStream/service" "VideoStream/service"
"VideoStream/worker" "VideoStream/worker"
"fmt"
"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"
@ -97,7 +96,7 @@ func ReadConfigAndSetSystem() {
} }
if is_get == false && device.NextStop == false { //如果设备流已经停止且不暂停,则开启 if is_get == false && device.NextStop == false { //如果设备流已经停止且不暂停,则开启
go service.GetVideoStream(device.ID) go service.GetVideoStream(device.ID)
fmt.Println("device:", device.ID, " has started!") log.Fatalf("device:%d has started!\n", device.ID)
} }
} }
} }

View File

@ -3,6 +3,7 @@ package proto
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"os" "os"
) )
@ -42,18 +43,18 @@ func ReadConfig(path string) error {
//查看配置文件是否存在,不存在则创建 //查看配置文件是否存在,不存在则创建
_, err := os.Stat(path) _, err := os.Stat(path)
if err != nil { if err != nil {
fmt.Println("Config file not found!") log.Fatalf("Config file not found!")
//写入json文件 //写入json文件
file, err := os.Create(path) file, err := os.Create(path)
if err != nil { if err != nil {
fmt.Println("Error creating config file") log.Fatalf("Error creating config file")
return err return err
} }
defer file.Close() defer file.Close()
encoder := json.NewEncoder(file) encoder := json.NewEncoder(file)
err = encoder.Encode(&Config) err = encoder.Encode(&Config)
if err != nil { if err != nil {
fmt.Println("Error encoding config") log.Fatalf("Error encoding config")
} }
return err return err
} }
@ -61,14 +62,14 @@ func ReadConfig(path string) error {
//读json文件 //读json文件
file, err := os.Open(path) file, err := os.Open(path)
if err != nil { if err != nil {
fmt.Println("Error opening config file") log.Fatalf("Error opening config file")
return err return err
} }
defer file.Close() defer file.Close()
decoder := json.NewDecoder(file) decoder := json.NewDecoder(file)
err = decoder.Decode(&Config) err = decoder.Decode(&Config)
if err != nil { if err != nil {
fmt.Println("Error decoding config:", err) log.Fatalf("Error decoding config:", err)
return err return err
} else { } else {
if Config.SERVER_PORT == "" { if Config.SERVER_PORT == "" {
@ -78,7 +79,7 @@ func ReadConfig(path string) error {
//将配置写入redis //将配置写入redis
jsonData, err2 := json.Marshal(Config) jsonData, err2 := json.Marshal(Config)
if err2 != nil { if err2 != nil {
fmt.Println("ReadConfigToSetSystem Error encoding config,err :", err2) log.Fatalf("ReadConfigToSetSystem Error encoding config,err :", err2)
} }
SigningKey = []byte(Config.TOKEN_SECRET) SigningKey = []byte(Config.TOKEN_SECRET)
if Config.TOKEN_SECRET == "" { if Config.TOKEN_SECRET == "" {

View File

@ -73,12 +73,24 @@ func GetDeviceCurrentFrame(device_id int) (gocv.Mat, int) {
} }
func getVideoFrame(device proto.DeviceInfo) { func getVideoFrame(device proto.DeviceInfo) {
//捕获异常
defer func() {
if err := recover(); err != nil {
log.Fatalf("设备:%d 错误: %v\n", device.ID, err)
}
}()
webcam, err := gocv.OpenVideoCapture(device.Stream) webcam, err := gocv.OpenVideoCapture(device.Stream)
if err != nil { if err != nil {
fmt.Printf("设备:%s 错误: 无法打开视频流err: %v\n", device.ID, err) log.Fatalf("设备:%s 错误: 无法打开视频流err: %v\n", device.ID, err)
return return
} }
defer webcam.Close() defer func(webcam *gocv.VideoCapture) {
err2 := webcam.Close()
if err2 != nil {
log.Fatalf("设备:%d 错误: 无法关闭视频流,%s \n", device.ID, err2.Error())
}
}(webcam)
// 字体相关设置对应OpenCV默认字体等这里简化处理实际可按需求调整 // 字体相关设置对应OpenCV默认字体等这里简化处理实际可按需求调整
font := gocv.FontHersheySimplex font := gocv.FontHersheySimplex
fontScale := 0.5 fontScale := 0.5
@ -87,7 +99,7 @@ func getVideoFrame(device proto.DeviceInfo) {
z := 0 z := 0
for { for {
if device.LogFrame > 0 && z%device.LogFrame == 0 { if device.LogFrame > 0 && z%device.LogFrame == 0 {
fmt.Printf("设备:%d 当前帧: %d\n", device.ID, z) log.Fatalf("设备:%d 当前帧: %d\n", device.ID, z)
} }
if device.NextStop { if device.NextStop {
break break
@ -95,11 +107,11 @@ func getVideoFrame(device proto.DeviceInfo) {
frame := gocv.NewMat() frame := gocv.NewMat()
ok := webcam.Read(&frame) ok := webcam.Read(&frame)
if !ok { if !ok {
fmt.Printf("设备 错误: 无法从视频流中读取帧:", device, "\n") log.Fatalf("设备 错误: 无法从视频流中读取帧:", device, "\n")
break break
} }
if frame.Empty() { if frame.Empty() {
fmt.Printf("设备:%s 错误: 无法从视频流中读取帧\n", device) log.Fatalf("设备:%s 错误: 无法从视频流中读取帧\n", device)
//等待50ms //等待50ms
time.Sleep(50 * time.Millisecond) time.Sleep(50 * time.Millisecond)
continue continue
@ -107,7 +119,7 @@ func getVideoFrame(device proto.DeviceInfo) {
height := frame.Rows() height := frame.Rows()
width := frame.Cols() width := frame.Cols()
if height < device.CheckFrameHeight || width < device.CheckFrameWidth { if height < device.CheckFrameHeight || width < device.CheckFrameWidth {
fmt.Printf("设备:%s 帧尺寸已改变\n", device) log.Fatalf("设备:%s 帧尺寸已改变\n", device)
break break
} }
currentTime := time.Now().Format("2006-01-02 15:04:05") currentTime := time.Now().Format("2006-01-02 15:04:05")
@ -115,12 +127,12 @@ func getVideoFrame(device proto.DeviceInfo) {
//需要将帧付给全局变量 //需要将帧付给全局变量
err3 := SetDeviceCurrentFrame(frame, device.ID) err3 := SetDeviceCurrentFrame(frame, device.ID)
if err3 != nil { if err3 != nil {
fmt.Printf("设备:%d 错误: 无法设置当前帧,err:%s \n", device.ID, err3.Error()) log.Fatalf("设备:%d 错误: 无法设置当前帧,err:%s \n", device.ID, err3.Error())
} }
z++ z++
err2 := frame.Close() err2 := frame.Close()
if err2 != nil { if err2 != nil {
fmt.Println("设备:%d,计数z=%d, 错误: 无法关闭帧", device.ID, z) log.Fatalf("设备:%d,计数z=%d, 错误: 无法关闭帧\n", device.ID, z)
} }
} }
} }