102 lines
2.6 KiB
Go
102 lines
2.6 KiB
Go
package dynamics
|
|
|
|
import (
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/panjf2000/gnet/v2"
|
|
"joylink.club/bj-rtsts-server/config"
|
|
"log"
|
|
"net"
|
|
"strconv"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// 这里用来测试通信与数据传输是否正常
|
|
|
|
func TestAll(t *testing.T) {
|
|
loadAndChangeConfig()
|
|
//注册列车信息处理逻辑
|
|
RegisterTrainInfoHandler(&ExampleTrainInfoHandler{})
|
|
//启动udp服务
|
|
go RunUdpServer()
|
|
////启动仅用于的测试的模拟远程udp服务
|
|
go runTestUdpServer()
|
|
////启动http服务
|
|
go runTestHttpServer()
|
|
time.Sleep(2 * time.Second)
|
|
//向本地udp服务发送数据
|
|
sendDataToLocalUdpServer()
|
|
//向远程udp服务发送数据
|
|
_ = SendTurnoutInfo(&TurnoutInfo{Code: 02})
|
|
//发送http请求
|
|
_, _, _ = SendTrainInitReq(&InitTrainInfo{Speed: 10})
|
|
}
|
|
|
|
func loadAndChangeConfig() {
|
|
config.LoadConfig()
|
|
config.Config.Dynamics.Ip = "127.0.0.1"
|
|
config.Config.Dynamics.HttpPort = 3500
|
|
}
|
|
|
|
func sendDataToLocalUdpServer() {
|
|
addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:"+strconv.Itoa(config.Config.Dynamics.UdpLocalPort))
|
|
conn, _ := net.DialUDP("udp", nil, addr)
|
|
buf, _ := hex.DecodeString("0009012EE009000000070380000006000100020003000A000A000A000A000A000A000A")
|
|
conn.Write(buf)
|
|
conn.Close()
|
|
}
|
|
|
|
func runTestHttpServer() {
|
|
engine := gin.Default()
|
|
engine.POST("/api/aerodynamics/init/train", func(context *gin.Context) {
|
|
info := InitTrainInfo{}
|
|
err := context.ShouldBindJSON(&info)
|
|
if err != nil {
|
|
println(err.Error())
|
|
}
|
|
data, err := json.MarshalIndent(info, "", " ")
|
|
fmt.Println("---------------- 接收到的列车初始化信息 ----------------")
|
|
fmt.Println(string(data))
|
|
if info.Speed != 10 {
|
|
println("http服务接收到的数据异常")
|
|
}
|
|
})
|
|
engine.Run(fmt.Sprintf(":%d", config.Config.Dynamics.HttpPort))
|
|
}
|
|
|
|
func runTestUdpServer() {
|
|
server := &testUdpServer{addr: fmt.Sprintf("udp://:%d", config.Config.Dynamics.UdpRemotePort), multicore: false}
|
|
log.Fatal(gnet.Run(server, server.addr, gnet.WithMulticore(server.multicore)))
|
|
}
|
|
|
|
type testUdpServer struct {
|
|
gnet.BuiltinEventEngine
|
|
|
|
eng gnet.Engine
|
|
addr string
|
|
multicore bool
|
|
|
|
eventHandlers []gnet.EventHandler
|
|
}
|
|
|
|
func (server *testUdpServer) OnTraffic(c gnet.Conn) gnet.Action {
|
|
buf, err := c.Next(-1)
|
|
if err != nil {
|
|
println(err.Error())
|
|
}
|
|
fmt.Println("---------------- 远程udp服务接收到的字节数据 ----------------")
|
|
fmt.Println(buf)
|
|
return gnet.None
|
|
}
|
|
|
|
type ExampleTrainInfoHandler struct {
|
|
}
|
|
|
|
func (handler *ExampleTrainInfoHandler) HandleTrainInfo(info TrainInfo) {
|
|
fmt.Println("处理列车信息...")
|
|
fmt.Println(info)
|
|
}
|