rts-sim-testing-service/ats/verify/simulation/simulation_manage.go

121 lines
3.2 KiB
Go

package simulation
import (
"strconv"
"sync"
"joylink.club/bj-rtsts-server/ats/verify/simulation/wayside/memory"
"joylink.club/bj-rtsts-server/config"
"joylink.club/bj-rtsts-server/sys_error"
"joylink.club/bj-rtsts-server/third_party/dynamics"
"joylink.club/bj-rtsts-server/third_party/semi_physical_train"
"joylink.club/bj-rtsts-server/dto"
)
// 仿真存储集合
var simulationMap sync.Map
// 创建前检查
func IsExistSimulation() bool {
i := 0
simulationMap.Range(func(_, _ any) bool {
i++
return true
})
return i > 0
}
// 创建仿真对象
func CreateSimulation(projectId int32, mapIds []int32) (string, error) {
simulationId := createSimulationId(projectId)
_, e := simulationMap.Load(simulationId)
if !e && IsExistSimulation() {
// panic(dto.ErrorDto{Code: dto.DataAlreadyExist, Message: "已有仿真在运行"})
return "", sys_error.New("一套环境同时只能运行一个仿真")
}
if !e {
verifySimulation, err := memory.CreateSimulation(projectId, mapIds)
if err != nil {
return "", err
// panic(fmt.Sprintf("创建仿真失败:%s", err.Error()))
}
verifySimulation.SimulationId = simulationId
if config.Config.Dynamics.Open {
// 动力学接口调用
lineBaseInfo := verifySimulation.BuildLineBaseInfo()
err := dynamics.Default().RequestStartSimulation(lineBaseInfo)
if err != nil {
return "", err
// panic(dto.ErrorDto{Code: dto.DynamicsError, Message: err.Error()})
}
dynamics.Default().Start(verifySimulation)
}
if config.Config.Vobc.Open {
// 半实物系统接口功能启动
semi_physical_train.Default().Start(verifySimulation)
}
simulationMap.Store(simulationId, verifySimulation)
// 全部成功,启动仿真
verifySimulation.World.StartUp()
}
return simulationId, nil
}
// 删除仿真对象
func DestroySimulation(simulationId string) {
s, e := simulationMap.Load(simulationId)
if !e {
return
}
simulationInfo := s.(*memory.VerifySimulation)
simulationMap.Delete(simulationId)
// 停止ecs world
simulationInfo.World.Close()
if config.Config.Dynamics.Open {
// 停止动力学接口功能
dynamics.Default().Stop()
dynamics.Default().RequestStopSimulation()
}
}
func createSimulationId(projectId int32) string {
// 当前服务器IP + 端口 + 项目
return config.SimulationId_prefix + "_" + strconv.Itoa(config.Config.Server.Port) + "_" + strconv.Itoa(int(projectId))
}
// 获取仿真列表
func ListAllSimulations() []*dto.SimulationInfoRspDto {
var simArr []*dto.SimulationInfoRspDto
simulationMap.Range(func(_, v any) bool {
s := v.(*memory.VerifySimulation)
simArr = append(simArr, &dto.SimulationInfoRspDto{
SimulationId: s.SimulationId,
MapId: s.MapIds[0],
MapIds: s.MapIds,
ProjectId: s.ProjectId,
})
return true
})
return simArr
}
// 根据仿真id查找仿真实例
func FindSimulation(simulationId string) *memory.VerifySimulation {
m, e := simulationMap.Load(simulationId)
if e {
return m.(*memory.VerifySimulation)
}
return nil
}
// 获取普通仿真数组
func GetSimulationArr() []*memory.VerifySimulation {
var result []*memory.VerifySimulation
simulationMap.Range(func(_, v any) bool {
result = append(result, v.(*memory.VerifySimulation))
return true
})
return result
}