package com.ard.work.config; import com.ard.work.domain.enums.RouteEvent; import com.ard.work.domain.enums.RouteState; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.config.EnableStateMachineFactory; import org.springframework.statemachine.config.StateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; import org.springframework.statemachine.guard.Guard; import org.springframework.statemachine.service.DefaultStateMachineService; import org.springframework.statemachine.service.StateMachineService; import java.util.EnumSet; @Configuration @EnableStateMachineFactory public class RouteStateMachineConfig extends StateMachineConfigurerAdapter { /** * 配置状态机的状态集 */ @Override public void configure(StateMachineStateConfigurer states) throws Exception { states .withStates() .initial(RouteState.IDLE) // 初始状态 .states(EnumSet.allOf(RouteState.class)); // 注册所有状态 } /** * 配置状态流转规则 */ @Override public void configure(StateMachineTransitionConfigurer transitions) throws Exception { transitions // IDLE → UPLOADED .withExternal() .source(RouteState.IDLE) .target(RouteState.UPLOADED) .event(RouteEvent.UPLOAD_SUCCESS) .and() // UPLOADED → RUNNING .withExternal() .source(RouteState.UPLOADED) .target(RouteState.RUNNING) .event(RouteEvent.START_SUCCESS) .and() // RUNNING → PAUSED .withExternal() .source(RouteState.RUNNING) .target(RouteState.PAUSED) .event(RouteEvent.PAUSE_SUCCESS) .and() // PAUSED → RUNNING .withExternal() .source(RouteState.PAUSED) .target(RouteState.RUNNING) .event(RouteEvent.RESUME_SUCCESS) .and() // RUNNING / PAUSED → STOPPED .withExternal() .source(RouteState.RUNNING) .target(RouteState.STOPPED) .event(RouteEvent.STOP_SUCCESS) .and() .withExternal() .source(RouteState.PAUSED) .target(RouteState.STOPPED) .event(RouteEvent.STOP_SUCCESS) .and() // ⭐ STOPPED → IDLE(为下一条航线做准备) .withExternal() .source(RouteState.STOPPED) .target(RouteState.IDLE) .event(RouteEvent.RESET_ROUTE); } /** * 可选:守卫器 - 校验boxSn合法性(示例) */ @Bean public Guard validBoxSnGuard() { return context -> { // 从扩展变量中获取boxSn并校验 String boxSn = (String) context.getMessageHeader("boxSn"); return boxSn != null && !boxSn.isEmpty(); }; } /** * 状态机服务(用于管理多实例) */ @Bean public StateMachineService stateMachineService( org.springframework.statemachine.config.StateMachineFactory factory) { return new DefaultStateMachineService<>(factory); } }