rts-sim-testing-service/message_server/simulation_state_ms.go

55 lines
1.4 KiB
Go
Raw Normal View History

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"
2023-10-27 16:51:48 +08:00
"joylink.club/ecs"
)
// 世界状态变化消息服务
type SimulationStateMs struct {
2023-10-27 16:51:48 +08:00
vs *memory.VerifySimulation
channel string
}
func NewSimulationStateMs(vs *memory.VerifySimulation) *SimulationStateMs {
2023-10-27 16:51:48 +08:00
ms := &SimulationStateMs{
vs: vs,
2023-11-17 18:04:38 +08:00
channel: fmt.Sprintf(SimulationStateTopic, vs.SimulationId),
}
2023-10-27 16:51:48 +08:00
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,
2023-10-27 16:51:48 +08:00
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,
})
2023-10-27 16:51:48 +08:00
}
})
return ms
}
2023-10-27 16:51:48 +08:00
func doSendState(channel string, status *state.SimulationStatus) error {
b, err := proto.Marshal(status)
if err != nil {
2023-10-27 16:51:48 +08:00
return fmt.Errorf("仿真状态消息服务数据序列化失败, %s", err)
}
mqtt.Publish(channel, b)
// apiproto.PublishMsg(channel, b)
2023-10-27 16:51:48 +08:00
return nil
}