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

54 lines
1.4 KiB
Go
Raw Normal View History

package message_server
import (
"fmt"
"google.golang.org/protobuf/proto"
2023-10-27 16:51:48 +08:00
apiproto "joylink.club/bj-rtsts-server/grpcproto"
"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,
channel: fmt.Sprintf("simulation-%s-status", 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)
}
2023-10-27 16:51:48 +08:00
apiproto.PublishMsg(channel, b)
return nil
}