package service import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net" "gat1400Exchange/config" "gat1400Exchange/models" "gat1400Exchange/pkg/logger" "golang.org/x/text/encoding/simplifiedchinese" "golang.org/x/text/transform" ) type ElevatorStatus struct { TotalFloors int `json:"TotalFloors"` Floor int `json:"Floor"` FloorName string `json:"FloorName"` RunDir int `json:"RunDir"` Speed string `json:"Speed"` } type Elevator struct { Name string `json:"Name"` IP string `json:"IP"` Status ElevatorStatus `json:"Status"` Alarm []interface{} `json:"Alarm"` // You might want to define a specific type for alarms } type ElevatorData struct { Elevator []Elevator `json:"Elevator"` } // 对接网络视频字符叠加器,接收udp发送的楼层信息, 更新device地址 func NVCSServer() { // 指定监听的端口 port := config.ServeConf.Port // 创建一个UDP地址 address, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%s", port)) if err != nil { logger.Error("Error resolving address:", err) return } // 创建一个UDP连接 conn, err := net.ListenUDP("udp", address) if err != nil { logger.Error("Error listening:", err) return } defer conn.Close() logger.Info("UDP server listening on port %s...", port) // 无限循环等待接收数据 for { // 创建一个缓冲区来存储接收的数据 buffer := make([]byte, 256) // 从连接中读取数据 numBytes, clientAddr, err := conn.ReadFromUDP(buffer) if err != nil { logger.Warn("Error reading from UDP connection:%s", err.Error()) continue } // 设备上传的中文数据为GBK编码, 转换为utf8 decoder := simplifiedchinese.GBK.NewDecoder() reader := transform.NewReader(bytes.NewReader(buffer[:numBytes]), decoder) decodedBytes, err := ioutil.ReadAll(reader) var data ElevatorData // Unmarshal JSON into the struct err = json.Unmarshal(decodedBytes, &data) if err != nil { logger.Warn("ElevatorData unmarshal error:%s", err.Error()) continue } if len(data.Elevator) == 0 { continue } if data.Elevator[0].Status.RunDir > 0 { continue } elevator := data.Elevator[0] var d = models.Device{ Id: elevator.Name, Pos: elevator.Status.FloorName, Ip: elevator.IP, } err = d.Upsert() if err != nil { logger.Warn("Device db update error:%s", err.Error()) } deviceAliveCache.Add(elevator.Name, true) logger.Debug("Received %d bytes from %s, %+v", numBytes, clientAddr, data) } }