package com.tuoheng.status.machine.service; import com.tuoheng.status.machine.events.CoverEvent; import com.tuoheng.status.machine.status.CoverState; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.statemachine.StateMachine; import org.springframework.statemachine.config.StateMachineFactory; import org.springframework.stereotype.Component; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 舱门状态机管理器 */ @Component public class CoverMachineService { @Autowired StateMachineFactory coverStateMachineFactory; private final Map> stateMachineMap = new ConcurrentHashMap<>(); public StateMachine getOrCreateStateMachine(String airportSn) { return stateMachineMap.computeIfAbsent(airportSn, id -> { StateMachine stateMachine = coverStateMachineFactory.getStateMachine(id); stateMachine.start(); System.out.println("创建并启动舱门状态机: " + id); return stateMachine; }); } public CoverState getCurrentState(String airportSn) { StateMachine stateMachine = stateMachineMap.get(airportSn); if (stateMachine == null) { return null; } return stateMachine.getState().getId(); } public boolean sendEvent(String airportSn, CoverEvent event) { StateMachine stateMachine = getOrCreateStateMachine(airportSn); boolean result = stateMachine.sendEvent(event); if (result) { System.out.println(String.format("舱门事件发送成功 - 机巢: %s, 事件: %s, 当前状态: %s", airportSn, event, getCurrentState(airportSn))); } else { System.out.println(String.format("舱门事件发送失败 - 机巢: %s, 事件: %s, 当前状态: %s", airportSn, event, getCurrentState(airportSn))); } return result; } public boolean isInState(String airportSn, CoverState state) { StateMachine stateMachine = stateMachineMap.get(airportSn); if (stateMachine == null) { return false; } return stateMachine.getState().getId() == state; } public void removeStateMachine(String airportSn) { StateMachine stateMachine = stateMachineMap.remove(airportSn); if (stateMachine != null) { stateMachine.stop(); System.out.println("停止并移除舱门状态机: " + airportSn); } } }