rts-sim-testing-service/message_server/simulation_state_ms.go
2023-10-30 11:13:36 +08:00

54 lines
1.4 KiB
Go

package message_server
import (
"fmt"
"google.golang.org/protobuf/proto"
apiproto "joylink.club/bj-rtsts-server/grpcproto"
"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("simulation-%s-status", 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)
}
apiproto.PublishMsg(channel, b)
return nil
}