rts-sim-testing-service/third_party/electrical_machinery/electrical_machinery.go

75 lines
2.1 KiB
Go

package electrical_machinery
import (
"fmt"
"sync"
"joylink.club/bj-rtsts-server/config"
"joylink.club/bj-rtsts-server/third_party/message"
"joylink.club/bj-rtsts-server/third_party/udp"
)
// 电机转速UDP
type ElectricMachinery interface {
Start(manager ElectricMachineryMessageManager) // 启动电机转速UDP消息处理
Stop() // 停止电机转速消息处理
SendElectricMachineryMessage(info *message.ElectricMachinery) // 发送电机转速消息
}
type ElectricMachineryMessageManager interface {
GetElectricMachineryRunConfig() *config.ElectricMachineryConfig // 获取电机转速参数
}
type electricalMachineryImpl struct {
electricalMachineryUdpClient udp.UdpClient
manager ElectricMachineryMessageManager
runConfig *config.ElectricMachineryConfig
}
func (s *electricalMachineryImpl) Start(manager ElectricMachineryMessageManager) {
if manager == nil {
panic("启动电机转速消息服务错误: ElectricMachineryMessageManager不能为nil")
}
if s.manager != nil {
panic("启动电机转速消息服务错误: 存在正在运行的任务")
}
s.runConfig = manager.GetElectricMachineryRunConfig()
if s.runConfig == nil || s.runConfig.Ip == "" || !s.runConfig.Open {
return
}
// 初始化客户端、服务端
s.initElectricalMachinery()
s.manager = manager
}
func (s *electricalMachineryImpl) Stop() {
initMutex.Lock()
defer initMutex.Unlock()
_default = nil
if s.electricalMachineryUdpClient != nil {
s.electricalMachineryUdpClient.Close()
}
s.manager = nil
}
func (s *electricalMachineryImpl) SendElectricMachineryMessage(info *message.ElectricMachinery) {
s.electricalMachineryUdpClient.Send(info.Encode())
}
func (s *electricalMachineryImpl) initElectricalMachinery() {
s.electricalMachineryUdpClient = udp.NewClient(fmt.Sprintf("%v:%v", s.runConfig.Ip, s.runConfig.RemotePort))
}
var _default ElectricMachinery
var initMutex sync.Mutex
func Default() ElectricMachinery {
initMutex.Lock()
defer initMutex.Unlock()
if _default == nil {
_default = &electricalMachineryImpl{}
}
return _default
}