rts-sim-testing-service/message_server/simulation_state_ms.go
2023-11-17 18:04:38 +08:00

55 lines
1.4 KiB
Go

package message_server
import (
"fmt"
"google.golang.org/protobuf/proto"
"joylink.club/bj-rtsts-server/mqtt"
"joylink.club/bj-rtsts-server/ts/protos/state"
"joylink.club/bj-rtsts-server/ts/simulation/wayside/memory"
"joylink.club/ecs"
)
// 世界状态变化消息服务
type SimulationStateMs struct {
vs *memory.VerifySimulation
channel string
}
func NewSimulationStateMs(vs *memory.VerifySimulation) *SimulationStateMs {
ms := &SimulationStateMs{
vs: vs,
channel: fmt.Sprintf(SimulationStateTopic, vs.SimulationId),
}
ecs.WorldStateChangeEvent.Subscribe(ms.vs.World, func(_ ecs.World, e ecs.WorldStateChange) {
switch e.NewState {
case ecs.WorldClose:
doSendState(ms.channel, &state.SimulationStatus{
SimulationId: vs.SimulationId,
State: state.SimulationStatus_DESTROY,
})
case ecs.WorldError:
doSendState(ms.channel, &state.SimulationStatus{
SimulationId: vs.SimulationId,
State: state.SimulationStatus_ERROR,
})
case ecs.WorldPause:
doSendState(ms.channel, &state.SimulationStatus{
SimulationId: vs.SimulationId,
State: state.SimulationStatus_PAUSE,
})
}
})
return ms
}
func doSendState(channel string, status *state.SimulationStatus) error {
b, err := proto.Marshal(status)
if err != nil {
return fmt.Errorf("仿真状态消息服务数据序列化失败, %s", err)
}
mqtt.Publish(channel, b)
// apiproto.PublishMsg(channel, b)
return nil
}