Commit 1e2e8666 authored by wanghao's avatar wanghao

1 机械臂 状态检查和指令完成之间存在竞态条件,影响界面显示 指令状态问题调整。

parent 4567dc04
...@@ -56,7 +56,8 @@ public class NettyUdpServerHandler extends SimpleChannelInboundHandler<DatagramP ...@@ -56,7 +56,8 @@ public class NettyUdpServerHandler extends SimpleChannelInboundHandler<DatagramP
private IRobotArmCommandService robotArmCommandService; private IRobotArmCommandService robotArmCommandService;
@Resource @Resource
private ApplicationEventPublisher eventPublisher; // 新增事件发布器 private ApplicationEventPublisher eventPublisher; // 新增事件发布器
// 命令完成锁,用于确保命令完成时只有一个线程执行
private final Object completionLock = new Object();
// 使用原子引用,确保状态变更的原子性 // 使用原子引用,确保状态变更的原子性
private final AtomicReference<CommandState> commandState = new AtomicReference<>(CommandState.IDLE); private final AtomicReference<CommandState> commandState = new AtomicReference<>(CommandState.IDLE);
...@@ -228,12 +229,14 @@ public class NettyUdpServerHandler extends SimpleChannelInboundHandler<DatagramP ...@@ -228,12 +229,14 @@ public class NettyUdpServerHandler extends SimpleChannelInboundHandler<DatagramP
} }
private void handleCompleteState() { private void handleCompleteState() {
// 原子地获取并清空当前指令ID // 只在完全空闲时处理
Long commandIdToComplete = currentCommandId; Long commandIdToComplete = currentCommandId;
if (commandIdToComplete != null) { if (commandIdToComplete != null) {
// 尝试将状态从 EXECUTING 转为 COMPLETING synchronized (completionLock) {
if (commandState.compareAndSet(CommandState.EXECUTING, CommandState.COMPLETING)) { // 再次检查,防止在获取锁期间状态已改变
if (commandIdToComplete.equals(currentCommandId) &&
commandState.compareAndSet(CommandState.EXECUTING, CommandState.COMPLETING)) {
try { try {
// 完成指令 // 完成指令
robotArmCommandService.completeCommand(commandIdToComplete); robotArmCommandService.completeCommand(commandIdToComplete);
...@@ -245,18 +248,23 @@ public class NettyUdpServerHandler extends SimpleChannelInboundHandler<DatagramP ...@@ -245,18 +248,23 @@ public class NettyUdpServerHandler extends SimpleChannelInboundHandler<DatagramP
// 状态转为空闲 // 状态转为空闲
commandState.set(CommandState.IDLE); commandState.set(CommandState.IDLE);
// 处理待执行指令 // 处理待执行指令(这里也加锁确保顺序)
synchronized (this) {
handleFullyIdleState(); handleFullyIdleState();
}
} catch (Exception e) { } catch (Exception e) {
log.error("指令完成失败: {}", commandIdToComplete, e); log.error("指令完成失败: {}", commandIdToComplete, e);
commandState.set(CommandState.ERROR); commandState.set(CommandState.ERROR);
} }
} }
}
} else { } else {
// 没有当前指令,直接处理待执行 // 没有当前指令,直接处理待执行
synchronized (this) {
handleFullyIdleState(); handleFullyIdleState();
} }
} }
}
/** /**
* 记录当前执行的指令 * 记录当前执行的指令
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment