Files
zmkgC/api/video_hat/ws_connect.go
2025-07-07 20:11:59 +08:00

90 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package video_hat
import (
"encoding/json"
"github.com/gorilla/websocket"
"github.com/tiger1103/gfast/v3/api/constant"
"github.com/tiger1103/gfast/v3/api/video_hat/ws2"
"log"
"time"
)
// 项目启动就登录视频安全帽的 WS
func WsConnection() {
// 首先加载 WS 路径映射
InitWsMap()
// 无限循环尝试连接,直到成功
for {
if connectWs() {
break // 如果连接成功,则退出循环
}
log.Println("Reconnecting in 5 seconds...")
time.Sleep(5 * time.Second) // 等待5秒后重新连接WS
}
}
func connectWs() bool {
// 创建 WebSocket 连接
dialer := websocket.Dialer{
HandshakeTimeout: 10 * time.Second,
}
// 尝试连接 WebSocket
var err error
constant.Conn, _, err = dialer.Dial(constant.Url, nil)
if err != nil {
log.Println("Dial:", err)
return false
}
defer constant.Conn.Close()
// 连接成功之后发送登录信息
ws2.Login(constant.Conn)
// 设置定时任务每间隔60秒发送参数获取实时、状态等心跳包
go ws2.SendHeartbeatTime(constant.Conn)
// 处理从 WebSocket 接收的消息
if handlerFun(constant.Conn) {
return true
}
return false
}
func handlerFun(Conn *websocket.Conn) bool {
// 读取 Conn 的数据成 JSON 字符串
for {
_, message, err := Conn.ReadMessage()
if err != nil {
log.Println("ReadMessage:", err)
return false // 如果读取过程中出现错误,则返回 false
}
// 创建一个 map 来存储解析后的 JSON
var msgMap map[string]interface{}
// 将读取到的字节切片解析为 JSON
err = json.Unmarshal(message, &msgMap)
if err != nil {
log.Println("Unmarshal:", err)
continue // 如果解析失败,则跳过此次循环
}
if cmd, ok := msgMap["cmd"].(string); ok {
if handler, exists := commandHandlers[cmd]; exists {
jsonString, err := json.Marshal(msgMap)
if err != nil {
log.Println("Marshal:", err)
continue // 如果序列化失败,则跳过此次循环
}
handler(string(jsonString)) // 调用处理函数
}
}
}
return true // 正常退出循环,返回 true
}