feat: 无人机控制指令

This commit is contained in:
2025-12-17 11:45:15 +08:00
parent 8990daf861
commit 17bed2438f
23 changed files with 2168 additions and 1774 deletions
@@ -336,8 +336,8 @@ public class DeviceCommandController {
@Operation(summary = "DRC杆量控制")
@PostMapping("/drc/stick")
public Result<String> stickControl(@RequestBody StickControlRequest request) {
log.info("收到杆量控制命令: device={}, roll={}, pitch={}, throttle={}, yaw={}",
request.getDeviceSn(), request.getRoll(), request.getPitch(), request.getThrottle(), request.getYaw());
log.info("收到杆量控制命令: device={}, roll={}, pitch={}, throttle={}, yaw={}, gimbalPitch={}",
request.getDeviceSn(), request.getRoll(), request.getPitch(), request.getThrottle(), request.getYaw(), request.getGimbalPitch());
try {
JSONObject params = new JSONObject();
@@ -345,6 +345,7 @@ public class DeviceCommandController {
params.put("pitch", request.getPitch() != null ? request.getPitch() : 1024);
params.put("throttle", request.getThrottle() != null ? request.getThrottle() : 1024);
params.put("yaw", request.getYaw() != null ? request.getYaw() : 1024);
params.put("gimbal_pitch", request.getGimbalPitch() != null ? request.getGimbalPitch() : 1024);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
@@ -461,6 +462,8 @@ public class DeviceCommandController {
private Integer throttle;
/** 偏航通道(624-1424,1024为中值) */
private Integer yaw;
/** 云台俯仰(624-1424,1024为中值) */
private Integer gimbalPitch;
}
/**
@@ -16,7 +16,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -6,7 +6,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import jakarta.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
@@ -11,7 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import javax.annotation.PostConstruct;
import jakarta.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@@ -464,8 +464,7 @@ public class SseEmitterManager {
.filter(w -> deviceSn.equals(w.getDeviceSn()) && Boolean.TRUE.equals(w.getIsDroneTelemetry()))
.count();
log.info("【无人机数据推送】deviceSn={}, 无人机SSE连接数={}, 总连接数={}",
deviceSn, droneConnectionCount, emitters.size());
// log.info("【无人机数据推送】deviceSn={}, 无人机SSE连接数={}, 总连接数={}",deviceSn, droneConnectionCount, emitters.size());
if (droneConnectionCount == 0) {
log.warn("【无人机数据推送】没有找到无人机SSE连接: deviceSn={}", deviceSn);
@@ -488,7 +487,7 @@ public class SseEmitterManager {
.id("drone-" + System.currentTimeMillis());
wrapper.getEmitter().send(event);
log.info("✅ 发送无人机数据更新成功: session={}, deviceSn={}", sessionId, deviceSn);
// log.info("✅ 发送无人机数据更新成功: session={}, deviceSn={}", sessionId, deviceSn);
} catch (Exception e) {
log.warn("发送无人机数据更新失败,连接可能已关闭: session={}, deviceSn={}, error={}",
sessionId, deviceSn, e.getMessage());
@@ -16,8 +16,8 @@ import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@@ -211,7 +211,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
*/
private void handleCommandResponseMessage(JSONObject json) {
String topic = json.getString("topic");
String requestId = json.getString("id");
String requestId = json.getString("requestId");
String deviceSn = extractDeviceSn(topic);
log.info("收到命令响应: topic={}, requestId={}, deviceSn={}, json={}", topic, requestId, deviceSn, json.toJSONString());
@@ -1,30 +0,0 @@
package com.central.device.websocket.config;
import com.central.device.websocket.handler.DeviceControlWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* 设备控制WebSocket配置
* 用于云台控制和摇杆控制的高频实时通信
*
* @author lishilin
* @date 2025-01-19
*/
@Configuration
@EnableWebSocket
public class DeviceControlWebSocketConfig implements WebSocketConfigurer {
@Autowired
private DeviceControlWebSocketHandler deviceControlWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// 注册WebSocket端点,路径格式: /ws/control/{deviceSn}
registry.addHandler(deviceControlWebSocketHandler, "/ws/control/*")
.setAllowedOrigins("*"); // 生产环境应配置具体域名
}
}
@@ -1,309 +0,0 @@
package com.central.device.websocket.handler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.config.WebSocketProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 设备控制WebSocket处理器
* 处理前端发送的高频控制指令(云台、摇杆)
* 直接转发到JetLinks WebSocket
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Component
public class DeviceControlWebSocketHandler extends TextWebSocketHandler {
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
@Autowired
private WebSocketProperties properties;
/**
* 活跃的WebSocket会话: sessionId -> WebSocketSession
*/
private final Map<String, WebSocketSession> activeSessions = new ConcurrentHashMap<>();
/**
* 会话对应的设备SN: sessionId -> deviceSn
*/
private final Map<String, String> sessionDeviceMap = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 从URL路径中提取deviceSn: /ws/control/{deviceSn}
String path = session.getUri().getPath();
String deviceSn = extractDeviceSn(path);
if (deviceSn == null || deviceSn.isEmpty()) {
log.warn("无效的WebSocket连接,缺少deviceSn: path={}", path);
session.close(CloseStatus.BAD_DATA.withReason("Missing deviceSn"));
return;
}
String sessionId = session.getId();
activeSessions.put(sessionId, session);
sessionDeviceMap.put(sessionId, deviceSn);
log.info("设备控制WebSocket连接建立: sessionId={}, deviceSn={}", sessionId, deviceSn);
// 确保JetLinks WebSocket已连接
if (!jetLinksWebSocketClient.isConnected()) {
log.info("JetLinks WebSocket未连接,自动建立连接");
jetLinksWebSocketClient.connect();
}
// 发送连接成功消息
sendResponse(session, "response", true, "连接成功", null);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String sessionId = session.getId();
String deviceSn = sessionDeviceMap.get(sessionId);
if (deviceSn == null) {
log.warn("未知会话收到消息: sessionId={}", sessionId);
return;
}
try {
String payload = message.getPayload();
JSONObject json = JSON.parseObject(payload);
String type = json.getString("type");
switch (type) {
case "heartbeat":
// 心跳响应
sendPong(session);
break;
case "stick_control":
// 摇杆控制
handleStickControl(session, deviceSn, json.getJSONObject("data"));
break;
case "gimbal_control":
// 云台控制
handleGimbalControl(session, deviceSn, json.getJSONObject("data"));
break;
default:
log.warn("未知消息类型: type={}, sessionId={}", type, sessionId);
sendResponse(session, "error", false, "未知消息类型: " + type, null);
}
} catch (Exception e) {
log.error("处理控制消息失败: sessionId={}, error={}", sessionId, e.getMessage());
sendResponse(session, "error", false, "消息处理失败: " + e.getMessage(), null);
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
String sessionId = session.getId();
String deviceSn = sessionDeviceMap.remove(sessionId);
activeSessions.remove(sessionId);
log.info("设备控制WebSocket连接关闭: sessionId={}, deviceSn={}, status={}",
sessionId, deviceSn, status);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
String sessionId = session.getId();
log.error("设备控制WebSocket传输错误: sessionId={}, error={}", sessionId, exception.getMessage());
}
/**
* 处理摇杆控制
*/
private void handleStickControl(WebSocketSession session, String deviceSn, JSONObject data) {
if (data == null) {
sendResponse(session, "error", false, "缺少控制数据", null);
return;
}
// 构建JetLinks命令
JSONObject params = new JSONObject();
params.put("roll", data.getIntValue("roll") != 0 ? data.getIntValue("roll") : 1024);
params.put("pitch", data.getIntValue("pitch") != 0 ? data.getIntValue("pitch") : 1024);
params.put("throttle", data.getIntValue("throttle") != 0 ? data.getIntValue("throttle") : 1024);
params.put("yaw", data.getIntValue("yaw") != 0 ? data.getIntValue("yaw") : 1024);
String commandId = sendToJetLinks(deviceSn, "stick_control", params);
if (commandId != null) {
sendResponse(session, "response", true, "摇杆指令已发送", commandId);
} else {
sendResponse(session, "error", false, "摇杆指令发送失败", null);
}
}
/**
* 处理云台控制
*/
private void handleGimbalControl(WebSocketSession session, String deviceSn, JSONObject data) {
if (data == null) {
sendResponse(session, "error", false, "缺少控制数据", null);
return;
}
// 构建JetLinks命令
JSONObject params = new JSONObject();
params.put("pitch_speed", data.getDoubleValue("pitchSpeed"));
params.put("yaw_speed", data.getDoubleValue("yawSpeed"));
params.put("locked", data.getBooleanValue("locked"));
String commandId = sendToJetLinks(deviceSn, "camera_screen_drag", params);
if (commandId != null) {
sendResponse(session, "response", true, "云台指令已发送", commandId);
} else {
sendResponse(session, "error", false, "云台指令发送失败", null);
}
}
/**
* 发送命令到JetLinks
*
* @return commandId 或 null(失败时)
*/
private String sendToJetLinks(String deviceSn, String method, JSONObject data) {
if (!jetLinksWebSocketClient.isConnected()) {
log.warn("JetLinks WebSocket未连接,尝试重连");
jetLinksWebSocketClient.connect();
// 等待连接(最多1秒,避免阻塞高频控制)
int waitCount = 0;
while (!jetLinksWebSocketClient.isConnected() && waitCount < 10) {
try {
Thread.sleep(100);
waitCount++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}
if (!jetLinksWebSocketClient.isConnected()) {
log.error("JetLinks WebSocket连接失败");
return null;
}
}
try {
String commandId = UUID.randomUUID().toString();
// 构造 properties
JSONObject properties = new JSONObject();
properties.put("method", method);
JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data);
properties.put("data", dataWrapper);
// 构造 parameter
JSONObject parameter = new JSONObject();
parameter.put("messageType", "WRITE_PROPERTY");
parameter.put("properties", properties);
JSONObject headers = new JSONObject();
headers.put("async", false);
parameter.put("headers", headers);
// 构造完整消息
JSONObject message = new JSONObject();
message.put("type", "sub");
message.put("topic", "/device-message-sender/D-Dock2/" + deviceSn);
message.put("parameter", parameter);
message.put("id", commandId);
// 发送
String messageJson = message.toJSONString();
log.debug("发送实时控制命令: deviceSn={}, method={}, commandId={}", deviceSn, method, commandId);
jetLinksWebSocketClient.send(messageJson);
return commandId;
} catch (Exception e) {
log.error("发送JetLinks命令失败: deviceSn={}, method={}, error={}", deviceSn, method, e.getMessage());
return null;
}
}
/**
* 发送响应消息
*/
private void sendResponse(WebSocketSession session, String type, boolean success, String message, String commandId) {
try {
JSONObject response = new JSONObject();
response.put("type", type);
response.put("success", success);
response.put("message", message);
if (commandId != null) {
response.put("commandId", commandId);
}
session.sendMessage(new TextMessage(response.toJSONString()));
} catch (IOException e) {
log.error("发送响应失败: sessionId={}, error={}", session.getId(), e.getMessage());
}
}
/**
* 发送心跳响应
*/
private void sendPong(WebSocketSession session) {
try {
JSONObject pong = new JSONObject();
pong.put("type", "pong");
pong.put("timestamp", System.currentTimeMillis());
session.sendMessage(new TextMessage(pong.toJSONString()));
} catch (IOException e) {
log.error("发送心跳响应失败: sessionId={}, error={}", session.getId(), e.getMessage());
}
}
/**
* 从路径中提取deviceSn
* 路径格式: /ws/control/{deviceSn}
*/
private String extractDeviceSn(String path) {
if (path == null) return null;
// 移除末尾的斜杠
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
// 提取最后一段作为deviceSn
int lastSlash = path.lastIndexOf('/');
if (lastSlash >= 0 && lastSlash < path.length() - 1) {
return path.substring(lastSlash + 1);
}
return null;
}
/**
* 获取活跃连接数
*/
public int getActiveConnectionCount() {
return activeSessions.size();
}
}
@@ -12,8 +12,8 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -411,8 +411,7 @@ public class DeviceMessageHandler {
alarmDataService.saveMsgAlarmData(deviceSn, msgAlarmData);
}
log.info("处理 msg_alarm 事件: deviceSn={}, timestamp={}, droneData字段: {}",
deviceSn, timestamp, droneData.keySet());
//log.info("处理 msg_alarm 事件: deviceSn={}, timestamp={}, droneData字段: {}",deviceSn, timestamp, droneData.keySet());
// 触发 msg_alarm 回调(用于一次性订阅)
BiConsumer<String, JSONObject> msgAlarmCallback = msgAlarmCallbacks.get(deviceSn);
@@ -430,11 +429,11 @@ public class DeviceMessageHandler {
// 推送到无人机专用的SSE连接
if (sseEmitterManager != null) {
try {
log.info("【handleMsgAlarmEvent】准备推送无人机数据到SSE: deviceSn={}", deviceSn);
// log.info("【handleMsgAlarmEvent】准备推送无人机数据到SSE: deviceSn={}", deviceSn);
sseEmitterManager.getClass()
.getMethod("sendDroneDataUpdate", String.class, DroneRealtimeData.class)
.invoke(sseEmitterManager, deviceSn, droneRealtimeData);
log.info("【handleMsgAlarmEvent】已推送无人机数据到专用SSE连接: deviceSn={}", deviceSn);
// log.info("【handleMsgAlarmEvent】已推送无人机数据到专用SSE连接: deviceSn={}", deviceSn);
} catch (Exception e) {
log.error("【handleMsgAlarmEvent】调用无人机SSE推送失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
}
@@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import jakarta.annotation.PostConstruct;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.*;
@@ -253,6 +253,7 @@ public class DeviceCommandManager {
data.put("pitch", params.getIntValue("pitch"));
data.put("throttle", params.getIntValue("throttle"));
data.put("yaw", params.getIntValue("yaw"));
data.put("gimbal_pitch", params.getIntValue("gimbal_pitch"));
break;
case "camera_screen_drag":
@@ -269,9 +270,15 @@ public class DeviceCommandManager {
}
properties.put("method", method);
JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data);
properties.put("data", dataWrapper);
// 一键起飞命令需要 data.data 的嵌套结构,其他命令直接使用 data
if ("takeoff_to_point".equals(method)) {
JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data);
properties.put("data", dataWrapper);
} else {
properties.put("data", data);
}
return properties;
}
@@ -8,7 +8,7 @@ import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import jakarta.annotation.PreDestroy;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;