rts-sim-testing-service/third_party/interlock/beijing11/interlock.go

64 lines
1.4 KiB
Go
Raw Normal View History

2024-05-13 13:17:16 +08:00
// Package beijing11 北京11号线联锁通信
package beijing11
import (
"encoding/json"
2024-05-13 13:17:16 +08:00
"fmt"
"joylink.club/bj-rtsts-server/config"
"joylink.club/bj-rtsts-server/third_party/udp"
"log/slog"
"sync"
)
var (
initMutex = sync.Mutex{}
logTag = "[北京11号线联锁通信]"
running = false
server udp.UdpServer
2024-05-13 13:17:16 +08:00
)
func Start(interlockConfig *config.InterlockConfig) {
if interlockConfig == nil || interlockConfig.Ip == "" || !interlockConfig.Open {
2024-05-13 13:17:16 +08:00
return
}
if running {
return
2024-05-13 13:17:16 +08:00
}
initMutex.Lock()
defer initMutex.Unlock()
if running {
2024-05-13 13:17:16 +08:00
return
}
//UDP通信设施
server = udp.NewServer(fmt.Sprintf(":%d", interlockConfig.LocalPort), func(b []byte) {
slog.Info(fmt.Sprintf("%s收到消息%x", logTag, b))
frame := &FromInterlockFrame{}
err := frame.Decode(b)
2024-05-13 13:17:16 +08:00
if err != nil {
slog.Error(fmt.Sprintf("%s解析数据出错%s", logTag, err))
} else {
marshal, err := json.Marshal(frame)
if err != nil {
slog.Error(fmt.Sprintf("%s解析为json出错%s", logTag, err))
} else {
slog.Info(fmt.Sprintf("%s解析为json%s", logTag, string(marshal)))
}
2024-05-13 13:17:16 +08:00
}
})
err := server.Listen()
if err != nil {
panic(fmt.Sprintf("%s启动UDP服务失败%s", logTag, err))
2024-05-13 13:17:16 +08:00
}
running = true
2024-05-13 13:17:16 +08:00
}
func Stop() {
2024-05-13 13:17:16 +08:00
initMutex.Lock()
defer initMutex.Unlock()
running = false
if server != nil {
server.Close()
server = nil
2024-05-13 13:17:16 +08:00
}
}