rts-sim-testing-service/dynamics/udp.go

90 lines
2.4 KiB
Go
Raw Normal View History

2023-07-26 17:02:53 +08:00
package dynamics
import (
"encoding/binary"
"errors"
"fmt"
"github.com/panjf2000/gnet/v2"
"joylink.club/bj-rtsts-server/config"
"log"
"net"
)
var server *udpServer
// SendTurnoutInfo 发送道岔信息
func SendTurnoutInfo(info *TurnoutInfo) error {
if server == nil {
return errors.New("服务尚未启动")
}
remoteAddr, _ := net.ResolveUDPAddr("udp", config.Config.Dynamics.UdpRemoteAddr)
conn, err := net.DialUDP("udp", nil, remoteAddr)
if err != nil {
panic(err)
}
defer conn.Close()
var data []byte
data = binary.BigEndian.AppendUint16(data, info.Code)
var b byte
if info.NPosition {
b |= 1 << 7
}
if info.RPosition {
b |= 1 << 6
}
data = append(data, b)
_, err = conn.Write(data)
return err
}
type udpServer struct {
gnet.BuiltinEventEngine
eng gnet.Engine
addr string
multicore bool
eventHandlers []gnet.EventHandler
}
func (server *udpServer) OnBoot(eng gnet.Engine) gnet.Action {
server.eng = eng
log.Printf("echo server with multi-core=%t is listening on %s\n", server.multicore, server.addr)
return gnet.None
}
// OnTraffic 接收到数据后的解析
func (server *udpServer) OnTraffic(c gnet.Conn) gnet.Action {
buf, _ := c.Next(-1)
trainInfo := TrainInfo{}
trainInfo.LifeSignal = binary.BigEndian.Uint16(buf[0:2])
trainInfo.Number = buf[2]
trainInfo.Len = binary.BigEndian.Uint16(buf[3:5])
trainInfo.Link = buf[5]
trainInfo.LinkOffset = binary.BigEndian.Uint32(buf[6:10])
trainInfo.Slope = buf[10]
b := buf[11]
trainInfo.UpSlope = (b & (1 << 7)) != 0
trainInfo.Up = (b & (1 << 6)) != 0
trainInfo.TotalResistance = binary.BigEndian.Uint16(buf[13:15])
trainInfo.Resistance1 = binary.BigEndian.Uint16(buf[15:17])
trainInfo.Resistance2 = binary.BigEndian.Uint16(buf[17:19])
trainInfo.Resistance3 = binary.BigEndian.Uint16(buf[19:21])
trainInfo.Speed = binary.BigEndian.Uint16(buf[21:23])
trainInfo.HeadSpeed1 = binary.BigEndian.Uint16(buf[23:25])
trainInfo.HeadSpeed2 = binary.BigEndian.Uint16(buf[25:27])
trainInfo.TailSpeed1 = binary.BigEndian.Uint16(buf[27:29])
trainInfo.TailSpeed2 = binary.BigEndian.Uint16(buf[29:31])
trainInfo.HeadRadarSpeed = binary.BigEndian.Uint16(buf[31:33])
trainInfo.TailRadarSpeed = binary.BigEndian.Uint16(buf[33:35])
fmt.Println(trainInfo)
return gnet.None
}
func RunUdpServer() {
server = &udpServer{addr: fmt.Sprintf("udp://:%d", config.Config.Dynamics.UdpLocalPort), multicore: false}
log.Fatal(gnet.Run(server, server.addr, gnet.WithMulticore(server.multicore)))
}