feat: 1:地图仪表盘 2:获取设备消息

This commit is contained in:
2025-11-28 12:38:53 +08:00
parent 5102461a4c
commit 7ce0185974
74 changed files with 15488 additions and 55 deletions
@@ -5,6 +5,7 @@ import com.central.search.annotation.EnableSearchClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
@@ -14,6 +15,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableSearchClient
@EnableTransactionManagement
@EnableFeignInterceptor
@EnableScheduling
@SpringBootApplication
public class DeviceCenterApp {
public static void main(String[] args) {
@@ -0,0 +1,239 @@
package com.central.device.controller;
import com.alibaba.fastjson.JSONObject;
import com.central.common.model.Result;
import com.central.device.service.DeviceAlarmDataService;
import com.central.device.service.OneTimeSubscriptionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 设备告警数据接口
* 提供一次性订阅获取设备 fire_alarm 和 msg_alarm 数据的接口
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@RestController
@RequestMapping("/device/alarm")
@Tag(name = "设备告警数据接口")
public class DeviceAlarmController {
@Autowired
private OneTimeSubscriptionService oneTimeSubscriptionService;
@Autowired
private DeviceAlarmDataService alarmDataService;
/**
* 一次性订阅获取设备告警数据
* 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅并关闭 WebSocket
* 如果实时订阅未获取到数据,会尝试从 Redis 缓存获取
*
* @param deviceSn 设备SN
* @return 包含 fire_alarm 和 msg_alarm 数据的结果
*/
@GetMapping("/subscribe/{deviceSn}")
@Operation(summary = "一次性订阅获取设备告警数据", description = "订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅")
public Result<DeviceAlarmResponse> subscribeOnce(
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
log.info("接收到一次性订阅请求: deviceSn={}", deviceSn);
if (deviceSn == null || deviceSn.trim().isEmpty()) {
return Result.failed("设备SN不能为空");
}
try {
OneTimeSubscriptionService.DeviceAlarmResult alarmResult = oneTimeSubscriptionService.subscribeOnce(deviceSn);
DeviceAlarmResponse response = new DeviceAlarmResponse();
response.setDeviceSn(alarmResult.getDeviceSn());
response.setSuccess(alarmResult.isSuccess());
response.setMessage(alarmResult.getMessage());
response.setFireAlarmData(alarmResult.getFireAlarmData());
response.setMsgAlarmData(alarmResult.getMsgAlarmData());
response.setFireAlarmFromCache(alarmResult.isFireAlarmFromCache());
response.setMsgAlarmFromCache(alarmResult.isMsgAlarmFromCache());
if (alarmResult.isSuccess()) {
return Result.succeed(response, "获取成功");
} else {
return Result.succeed(response, "未获取到数据");
}
} catch (Exception e) {
log.error("一次性订阅请求失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
return Result.failed("订阅失败: " + e.getMessage());
}
}
/**
* 一次性订阅获取设备告警数据(带超时参数)
*
* @param deviceSn 设备SN
* @param timeoutSeconds 超时时间(秒),默认30秒
* @return 包含 fire_alarm 和 msg_alarm 数据的结果
*/
@GetMapping("/subscribe/{deviceSn}/timeout/{timeoutSeconds}")
@Operation(summary = "一次性订阅获取设备告警数据(带超时)", description = "订阅 fire_alarm 和 msg_alarm,可自定义超时时间")
public Result<DeviceAlarmResponse> subscribeOnceWithTimeout(
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn,
@Parameter(description = "超时时间(秒)", required = true) @PathVariable int timeoutSeconds) {
log.info("接收到一次性订阅请求(带超时): deviceSn={}, timeout={}s", deviceSn, timeoutSeconds);
if (deviceSn == null || deviceSn.trim().isEmpty()) {
return Result.failed("设备SN不能为空");
}
if (timeoutSeconds < 1 || timeoutSeconds > 120) {
return Result.failed("超时时间必须在1-120秒之间");
}
try {
OneTimeSubscriptionService.DeviceAlarmResult alarmResult =
oneTimeSubscriptionService.subscribeOnce(deviceSn, timeoutSeconds);
DeviceAlarmResponse response = new DeviceAlarmResponse();
response.setDeviceSn(alarmResult.getDeviceSn());
response.setSuccess(alarmResult.isSuccess());
response.setMessage(alarmResult.getMessage());
response.setFireAlarmData(alarmResult.getFireAlarmData());
response.setMsgAlarmData(alarmResult.getMsgAlarmData());
response.setFireAlarmFromCache(alarmResult.isFireAlarmFromCache());
response.setMsgAlarmFromCache(alarmResult.isMsgAlarmFromCache());
if (alarmResult.isSuccess()) {
return Result.succeed(response, "获取成功");
} else {
return Result.succeed(response, "未获取到数据");
}
} catch (Exception e) {
log.error("一次性订阅请求失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
return Result.failed("订阅失败: " + e.getMessage());
}
}
/**
* 从 Redis 缓存获取设备告警数据(不进行实时订阅)
*
* @param deviceSn 设备SN
* @return 缓存的 fire_alarm 和 msg_alarm 数据
*/
@GetMapping("/cache/{deviceSn}")
@Operation(summary = "从缓存获取设备告警数据", description = "仅从 Redis 缓存获取,不进行实时订阅")
public Result<DeviceAlarmResponse> getFromCache(
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
log.info("从缓存获取设备告警数据: deviceSn={}", deviceSn);
if (deviceSn == null || deviceSn.trim().isEmpty()) {
return Result.failed("设备SN不能为空");
}
try {
JSONObject fireAlarmData = alarmDataService.getFireAlarmData(deviceSn);
JSONObject msgAlarmData = alarmDataService.getMsgAlarmData(deviceSn);
DeviceAlarmResponse response = new DeviceAlarmResponse();
response.setDeviceSn(deviceSn);
response.setFireAlarmData(fireAlarmData);
response.setMsgAlarmData(msgAlarmData);
response.setFireAlarmFromCache(fireAlarmData != null);
response.setMsgAlarmFromCache(msgAlarmData != null);
response.setSuccess(fireAlarmData != null || msgAlarmData != null);
response.setMessage(buildCacheResultMessage(fireAlarmData != null, msgAlarmData != null));
return Result.succeed(response);
} catch (Exception e) {
log.error("从缓存获取数据失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
return Result.failed("获取缓存失败: " + e.getMessage());
}
}
/**
* 删除设备告警数据缓存
*
* @param deviceSn 设备SN
* @return 操作结果
*/
@DeleteMapping("/cache/{deviceSn}")
@Operation(summary = "删除设备告警数据缓存", description = "删除 Redis 中指定设备的告警数据缓存")
public Result<Void> deleteCache(
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
log.info("删除设备告警数据缓存: deviceSn={}", deviceSn);
if (deviceSn == null || deviceSn.trim().isEmpty()) {
return Result.failed("设备SN不能为空");
}
try {
alarmDataService.deleteAlarmData(deviceSn);
return Result.succeed(null, "删除成功");
} catch (Exception e) {
log.error("删除缓存失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
return Result.failed("删除缓存失败: " + e.getMessage());
}
}
/**
* 构建缓存结果消息
*/
private String buildCacheResultMessage(boolean hasFireAlarm, boolean hasMsgAlarm) {
if (hasFireAlarm && hasMsgAlarm) {
return "fire_alarm 和 msg_alarm 缓存数据都存在";
} else if (hasFireAlarm) {
return "仅 fire_alarm 缓存数据存在";
} else if (hasMsgAlarm) {
return "仅 msg_alarm 缓存数据存在";
} else {
return "缓存中无数据";
}
}
/**
* 设备告警数据响应
*/
@lombok.Data
public static class DeviceAlarmResponse {
/**
* 设备SN
*/
private String deviceSn;
/**
* 是否成功
*/
private boolean success;
/**
* 结果消息
*/
private String message;
/**
* fire_alarm 数据(机库状态数据)
*/
private JSONObject fireAlarmData;
/**
* msg_alarm 数据(无人机遥测数据)
*/
private JSONObject msgAlarmData;
/**
* fire_alarm 数据是否来自缓存
*/
private boolean fireAlarmFromCache;
/**
* msg_alarm 数据是否来自缓存
*/
private boolean msgAlarmFromCache;
}
}
@@ -0,0 +1,195 @@
package com.central.device.controller;
import com.alibaba.fastjson.JSONObject;
import com.central.common.model.Result;
import com.central.device.websocket.manager.DeviceCommandManager;
import com.central.device.websocket.model.CommandStatus;
import com.central.device.websocket.model.DeviceCommand;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 设备命令控制器
* 提供HTTP接口接收前端命令请求,发送命令到设备
*
* @author lishilin
* @date 2025-01-01
*/
@Slf4j
@RestController
@RequestMapping("/device/command")
@Tag(name = "设备命令控制")
public class DeviceCommandController {
@Autowired
private DeviceCommandManager commandManager;
/**
* 发送设备命令
*/
@Operation(summary = "发送设备命令")
@PostMapping("/send")
public Result<String> sendCommand(@RequestBody SendCommandRequest request) {
log.info("收到设备命令请求: device={}, type={}",
request.getDeviceSn(), request.getCommandType());
try {
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
request.getCommandType(),
request.getParams()
);
return Result.succeed(commandId, "命令已提交");
} catch (Exception e) {
log.error("发送命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 查询命令状态
*/
@Operation(summary = "查询命令状态")
@GetMapping("/status/{commandId}")
public Result<CommandStatusDTO> getCommandStatus(@PathVariable String commandId) {
CommandStatus status = commandManager.getCommandStatus(commandId);
if (status == null) {
return Result.failed("命令不存在");
}
CommandStatusDTO dto = new CommandStatusDTO();
dto.setCommandId(commandId);
dto.setStatus(status.name());
dto.setStatusDesc(getStatusDescription(status));
// 获取命令详情
DeviceCommand command = commandManager.getCommand(commandId);
if (command != null) {
dto.setDeviceSn(command.getDeviceSn());
dto.setCommandType(command.getCommandType());
dto.setCreateTime(command.getCreateTime());
dto.setSendTime(command.getSendTime());
dto.setRetryCount(command.getRetryCount());
dto.setErrorMsg(command.getErrorMsg());
}
return Result.succeed(dto);
}
/**
* 一键起飞
*/
@Operation(summary = "无人机一键起飞")
@PostMapping("/takeoff")
public Result<String> takeoff(@RequestBody TakeoffRequest request) {
log.info("收到起飞命令: device={}, altitude={}", request.getDeviceSn(), request.getAltitude());
try {
JSONObject params = new JSONObject();
params.put("altitude", request.getAltitude() != null ? request.getAltitude() : 50);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"takeoff",
params
);
return Result.succeed(commandId, "起飞命令已发送");
} catch (Exception e) {
log.error("发送起飞命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 一键返航
*/
@Operation(summary = "无人机一键返航")
@PostMapping("/return")
public Result<String> returnHome(@RequestParam String deviceSn) {
log.info("收到返航命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"return_home",
new JSONObject()
);
return Result.succeed(commandId, "返航命令已发送");
} catch (Exception e) {
log.error("发送返航命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 一键降落
*/
@Operation(summary = "无人机一键降落")
@PostMapping("/land")
public Result<String> land(@RequestParam String deviceSn) {
log.info("收到降落命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"land",
new JSONObject()
);
return Result.succeed(commandId, "降落命令已发送");
} catch (Exception e) {
log.error("发送降落命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 获取状态描述
*/
private String getStatusDescription(CommandStatus status) {
return switch (status) {
case PENDING -> "等待发送";
case SENDING -> "发送中";
case SENT -> "已发送,等待设备响应";
case SUCCESS -> "执行成功";
case FAILED -> "执行失败";
case TIMEOUT -> "响应超时";
case EXPIRED -> "命令已过期";
};
}
// ========== DTO类 ==========
@Data
public static class SendCommandRequest {
private String deviceSn;
private String commandType;
private JSONObject params;
}
@Data
public static class TakeoffRequest {
private String deviceSn;
private Integer altitude; // 起飞高度(米)
}
@Data
public static class CommandStatusDTO {
private String commandId;
private String deviceSn;
private String commandType;
private String status;
private String statusDesc;
private Long createTime;
private Long sendTime;
private Integer retryCount;
private String errorMsg;
}
}
@@ -10,11 +10,16 @@ import com.central.device.util.http.Response;
import com.central.device.util.http.SimpleHttpRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@@ -65,4 +70,27 @@ public class ApiTokenController {
}
return Result.failed("请重试");
}
@Operation(summary = "获取OAuth2 Token")
@PostMapping("/oauth2")
public Result getOAuth2Token() throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType,
"grant_type=client_credentials&client_id=WFMfEGS8iHrEPRBH&client_secret=ihat3zHC6T7xPZYFAEnG3tExQiFANd2n");
Request request = new Request.Builder()
.url(jetlinksServiceUrl + "oauth2/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
okhttp3.Response response = client.newCall(request).execute();
if (response.isSuccessful() && response.body() != null) {
String responseBody = response.body().string();
JSONObject jsonObject = JSON.parseObject(responseBody);
return Result.succeed(jsonObject, "获取OAuth2 Token成功");
}
return Result.failed("获取OAuth2 Token失败");
}
}
@@ -0,0 +1,194 @@
package com.central.device.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* 设备告警数据服务
* 负责将 fire_alarm 和 msg_alarm 数据存储到 Redis,并提供查询接口
* 所有订阅场景(一次性订阅、SSE订阅等)都可以复用此服务
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Service
public class DeviceAlarmDataService {
/**
* Redis key 前缀
*/
private static final String FIRE_ALARM_KEY_PREFIX = "device:fire_alarm:";
private static final String MSG_ALARM_KEY_PREFIX = "device:msg_alarm:";
/**
* 数据过期时间(秒)- 默认5分钟
*/
private static final long DATA_EXPIRE_SECONDS = 300;
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 保存 fire_alarm 数据到 Redis
*
* @param deviceSn 设备SN
* @param data 数据(JSONObject)
*/
public void saveFireAlarmData(String deviceSn, JSONObject data) {
if (deviceSn == null || data == null) {
return;
}
try {
String key = FIRE_ALARM_KEY_PREFIX + deviceSn;
String value = data.toJSONString();
stringRedisTemplate.opsForValue().set(key, value, DATA_EXPIRE_SECONDS, TimeUnit.SECONDS);
log.debug("保存 fire_alarm 数据到 Redis: deviceSn={}, dataSize={}", deviceSn, value.length());
} catch (Exception e) {
log.error("保存 fire_alarm 数据到 Redis 失败: deviceSn={}, error={}", deviceSn, e.getMessage());
}
}
/**
* 获取 fire_alarm 数据从 Redis
*
* @param deviceSn 设备SN
* @return 数据(JSONObject),如果不存在返回 null
*/
public JSONObject getFireAlarmData(String deviceSn) {
if (deviceSn == null) {
return null;
}
try {
String key = FIRE_ALARM_KEY_PREFIX + deviceSn;
String value = stringRedisTemplate.opsForValue().get(key);
if (value != null && !value.isEmpty()) {
log.debug("从 Redis 获取 fire_alarm 数据: deviceSn={}", deviceSn);
return JSON.parseObject(value);
}
} catch (Exception e) {
log.error("从 Redis 获取 fire_alarm 数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
}
return null;
}
/**
* 保存 msg_alarm 数据到 Redis
*
* @param deviceSn 设备SN
* @param data 数据(JSONObject)
*/
public void saveMsgAlarmData(String deviceSn, JSONObject data) {
if (deviceSn == null || data == null) {
return;
}
try {
String key = MSG_ALARM_KEY_PREFIX + deviceSn;
String value = data.toJSONString();
stringRedisTemplate.opsForValue().set(key, value, DATA_EXPIRE_SECONDS, TimeUnit.SECONDS);
log.debug("保存 msg_alarm 数据到 Redis: deviceSn={}, dataSize={}", deviceSn, value.length());
} catch (Exception e) {
log.error("保存 msg_alarm 数据到 Redis 失败: deviceSn={}, error={}", deviceSn, e.getMessage());
}
}
/**
* 获取 msg_alarm 数据从 Redis
*
* @param deviceSn 设备SN
* @return 数据(JSONObject),如果不存在返回 null
*/
public JSONObject getMsgAlarmData(String deviceSn) {
if (deviceSn == null) {
return null;
}
try {
String key = MSG_ALARM_KEY_PREFIX + deviceSn;
String value = stringRedisTemplate.opsForValue().get(key);
if (value != null && !value.isEmpty()) {
log.debug("从 Redis 获取 msg_alarm 数据: deviceSn={}", deviceSn);
return JSON.parseObject(value);
}
} catch (Exception e) {
log.error("从 Redis 获取 msg_alarm 数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
}
return null;
}
/**
* 删除设备的告警数据
*
* @param deviceSn 设备SN
*/
public void deleteAlarmData(String deviceSn) {
if (deviceSn == null) {
return;
}
try {
stringRedisTemplate.delete(FIRE_ALARM_KEY_PREFIX + deviceSn);
stringRedisTemplate.delete(MSG_ALARM_KEY_PREFIX + deviceSn);
log.debug("删除设备告警数据: deviceSn={}", deviceSn);
} catch (Exception e) {
log.error("删除设备告警数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
}
}
/**
* 检查是否存在 fire_alarm 数据
*
* @param deviceSn 设备SN
* @return true 如果存在
*/
public boolean hasFireAlarmData(String deviceSn) {
if (deviceSn == null) {
return false;
}
try {
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(FIRE_ALARM_KEY_PREFIX + deviceSn));
} catch (Exception e) {
log.error("检查 fire_alarm 数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
return false;
}
}
/**
* 检查是否存在 msg_alarm 数据
*
* @param deviceSn 设备SN
* @return true 如果存在
*/
public boolean hasMsgAlarmData(String deviceSn) {
if (deviceSn == null) {
return false;
}
try {
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(MSG_ALARM_KEY_PREFIX + deviceSn));
} catch (Exception e) {
log.error("检查 msg_alarm 数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
return false;
}
}
/**
* 刷新数据过期时间
*
* @param deviceSn 设备SN
*/
public void refreshExpireTime(String deviceSn) {
if (deviceSn == null) {
return;
}
try {
stringRedisTemplate.expire(FIRE_ALARM_KEY_PREFIX + deviceSn, DATA_EXPIRE_SECONDS, TimeUnit.SECONDS);
stringRedisTemplate.expire(MSG_ALARM_KEY_PREFIX + deviceSn, DATA_EXPIRE_SECONDS, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("刷新数据过期时间失败: deviceSn={}, error={}", deviceSn, e.getMessage());
}
}
}
@@ -40,5 +40,10 @@ public interface IAgeDeviceService extends ISuperService<AgeDevice> {
* 批量导入设备信息
*/
boolean importDevices(List<AgeDevice> deviceList);
/**
* 根据景区ID查询设备列表
*/
List<AgeDevice> listByScenicId(Long scenicId);
}
@@ -0,0 +1,328 @@
package com.central.device.service;
import com.alibaba.fastjson.JSONObject;
import com.central.device.sse.manager.SseEmitterManager;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.model.SubscriptionTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* 一次性订阅服务
* 用于一次性获取设备的 fire_alarm 和 msg_alarm 数据
* 订阅成功后自动取消订阅并关闭 WebSocket 连接,防止资源浪费
*
* 设计原则:
* 1. 不影响已有的 SSE 订阅(引用计数方式管理)
* 2. msg_alarm 只有无人机开机才有消息,需要容错处理
* 3. 支持只获取到部分数据的情况
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Service
public class OneTimeSubscriptionService {
/**
* 默认订阅超时时间(秒)
*/
private static final int DEFAULT_TIMEOUT_SECONDS = 30;
@Autowired
private JetLinksWebSocketClient webSocketClient;
@Autowired
private DeviceMessageHandler messageHandler;
@Autowired
private DeviceAlarmDataService alarmDataService;
@Autowired(required = false)
private SseEmitterManager sseEmitterManager;
/**
* 一次性订阅获取设备告警数据
* 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅并关闭 WebSocket
*
* @param deviceSn 设备SN
* @return 包含 fire_alarm 和 msg_alarm 数据的结果
*/
public DeviceAlarmResult subscribeOnce(String deviceSn) {
return subscribeOnce(deviceSn, DEFAULT_TIMEOUT_SECONDS);
}
/**
* 一次性订阅获取设备告警数据
* 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅
*
* 注意:
* 1. msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有消息
* 2. 不会无限等待,超时后会尝试从 Redis 获取缓存数据
* 3. 不会影响已有的 SSE 订阅
*
* @param deviceSn 设备SN
* @param timeoutSeconds 超时时间(秒)
* @return 包含 fire_alarm 和 msg_alarm 数据的结果
*/
public DeviceAlarmResult subscribeOnce(String deviceSn, int timeoutSeconds) {
log.info("开始一次性订阅: deviceSn={}, timeout={}s", deviceSn, timeoutSeconds);
DeviceAlarmResult result = new DeviceAlarmResult();
result.setDeviceSn(deviceSn);
// 检查 SSE 是否已有此设备的订阅(用于判断是否需要自己管理订阅)
int sseRefCount = getSseRefCount(deviceSn);
boolean hasSseSubscription = sseRefCount > 0;
// 检查设备是否已在消息处理器中注册
boolean deviceAlreadyRegistered = messageHandler.getDeviceData(deviceSn) != null;
log.info("设备 {} 状态检查: SSE引用计数={}, 已注册={}", deviceSn, sseRefCount, deviceAlreadyRegistered);
// 记录本次订阅新增的主题(用于清理时只取消自己订阅的)
Set<SubscriptionTopic> mySubscribedTopics = new HashSet<>();
// 用于存储回调接收到的数据
AtomicReference<JSONObject> fireAlarmData = new AtomicReference<>();
AtomicReference<JSONObject> msgAlarmData = new AtomicReference<>();
AtomicBoolean fireAlarmReceived = new AtomicBoolean(false);
AtomicBoolean msgAlarmReceived = new AtomicBoolean(false);
// 用于等待数据的 CountDownLatch(只等待1个即可返回,不强制等待全部)
CountDownLatch fireAlarmLatch = new CountDownLatch(1);
CountDownLatch msgAlarmLatch = new CountDownLatch(1);
try {
// 如果设备未注册,先添加设备到消息处理器(确保可以接收消息)
if (!deviceAlreadyRegistered) {
messageHandler.addDevice(deviceSn, null, null);
}
// 注册 fire_alarm 回调
messageHandler.registerFireAlarmCallback(deviceSn, (sn, data) -> {
if (!fireAlarmReceived.getAndSet(true)) {
log.info("一次性订阅收到 fire_alarm 数据: deviceSn={}", sn);
fireAlarmData.set(data);
fireAlarmLatch.countDown();
}
});
// 注册 msg_alarm 回调
messageHandler.registerMsgAlarmCallback(deviceSn, (sn, data) -> {
if (!msgAlarmReceived.getAndSet(true)) {
log.info("一次性订阅收到 msg_alarm 数据: deviceSn={}", sn);
msgAlarmData.set(data);
msgAlarmLatch.countDown();
}
});
// 订阅主题(始终订阅,WebSocket 内部会处理重复订阅)
// 即使 SSE 已订阅,也再次订阅,因为 WebSocket 的 subscribedTopics 会去重
webSocketClient.subscribeDevice(deviceSn,
SubscriptionTopic.EVENT_FIRE_ALARM,
SubscriptionTopic.EVENT_MSG_ALARM);
mySubscribedTopics.add(SubscriptionTopic.EVENT_FIRE_ALARM);
mySubscribedTopics.add(SubscriptionTopic.EVENT_MSG_ALARM);
// 等待 fire_alarm 数据(fire_alarm 是机库数据,通常会有)
boolean fireAlarmCompleted = fireAlarmLatch.await(timeoutSeconds, TimeUnit.SECONDS);
// 等待 msg_alarm 数据(msg_alarm 只有无人机开机才有,给较短时间)
// 如果 fire_alarm 已收到,只再等 5 秒;否则不额外等待
if (fireAlarmCompleted && !msgAlarmReceived.get()) {
log.info("fire_alarm 已收到,额外等待 5 秒获取 msg_alarm: deviceSn={}", deviceSn);
msgAlarmLatch.await(5, TimeUnit.SECONDS);
}
log.info("一次性订阅等待结束: deviceSn={}, fireAlarm={}, msgAlarm={}",
deviceSn, fireAlarmReceived.get(), msgAlarmReceived.get());
// 设置结果
result.setFireAlarmData(fireAlarmData.get());
result.setMsgAlarmData(msgAlarmData.get());
// 如果没有订阅到数据,尝试从 Redis 获取缓存数据
if (result.getFireAlarmData() == null) {
JSONObject cachedFireAlarm = alarmDataService.getFireAlarmData(deviceSn);
if (cachedFireAlarm != null) {
log.info("从 Redis 获取 fire_alarm 缓存数据: deviceSn={}", deviceSn);
result.setFireAlarmData(cachedFireAlarm);
result.setFireAlarmFromCache(true);
}
}
if (result.getMsgAlarmData() == null) {
JSONObject cachedMsgAlarm = alarmDataService.getMsgAlarmData(deviceSn);
if (cachedMsgAlarm != null) {
log.info("从 Redis 获取 msg_alarm 缓存数据: deviceSn={}", deviceSn);
result.setMsgAlarmData(cachedMsgAlarm);
result.setMsgAlarmFromCache(true);
}
}
result.setSuccess(result.getFireAlarmData() != null || result.getMsgAlarmData() != null);
result.setMessage(buildResultMessage(result));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("一次性订阅被中断: deviceSn={}", deviceSn);
result.setSuccess(false);
result.setMessage("订阅被中断");
} catch (Exception e) {
log.error("一次性订阅失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
result.setSuccess(false);
result.setMessage("订阅失败: " + e.getMessage());
} finally {
// 清理:移除回调、取消订阅(如果 SSE 没有订阅的话)
cleanupSubscription(deviceSn, hasSseSubscription, deviceAlreadyRegistered, mySubscribedTopics);
}
return result;
}
/**
* 获取 SSE 对设备的引用计数
*
* @param deviceSn 设备SN
* @return 引用计数,0 表示无订阅
*/
private int getSseRefCount(String deviceSn) {
if (sseEmitterManager == null) {
return 0;
}
try {
return sseEmitterManager.getDeviceRefCount(deviceSn);
} catch (Exception e) {
log.warn("获取 SSE 引用计数失败: deviceSn={}, error={}", deviceSn, e.getMessage());
return 0;
}
}
/**
* 清理订阅资源
* 设计原则:
* 1. 不影响 SSE 已有的订阅(fire_alarm, online, offline)
* 2. msg_alarm 是一次性订阅额外订阅的,需要自己负责取消
* 3. 【重要】一次性订阅和SSE订阅完全独立,一次性订阅不应该影响 deviceDataMap
*
* @param deviceSn 设备SN
* @param hasSseSubscription SSE 是否已有订阅(订阅开始时的状态)
* @param deviceAlreadyRegistered 设备是否在一次性订阅前就已注册
* @param mySubscribedTopics 本次一次性订阅新增的主题
*/
private void cleanupSubscription(String deviceSn, boolean hasSseSubscription,
boolean deviceAlreadyRegistered, Set<SubscriptionTopic> mySubscribedTopics) {
try {
// 【重要】重新检查当前 SSE 引用计数,因为在订阅过程中可能有新的 SSE 连接建立
int currentSseRefCount = getSseRefCount(deviceSn);
boolean currentHasSseSubscription = currentSseRefCount > 0;
log.info("清理一次性订阅资源: deviceSn={}, 订阅开始时SSE状态={}, 当前SSE引用计数={}, deviceAlreadyRegistered={}",
deviceSn, hasSseSubscription, currentSseRefCount, deviceAlreadyRegistered);
// 1. 移除回调(回调是一次性订阅独有的,SSE 不使用)
messageHandler.removeFireAlarmCallback(deviceSn);
messageHandler.removeMsgAlarmCallback(deviceSn);
// 2. 取消订阅(使用当前最新的 SSE 状态来判断)
if (currentHasSseSubscription) {
// SSE 当前有订阅,只取消 msg_alarm(这是一次性订阅额外订阅的)
// SSE 目前只订阅 online, offline, fire_alarm,不订阅 msg_alarm
// 所以 msg_alarm 需要一次性订阅自己负责取消
log.info("SSE 当前有订阅(引用计数={}),只取消 msg_alarm: deviceSn={}", currentSseRefCount, deviceSn);
webSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_MSG_ALARM);
// 不移除设备,因为 SSE 还在使用
} else {
// SSE 当前无订阅,可以安全取消本次订阅的所有主题
if (!mySubscribedTopics.isEmpty()) {
log.info("SSE 当前无订阅,取消本次订阅的主题: deviceSn={}, topics={}", deviceSn, mySubscribedTopics);
webSocketClient.unsubscribeDevice(deviceSn,
mySubscribedTopics.toArray(new SubscriptionTopic[0]));
}
// 【修复】无论设备之前是否注册,只要当前 SSE 无订阅,就应该移除设备
// 因为一次性订阅和 SSE 订阅是独立的,一次性订阅结束后应该清理自己添加的资源
// 原来的逻辑 `!deviceAlreadyRegistered` 会导致:
// - 如果一次性订阅A设备时,A设备已在deviceDataMap中(例如之前SSE订阅过但已断开)
// - 一次性订阅结束后,A设备不会被移除
// - 后续收到A设备的消息时,会打印"收到未订阅设备的状态事件"警告
messageHandler.removeDevice(deviceSn);
log.info("已从 deviceDataMap 移除设备: deviceSn={}", deviceSn);
}
} catch (Exception e) {
log.error("清理订阅资源失败: deviceSn={}, error={}", deviceSn, e.getMessage());
}
}
/**
* 构建结果消息
*
* @param result 结果对象
* @return 消息描述
*/
private String buildResultMessage(DeviceAlarmResult result) {
StringBuilder sb = new StringBuilder();
if (result.getFireAlarmData() != null) {
sb.append("fire_alarm: ").append(result.isFireAlarmFromCache() ? "来自缓存" : "实时订阅");
} else {
sb.append("fire_alarm: 未获取到");
}
sb.append(", ");
if (result.getMsgAlarmData() != null) {
sb.append("msg_alarm: ").append(result.isMsgAlarmFromCache() ? "来自缓存" : "实时订阅");
} else {
sb.append("msg_alarm: 未获取到");
}
return sb.toString();
}
/**
* 设备告警数据结果
*/
@lombok.Data
public static class DeviceAlarmResult {
/**
* 设备SN
*/
private String deviceSn;
/**
* 是否成功(至少获取到一种数据)
*/
private boolean success;
/**
* 结果消息
*/
private String message;
/**
* fire_alarm 数据
*/
private JSONObject fireAlarmData;
/**
* msg_alarm 数据
*/
private JSONObject msgAlarmData;
/**
* fire_alarm 数据是否来自缓存
*/
private boolean fireAlarmFromCache;
/**
* msg_alarm 数据是否来自缓存
*/
private boolean msgAlarmFromCache;
}
}
@@ -88,4 +88,12 @@ public class AgeDeviceServiceImpl extends SuperServiceImpl<AgeDeviceMapper, AgeD
throw new RuntimeException("批量导入设备信息失败", e);
}
}
@Override
public List<AgeDevice> listByScenicId(Long scenicId) {
if (scenicId == null) {
return List.of();
}
return this.list(new QueryWrapper<AgeDevice>().eq("workspace_id", scenicId));
}
}
@@ -0,0 +1,105 @@
package com.central.device.sse.controller;
import com.central.common.context.LoginUserContextHolder;
import com.central.device.sse.manager.SseEmitterManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
/**
* 设备状态SSE控制器(v3.0 - 设备级订阅 + 懒加载)
* 提供SSE端点供前端订阅单个设备实时数据
* 特性:
* 1. 按设备SN订阅,而不是按景区订阅
* 2. 懒加载WebSocket:只有前端调用时才连接WebSocket
* 3. 支持多个客户端订阅同一设备(引用计数)
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@RestController
@RequestMapping("/sse")
@Tag(name = "设备状态SSE接口")
public class DeviceStatusSseController {
@Autowired
private SseEmitterManager sseEmitterManager;
/**
* 订阅单个设备状态实时更新(懒加载模式)
* 前端建立SSE连接时,后端才开始连接WebSocket并订阅该设备
*
* @param deviceSn 设备SN
* @param clientSessionId 客户端会话ID(可选,从请求头获取,用于连接复用和清理)
* @return SSE连接
*/
@Operation(summary = "订阅设备状态实时更新(按设备SN)")
@GetMapping(value = "/device-status/{deviceSn}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public org.springframework.http.ResponseEntity<SseEmitter> subscribeDeviceStatus(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "客户端会话ID(可选)")
@RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) {
String tenantId = LoginUserContextHolder.getCurrentTenantId() != null ? LoginUserContextHolder.getCurrentTenantId() : "1";
String username = LoginUserContextHolder.getUser() != null ? LoginUserContextHolder.getUser().getUsername() : "anonymous";
// 生成sessionId:如果前端提供了clientSessionId,则使用它;否则生成UUID
String sessionId;
if (clientSessionId != null && !clientSessionId.trim().isEmpty()) {
sessionId = clientSessionId + "_" + deviceSn;
log.info("客户端订阅设备状态SSE(复用会话): session={}, deviceSn={}, tenant={}, user={}",
sessionId, deviceSn, tenantId, username);
} else {
sessionId = java.util.UUID.randomUUID().toString() + "_" + deviceSn;
log.info("客户端订阅设备状态SSE(新会话): session={}, deviceSn={}, tenant={}, user={}",
sessionId, deviceSn, tenantId, username);
}
// 添加SSE连接(内部会触发WebSocket懒加载和设备订阅)
// 如果同sessionId已存在连接,会自动断开旧连接
SseEmitter emitter = sseEmitterManager.addEmitter(sessionId, deviceSn, tenantId);
// 设置响应头,禁用缓冲
return org.springframework.http.ResponseEntity.ok()
.header("Cache-Control", "no-cache, no-transform")
.header("Connection", "keep-alive")
.header("X-Accel-Buffering", "no")
.contentType(org.springframework.http.MediaType.TEXT_EVENT_STREAM)
.body(emitter);
}
/**
* 主动断开SSE连接
* 前端页面卸载时调用,确保后端资源及时释放
*
* @param deviceSn 设备SN
* @param clientSessionId 客户端会话ID(必需)
* @return 断开结果
*/
@Operation(summary = "主动断开SSE连接")
@DeleteMapping("/device-status/{deviceSn}")
public org.springframework.http.ResponseEntity<String> disconnectDeviceStatus(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "客户端会话ID", required = true)
@RequestHeader(value = "X-Client-Session-Id") String clientSessionId) {
String sessionId = clientSessionId + "_" + deviceSn;
log.info("客户端主动断开SSE连接: session={}, deviceSn={}", sessionId, deviceSn);
boolean success = sseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
if (success) {
return org.springframework.http.ResponseEntity.ok("连接已断开");
} else {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
}
@@ -0,0 +1,65 @@
package com.central.device.sse.dto;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.model.GpsData;
import lombok.Data;
/**
* 设备实时数据DTO
* 用于SSE推送设备实时数据到前端
*
* @author lishilin
* @date 2025-01-19
*/
@Data
public class DeviceRealtimeDataDTO {
/**
* 设备SN
*/
private String deviceSn;
/**
* 是否在线
*/
private boolean online;
/**
* 温度(°C)
*/
private Double temperature;
/**
* 湿度(%)
*/
private Double humidity;
/**
* 电量百分比
*/
private Integer battery;
/**
* GPS数据
*/
private GpsData gps;
/**
* 飞行模式
*/
private String flightMode;
/**
* 飞行状态
*/
private String flightStatus;
/**
* 时间戳
*/
private long timestamp;
/**
* 原始消息数据
*/
private JSONObject rawData;
}
@@ -0,0 +1,57 @@
package com.central.device.sse.dto;
import lombok.Data;
import java.util.List;
/**
* 景区设备列表DTO
*
* @author lishilin
* @date 2025-01-19
*/
@Data
public class ScenicDeviceListDTO {
/**
* 景区ID
*/
private Long scenicId;
/**
* 景区名称
*/
private String scenicName;
/**
* 设备列表
*/
private List<DeviceInfoDTO> devices;
@Data
public static class DeviceInfoDTO {
/**
* 设备SN
*/
private String deviceSn;
/**
* 设备名称
*/
private String deviceName;
/**
* 设备类型
*/
private String deviceType;
/**
* 是否在线(初始状态为离线)
*/
private boolean online;
/**
* 电量百分比(初始状态为null)
*/
private Integer battery;
}
}
@@ -0,0 +1,330 @@
package com.central.device.sse.manager;
import com.central.device.sse.dto.DeviceRealtimeDataDTO;
import com.central.device.sse.model.EmitterWrapper;
import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.manager.DeviceSubscriptionManager;
import com.central.device.websocket.model.DeviceRealtimeData;
import lombok.extern.slf4j.Slf4j;
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 java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* SSE发射器管理器(v3.0 - 设备级推送 + 懒加载)
* 负责管理前端SSE连接、触发WebSocket懒加载、推送设备实时数据
*
* 主要改进:
* 1. 按设备SN管理连接,而不是按景区
* 2. WebSocket懒加载:只有前端调用时才连接
* 3. 引用计数:支持多个客户端订阅同一设备
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Component
public class SseEmitterManager {
@Autowired
private DeviceSubscriptionManager deviceSubscriptionManager;
@Autowired
private DeviceMessageHandler messageHandler;
/**
* SSE连接池: sessionId -> EmitterWrapper
*/
private final ConcurrentHashMap<String, EmitterWrapper> emitters = new ConcurrentHashMap<>();
/**
* 设备订阅计数: deviceSn -> count(引用计数)
*/
private final ConcurrentHashMap<String, Integer> deviceRefCount = new ConcurrentHashMap<>();
/**
* 心跳执行器
*/
private ScheduledExecutorService heartbeatExecutor;
/**
* 初始化
*/
@PostConstruct
public void init() {
// 设置DeviceMessageHandler的SSE管理器引用(解决循环依赖)
messageHandler.setSseEmitterManager(this);
// 启动心跳
startHeartbeat();
}
/**
* 添加SSE连接(按设备触发WebSocket懒加载和订阅)
*
* @param sessionId 会话ID(含设备SN)
* @param deviceSn 设备SN
* @param tenantId 租户ID
* @return SSE Emitter
*/
public SseEmitter addEmitter(String sessionId, String deviceSn, String tenantId) {
// 检查是否已存在相同sessionId的连接,如果存在则先移除(避免重复连接)
if (emitters.containsKey(sessionId)) {
log.warn("检测到重复连接,sessionId={},先移除旧连接", sessionId);
removeEmitter(sessionId, deviceSn);
}
// 创建SseEmitter(超时时间5分钟,避免僵尸连接)
// 设置合理的超时时间,超时后会自动触发onTimeout回调清理连接
long timeoutMs = 5 * 60 * 1000L; // 5分钟
SseEmitter emitter = new SseEmitter(timeoutMs);
// 设置回调
emitter.onCompletion(() -> {
log.info("SSE连接完成: session={}, deviceSn={}", sessionId, deviceSn);
removeEmitter(sessionId, deviceSn);
});
emitter.onTimeout(() -> {
log.warn("SSE连接超时: session={}, deviceSn={}", sessionId, deviceSn);
removeEmitter(sessionId, deviceSn);
});
emitter.onError((ex) -> {
log.error("SSE连接错误: session={}, deviceSn={}, error={}",
sessionId, deviceSn, ex.getMessage());
removeEmitter(sessionId, deviceSn);
});
// 保存连接(使用deviceSn作为scenicId字段,保持兼容性)
EmitterWrapper wrapper = new EmitterWrapper(emitter, 0L, tenantId, sessionId,deviceSn);
wrapper.setDeviceSn(deviceSn); // 扩展字段
emitters.put(sessionId, wrapper);
log.info("新增SSE连接: session={}, deviceSn={}, tenant={}, 当前连接数: {}",
sessionId, deviceSn, tenantId, emitters.size());
// 立即发送连接确认消息,激活SSE流
try {
emitter.send(SseEmitter.event()
.name("connected")
.data("SSE连接已建立"));
log.info("发送连接确认消息成功: session={}", sessionId);
} catch (Exception e) {
log.error("发送连接确认消息失败: session={}, error={}", sessionId, e.getMessage());
}
// 增加设备引用计数
int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1);
// 关键:如果是首次订阅该设备,触发WebSocket懒加载和设备订阅
if (refCount == 1) {
log.info("设备 {} 首次订阅,触发WebSocket懒加载", deviceSn);
deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId);
} else {
log.info("设备 {} 新增订阅,复用现有连接,当前引用计数: {}", deviceSn, refCount);
}
// 立即推送一次当前设备数据(如果存在)
com.central.device.websocket.model.DeviceRealtimeData currentData = messageHandler.getDeviceData(deviceSn);
if (currentData != null) {
log.info("推送设备 {} 的当前数据到新连接", deviceSn);
sendDeviceDataUpdate(deviceSn, currentData);
} else {
log.info("设备 {} 暂无缓存数据,等待WebSocket消息", deviceSn);
}
return emitter;
}
/**
* 移除SSE连接(减少设备引用计数,必要时取消订阅)
*/
private void removeEmitter(String sessionId, String deviceSn) {
EmitterWrapper wrapper = emitters.remove(sessionId);
if (wrapper == null) {
log.debug("SSE连接不存在,无需移除: session={}, deviceSn={}", sessionId, deviceSn);
return;
}
// 尝试完成emitter(优雅关闭)
try {
wrapper.getEmitter().complete();
} catch (Exception e) {
log.debug("完成SSE连接失败(可能已关闭): session={}, error={}", sessionId, e.getMessage());
}
log.info("移除SSE连接: session={}, deviceSn={}, 剩余连接数: {}",
sessionId, deviceSn, emitters.size());
// 减少设备引用计数
Integer refCount = deviceRefCount.compute(deviceSn, (k, v) -> {
if (v == null || v <= 1) {
return null; // 移除key
}
return v - 1;
});
// 关键:如果引用计数归零,取消设备订阅
if (refCount == null) {
log.info("设备 {} 引用计数归零,取消订阅", deviceSn);
deviceSubscriptionManager.unsubscribeDevice(deviceSn);
} else {
log.info("设备 {} 仍有 {} 个订阅,保持连接", deviceSn, refCount);
}
}
/**
* 主动移除SSE连接(公共方法,供控制器调用)
*
* @param sessionId 会话ID
* @param deviceSn 设备SN
* @return 是否成功移除
*/
public boolean removeEmitterBySessionId(String sessionId, String deviceSn) {
if (!emitters.containsKey(sessionId)) {
log.info("SSE连接不存在: session={}, deviceSn={}", sessionId, deviceSn);
return false;
}
removeEmitter(sessionId, deviceSn);
return true;
}
/**
* 推送设备数据更新(只推送给订阅该设备的连接)
*
* @param deviceSn 设备SN
* @param data 设备实时数据
*/
public void sendDeviceDataUpdate(String deviceSn, DeviceRealtimeData data) {
DeviceRealtimeDataDTO dto = convertToDTO(data);
// log.info("转换为DTO完成,准备发送到设备 {} 的所有SSE连接", deviceSn);
sendToDevice(deviceSn, "device-data-update", dto);
}
/**
* 发送给指定设备的所有连接
*/
private void sendToDevice(String deviceSn, String eventName, Object data) {
List<String> deadEmitters = new ArrayList<>();
// log.info("准备推送到设备: deviceSn={}, 当前所有连接数: {}", deviceSn, emitters.size());
// 打印所有连接的 deviceSn,用于调试
emitters.values().forEach(wrapper -> {
log.info(" 连接详情: session={}, deviceSn={}", wrapper.getSessionId(), wrapper.getDeviceSn());
});
// 找到匹配的连接
List<EmitterWrapper> matchingEmitters = emitters.values().stream()
.filter(wrapper -> {
boolean match = deviceSn.equals(wrapper.getDeviceSn());
return match;
})
.toList();
log.info("找到 {} 个匹配设备 {} 的SSE连接", matchingEmitters.size(), deviceSn);
matchingEmitters.forEach(wrapper -> {
try {
wrapper.getEmitter().send(SseEmitter.event()
.name(eventName)
.data(data));
log.info("✅ SSE推送成功: session={}, event={}, deviceSn={} , data={}",
wrapper.getSessionId(), eventName, deviceSn, data);
} catch (Exception e) {
log.error("❌ SSE推送失败: session={}, event={}, error={}",
wrapper.getSessionId(), eventName, e.getMessage());
deadEmitters.add(wrapper.getSessionId());
}
});
// 清理失败的连接
deadEmitters.forEach(sessionId -> {
EmitterWrapper wrapper = emitters.get(sessionId);
if (wrapper != null) {
removeEmitter(sessionId, wrapper.getDeviceSn());
}
});
}
/**
* 转换为DTO
*/
private DeviceRealtimeDataDTO convertToDTO(DeviceRealtimeData data) {
DeviceRealtimeDataDTO dto = new DeviceRealtimeDataDTO();
dto.setDeviceSn(data.getDeviceSn());
dto.setOnline(data.isOnline());
dto.setBattery(data.getBattery());
dto.setTemperature(data.getTemperature());
dto.setHumidity(data.getHumidity());
dto.setGps(data.getGps());
dto.setFlightMode(data.getFlightMode());
dto.setFlightStatus(data.getFlightStatus());
dto.setTimestamp(data.getLastMessageTime());
dto.setRawData(data.getRawData());
return dto;
}
/**
* 启动心跳
*/
private void startHeartbeat() {
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
heartbeatExecutor.scheduleAtFixedRate(() -> {
if (emitters.isEmpty()) {
return;
}
log.debug("发送SSE心跳,当前连接数: {}", emitters.size());
List<String> deadEmitters = new ArrayList<>();
emitters.forEach((sessionId, wrapper) -> {
try {
wrapper.getEmitter().send(SseEmitter.event()
.name("heartbeat")
.data("ping"));
} catch (Exception e) {
log.warn("SSE心跳发送失败: session={}, error={}", sessionId, e.getMessage());
deadEmitters.add(sessionId);
}
});
// 清理失败的连接
deadEmitters.forEach(sessionId -> {
EmitterWrapper wrapper = emitters.get(sessionId);
if (wrapper != null) {
removeEmitter(sessionId, wrapper.getDeviceSn());
}
});
}, 30000, 30000, TimeUnit.MILLISECONDS); // 每30秒发送一次心跳
log.info("SSE心跳已启动,间隔: 30秒");
}
/**
* 获取连接数
*/
public int getConnectionCount() {
return emitters.size();
}
/**
* 获取设备订阅数(引用计数)
*/
public int getDeviceRefCount(String deviceSn) {
return deviceRefCount.getOrDefault(deviceSn, 0);
}
}
@@ -0,0 +1,40 @@
package com.central.device.sse.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
/**
* SSE连接包装器
*
* @author lishilin
* @date 2025-01-01
*/
@Data
@AllArgsConstructor
public class EmitterWrapper {
/**
* SSE发射器
*/
private SseEmitter emitter;
/**
* 景区ID(保留字段,兼容旧版)
*/
private Long scenicId;
/**
* 租户ID
*/
private String tenantId;
/**
* 会话ID
*/
private String sessionId;
/**
* 设备SN(新增字段,v3.0)
*/
private String deviceSn;
}
@@ -0,0 +1,623 @@
package com.central.device.websocket.client;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.config.WebSocketProperties;
import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.manager.TokenManager;
import com.central.device.websocket.model.SubscriptionMessage;
import com.central.device.websocket.model.SubscriptionTopic;
import lombok.extern.slf4j.Slf4j;
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.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* JetLinks平台WebSocket客户端(全局单例)
* 使用主题订阅模式,所有设备共享一个WebSocket连接
* 基于Spring WebSocket实现
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Component
public class JetLinksWebSocketClient extends TextWebSocketHandler {
private final WebSocketProperties properties;
private final TokenManager tokenManager;
private final DeviceMessageHandler messageHandler;
private final StandardWebSocketClient webSocketClient;
/**
* 命令管理器(延迟注入,避免循环依赖)
*/
private Object commandManager;
/**
* 当前订阅的主题列表
*/
private final Set<String> subscribedTopics = new HashSet<>();
/**
* WebSocket会话
*/
private volatile WebSocketSession session;
/**
* 重连次数
*/
private int reconnectAttempts = 0;
/**
* 手动关闭标志
*/
private volatile boolean isManualClose = false;
/**
* 自动关闭标志(无订阅时自动断开,不应重连)
*/
private volatile boolean isAutoClose = false;
/**
* 连接状态
*/
private volatile boolean isConnected = false;
/**
* 心跳执行器
*/
private ScheduledExecutorService heartbeatExecutor;
/**
* 重连执行器
*/
private ScheduledExecutorService reconnectExecutor;
/**
* 构造函数
*/
public JetLinksWebSocketClient(WebSocketProperties properties,
TokenManager tokenManager,
DeviceMessageHandler messageHandler) {
this.properties = properties;
this.tokenManager = tokenManager;
this.messageHandler = messageHandler;
this.webSocketClient = new StandardWebSocketClient();
}
/**
* 初始化(仅初始化线程池,不自动连接)
*/
@PostConstruct
public void init() {
log.info("初始化JetLinks WebSocket客户端(懒加载模式)");
reconnectExecutor = Executors.newSingleThreadScheduledExecutor();
}
/**
* 手动连接WebSocket(按需连接)
*/
public synchronized void connect() {
// 如果已连接,直接返回
if (isConnected()) {
log.debug("WebSocket已连接,跳过重复连接");
return;
}
try {
String token = tokenManager.getValidToken();
String url = properties.getConnection().getBaseUrl() + "/" + token;
log.info("连接WebSocket: {}", url);
session = webSocketClient.execute(this, url).get();
} catch (Exception e) {
log.error("WebSocket连接失败: {}", e.getMessage(), e);
scheduleReconnect();
}
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
log.info("WebSocket连接成功");
this.session = session;
this.isConnected = true;
this.reconnectAttempts = 0;
this.isAutoClose = false; // 重置自动关闭标志
// 启动心跳
startHeartbeat();
// 重新订阅之前的主题
resubscribeAll();
// 处理命令队列
if (commandManager != null) {
try {
commandManager.getClass()
.getMethod("onWebSocketReconnected")
.invoke(commandManager);
} catch (Exception e) {
log.warn("调用命令管理器失败: {}", e.getMessage());
}
}
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
try {
String payload = message.getPayload();
// log.info("收到WebSocket消息: length={}, payload={}", payload.length(), payload);
JSONObject json = JSON.parseObject(payload);
String type = json.getString("type");
// 处理心跳响应
if ("pong".equals(type)) {
log.debug("收到心跳响应: pong");
return;
}
// 处理认证错误
if ("authError".equals(type)) {
handleAuthError(json);
return;
}
// 处理订阅结果(包括各种消息类型)
// JetLinks返回的消息可能是:result、event、property等
if ("result".equals(type) || json.containsKey("requestId")) {
handleSubscriptionResult(json);
return;
}
// 处理其他消息
log.warn("收到未知类型消息: type={}, payload={}", type, payload);
} catch (Exception e) {
log.error("处理WebSocket消息失败: {}", e.getMessage(), e);
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
log.warn("WebSocket连接关闭: code={}, reason={}, isAutoClose={}, isManualClose={}",
status.getCode(), status.getReason(), isAutoClose, isManualClose);
this.isConnected = false;
this.session = null;
stopHeartbeat();
// 如果是自动关闭(无订阅),不重连
if (isAutoClose) {
log.info("WebSocket因无订阅自动关闭,不触发重连");
isAutoClose = false; // 重置标志
return;
}
// 如果不是手动关闭,则尝试重连
if (!isManualClose && properties.getReconnect().isEnabled()) {
scheduleReconnect();
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
log.error("WebSocket连接异常: {}", exception.getMessage());
}
/**
* 处理认证错误
*/
private void handleAuthError(JSONObject json) {
String message = json.getString("message");
log.error("认证失败: {}", message);
// Token过期,刷新Token后重连
try {
log.info("Token已过期,刷新Token后重连...");
tokenManager.refreshToken();
// 关闭当前连接
if (session != null && session.isOpen()) {
session.close();
}
// 重新连接
scheduleReconnect();
} catch (Exception e) {
log.error("刷新Token失败: {}", e.getMessage(), e);
}
}
/**
* 处理订阅结果
*/
private void handleSubscriptionResult(JSONObject json) {
String topic = json.getString("topic");
// 从topic中提取deviceSn
String deviceSn = extractDeviceSn(topic);
if (deviceSn == null) {
log.warn("无法从topic提取deviceSn: {}", topic);
return;
}
// 【重要】检查该主题是否仍在订阅列表中
// 如果已经取消订阅,忽略延迟到达的消息,避免产生警告日志
if (!subscribedTopics.contains(topic)) {
log.debug("忽略已取消订阅主题的延迟消息: topic={}, deviceSn={}", topic, deviceSn);
return;
}
// 根据topic类型处理消息
if (topic.contains("/online")) {
// 设备上线
log.info("处理设备上线: deviceSn={}", deviceSn);
messageHandler.markDeviceOnline(deviceSn);
} else if (topic.contains("/offline")) {
// 设备离线
log.info("处理设备离线: deviceSn={}", deviceSn);
messageHandler.markDeviceOffline(deviceSn);
} else if (topic.contains("/message/property/report")) {
// 设备属性上报 - 使用专用处理方法
log.info("处理属性上报: deviceSn={}", deviceSn);
messageHandler.handlePropertyReport(deviceSn, json.toJSONString());
} else if (topic.contains("/message/event/fire_alarm")) {
// 设备状态事件上报 - 使用专用处理方法
log.info("处理fire_alarm事件: deviceSn={}", deviceSn);
messageHandler.handleDeviceStateEvent(deviceSn, json.toJSONString());
} else if (topic.contains("/message/event/msg_alarm")) {
// 无人机遥测数据事件 - 使用专用处理方法
log.info("处理msg_alarm事件: deviceSn={}", deviceSn);
messageHandler.handleMsgAlarmEvent(deviceSn, json.toJSONString());
} else {
log.warn("其他类型消息: topic={}, json={}", topic, json.toJSONString());
}
}
/**
* 从topic中提取deviceSn
* topic格式: /device/D-Dock2/{deviceSn}/...
*/
private String extractDeviceSn(String topic) {
if (topic == null || !topic.startsWith("/device/D-Dock2/")) {
return null;
}
String[] parts = topic.split("/");
if (parts.length >= 4) {
return parts[3];
}
return null;
}
/**
* 订阅设备指定主题(按需连接 + 按需订阅)
*
* @param deviceSn 设备SN
* @param topics 要订阅的主题列表(可变参数)
*/
public void subscribeDevice(String deviceSn, SubscriptionTopic... topics) {
if (topics == null || topics.length == 0) {
log.warn("未指定订阅主题,跳过订阅: device={}", deviceSn);
return;
}
// 如果未连接,先建立连接
if (!isConnected()) {
log.info("WebSocket未连接,自动建立连接后订阅设备: {}", deviceSn);
connect();
// 等待连接建立(最多等待5秒)
int waitCount = 0;
while (!isConnected() && waitCount < 50) {
try {
Thread.sleep(100);
waitCount++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("等待连接被中断");
return;
}
}
if (!isConnected()) {
log.error("WebSocket连接超时,无法订阅设备: {}", deviceSn);
return;
}
}
log.info("订阅设备: device={}, topics={}", deviceSn, topics);
// 订阅指定的主题
for (SubscriptionTopic topic : topics) {
subscribeTopic(topic, deviceSn);
}
}
/**
* 取消订阅设备指定主题
*
* @param deviceSn 设备SN
* @param topics 要取消订阅的主题列表(可变参数)
*/
public void unsubscribeDevice(String deviceSn, SubscriptionTopic... topics) {
if (!isConnected()) {
log.warn("WebSocket未连接,无法取消订阅: {}", deviceSn);
return;
}
if (topics == null || topics.length == 0) {
log.warn("未指定取消订阅主题,跳过: device={}", deviceSn);
return;
}
log.info("取消订阅设备: device={}, topics={}", deviceSn, topics);
// 取消订阅指定的主题
for (SubscriptionTopic topic : topics) {
unsubscribeTopic(topic, deviceSn);
}
// 检查是否所有订阅都已取消,如果是则断开WebSocket连接以节省资源
if (subscribedTopics.isEmpty()) {
log.info("所有设备订阅已取消,自动断开WebSocket连接以节省资源");
closeConnection();
}
}
/**
* 订阅主题
*/
private void subscribeTopic(SubscriptionTopic topicEnum, String deviceSn) {
String topic = topicEnum.getTopic(deviceSn);
SubscriptionMessage message = SubscriptionMessage.builder()
.type("sub")
.topic(topic)
.parameter(new JSONObject())
.id("request-id-" + UUID.randomUUID().toString())
.build();
send(JSON.toJSONString(message));
subscribedTopics.add(topic);
log.info("发送订阅消息: topic={}, id={}, message={}", topic, message.getId(), JSON.toJSONString(message));
}
/**
* 取消订阅主题
*/
private void unsubscribeTopic(SubscriptionTopic topicEnum, String deviceSn) {
String topic = topicEnum.getTopic(deviceSn);
// 检查该主题是否确实在订阅列表中
if (!subscribedTopics.contains(topic)) {
log.warn("取消订阅主题时发现该主题不在订阅列表中: topic={}, deviceSn={}", topic, deviceSn);
return;
}
SubscriptionMessage message = SubscriptionMessage.builder()
.type("unsub")
.topic(topic)
.parameter(new JSONObject())
.id("request-id-" + UUID.randomUUID().toString())
.build();
send(JSON.toJSONString(message));
subscribedTopics.remove(topic);
log.info("取消订阅主题: topic={}, id={}, 剩余订阅数: {}, 剩余主题: {}",
topic, message.getId(), subscribedTopics.size(), subscribedTopics);
}
/**
* 重新订阅所有主题
*/
private void resubscribeAll() {
if (subscribedTopics.isEmpty()) {
log.info("没有需要重新订阅的主题");
return;
}
log.info("重新订阅 {} 个主题", subscribedTopics.size());
Set<String> topics = new HashSet<>(subscribedTopics);
subscribedTopics.clear();
// 按设备分组重新订阅(订阅所有标准主题)
Set<String> deviceSns = new HashSet<>();
topics.forEach(topic -> {
String deviceSn = extractDeviceSn(topic);
if (deviceSn != null) {
deviceSns.add(deviceSn);
}
});
// 为每个设备重新订阅标准主题(只订阅关键主题)
deviceSns.forEach(deviceSn -> {
subscribeDevice(deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm最重要
);
});
}
/**
* 发送消息
*/
public void send(String message) {
if (session != null && session.isOpen()) {
try {
session.sendMessage(new TextMessage(message));
} catch (Exception e) {
log.error("发送消息失败: {}", e.getMessage(), e);
}
} else {
log.warn("WebSocket未连接,无法发送消息");
}
}
/**
* 计划重连
*/
private void scheduleReconnect() {
int maxAttempts = properties.getReconnect().getMaxAttempts();
if (maxAttempts > 0 && reconnectAttempts >= maxAttempts) {
log.error("重连次数超限({}), 停止重连", maxAttempts);
return;
}
reconnectAttempts++;
// 计算重连延迟(指数退避)
long delay = Math.min(
(long) Math.pow(properties.getReconnect().getMultiplier(), reconnectAttempts - 1)
* properties.getReconnect().getInitialDelay(),
properties.getReconnect().getMaxDelay()
);
log.info("准备重连 (尝试 {}/{}), 延迟: {}ms",
reconnectAttempts, maxAttempts > 0 ? maxAttempts : "∞", delay);
reconnectExecutor.schedule(this::connect, delay, TimeUnit.MILLISECONDS);
}
/**
* 启动心跳
*/
private void startHeartbeat() {
if (!properties.getHeartbeat().isEnabled()) {
return;
}
if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
return;
}
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
heartbeatExecutor.scheduleAtFixedRate(
this::sendHeartbeat,
properties.getHeartbeat().getInterval(),
properties.getHeartbeat().getInterval(),
TimeUnit.MILLISECONDS
);
log.debug("心跳已启动,间隔: {}ms", properties.getHeartbeat().getInterval());
}
/**
* 停止心跳
*/
private void stopHeartbeat() {
if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
heartbeatExecutor.shutdown();
log.debug("心跳已停止");
}
}
/**
* 发送心跳
*/
private void sendHeartbeat() {
if (isConnected && session != null && session.isOpen()) {
try {
JSONObject heartbeat = new JSONObject();
heartbeat.put("type", "ping");
heartbeat.put("timestamp", System.currentTimeMillis());
send(heartbeat.toJSONString());
log.debug("发送心跳");
} catch (Exception e) {
log.warn("发送心跳失败: {}", e.getMessage());
}
}
}
/**
* 关闭连接(内部使用,用于无订阅时自动断开)
*/
private void closeConnection() {
log.info("关闭WebSocket连接(无活跃订阅)");
stopHeartbeat();
// 设置自动关闭标志,防止触发重连
this.isAutoClose = true;
if (session != null && session.isOpen()) {
try {
session.close();
} catch (Exception e) {
log.error("关闭连接失败: {}", e.getMessage());
}
}
this.isConnected = false;
this.session = null;
}
/**
* 手动关闭连接(外部调用,应用停止时使用)
*/
public void closeManually() {
log.info("手动关闭WebSocket连接");
isManualClose = true;
stopHeartbeat();
if (reconnectExecutor != null) {
reconnectExecutor.shutdown();
}
if (session != null && session.isOpen()) {
try {
session.close();
} catch (Exception e) {
log.error("关闭连接失败: {}", e.getMessage());
}
}
}
/**
* 检查连接状态
*/
public boolean isConnected() {
return isConnected && session != null && session.isOpen();
}
/**
* 获取当前订阅数
*/
public int getSubscriptionCount() {
return subscribedTopics.size();
}
/**
* 设置命令管理器(延迟注入,避免循环依赖)
*/
public void setCommandManager(Object commandManager) {
this.commandManager = commandManager;
}
/**
* 销毁
*/
@PreDestroy
public void destroy() {
closeManually();
}
}
@@ -0,0 +1,188 @@
package com.central.device.websocket.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* WebSocket配置属性
*
* @author lishilin
* @date 2025-01-01
*/
@Data
@Component
@ConfigurationProperties(prefix = "device.websocket")
public class WebSocketProperties {
/**
* OAuth2配置
*/
private OAuth2Config oauth2 = new OAuth2Config();
/**
* 连接配置
*/
private ConnectionConfig connection = new ConnectionConfig();
/**
* 心跳配置
*/
private HeartbeatConfig heartbeat = new HeartbeatConfig();
/**
* 重连配置
*/
private ReconnectConfig reconnect = new ReconnectConfig();
/**
* 订阅配置
*/
private SubscribeConfig subscribe = new SubscribeConfig();
/**
* 超时配置
*/
private TimeoutConfig timeout = new TimeoutConfig();
/**
* 命令配置
*/
private CommandConfig command = new CommandConfig();
@Data
public static class OAuth2Config {
/**
* Token获取URL
*/
private String tokenUrl = "http://119.45.169.13:8848/oauth2/token";
/**
* 客户端ID
*/
private String clientId = "WFMfEGS8iHrEPRBH";
/**
* 客户端密钥
*/
private String clientSecret = "ihat3zHC6T7xPZYFAEnG3tExQiFANd2n";
}
@Data
public static class ConnectionConfig {
/**
* WebSocket基础URL
*/
private String baseUrl = "ws://119.45.169.13:8848/device";
/**
* 连接超时(ms)
*/
private int connectTimeout = 10000;
/**
* 读取超时(ms)
*/
private int readTimeout = 60000;
}
@Data
public static class HeartbeatConfig {
/**
* 是否启用心跳
*/
private boolean enabled = true;
/**
* 心跳间隔(ms)
*/
private int interval = 30000;
}
@Data
public static class ReconnectConfig {
/**
* 是否启用重连
*/
private boolean enabled = true;
/**
* 最大重连次数(0=无限)
*/
private int maxAttempts = 10;
/**
* 初始延迟(ms)
*/
private int initialDelay = 2000;
/**
* 最大延迟(ms)
*/
private int maxDelay = 60000;
/**
* 延迟倍数
*/
private int multiplier = 2;
}
@Data
public static class SubscribeConfig {
/**
* 每批订阅数量
*/
private int batchSize = 50;
/**
* 批次间隔(ms)
*/
private int batchInterval = 500;
/**
* 是否按需订阅
*/
private boolean onDemand = true;
}
@Data
public static class TimeoutConfig {
/**
* 设备离线判定阈值(ms)
*/
private long offlineThreshold = 60000;
/**
* 超时检查间隔(ms)
*/
private long checkInterval = 10000;
}
@Data
public static class CommandConfig {
/**
* 命令默认超时时间(ms)
*/
private long defaultTimeout = 60000;
/**
* 最大重试次数
*/
private int maxRetry = 3;
/**
* 重试基础延迟(ms)
*/
private long retryDelayBase = 1000;
/**
* 每个设备命令队列最大长度
*/
private int queueMaxSize = 100;
/**
* 过期命令清理间隔(ms)
*/
private long cleanupInterval = 10000;
}
}
@@ -0,0 +1,802 @@
package com.central.device.websocket.handler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.device.service.DeviceAlarmDataService;
import com.central.device.websocket.model.DeviceRealtimeData;
import com.central.device.websocket.model.GpsData;
import com.central.device.websocket.model.message.DeviceStateEventMessage;
import com.central.device.websocket.model.message.PropertyReportMessage;
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 java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
/**
* 设备消息处理器(v2.0)
* 负责接收设备WebSocket消息,解析并更新设备实时数据到内存Map
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Component
public class DeviceMessageHandler {
/**
* 设备实时数据Map: deviceSn -> DeviceRealtimeData
* 存储所有订阅设备的实时数据
*/
private final ConcurrentHashMap<String, DeviceRealtimeData> deviceDataMap = new ConcurrentHashMap<>();
/**
* 设备数据缓存:存储三种类型的原始dockData
* deviceSn -> [type1Data, type2Data, type3Data]
* type1: 飞行任务数据(wireless_link等)
* type2: 机库综合数据(latitude, drone_charge_state, sub_device等)
* type3: 机库状态数据(drone_battery_maintenance_info, electric_supply_voltage等)
*/
private final ConcurrentHashMap<String, JSONObject[]> deviceDataCache = new ConcurrentHashMap<>();
/**
* msg_alarm 数据缓存:存储最新的无人机遥测数据
* deviceSn -> msgAlarmData
*/
private final ConcurrentHashMap<String, JSONObject> msgAlarmDataCache = new ConcurrentHashMap<>();
/**
* fire_alarm 回调监听器(用于一次性订阅)
* deviceSn -> callback
*/
private final ConcurrentHashMap<String, BiConsumer<String, JSONObject>> fireAlarmCallbacks = new ConcurrentHashMap<>();
/**
* msg_alarm 回调监听器(用于一次性订阅)
* deviceSn -> callback
*/
private final ConcurrentHashMap<String, BiConsumer<String, JSONObject>> msgAlarmCallbacks = new ConcurrentHashMap<>();
/**
* 最近取消订阅的设备列表(用于抑制取消订阅后短时间内收到的消息警告)
* deviceSn -> 取消订阅的时间戳
* 设备取消订阅后,可能仍会收到少量延迟消息,此Map用于避免打印误导性警告
*/
private final ConcurrentHashMap<String, Long> recentlyUnsubscribedDevices = new ConcurrentHashMap<>();
/**
* 取消订阅后抑制警告的时间窗口(毫秒)
*/
private static final long UNSUBSCRIBE_GRACE_PERIOD_MS = 5000; // 5秒
/**
* SSE管理器(延迟注入)
*/
private Object sseEmitterManager;
/**
* 告警数据服务(用于Redis存储)
*/
@Autowired(required = false)
private DeviceAlarmDataService alarmDataService;
/**
* 设置SSE管理器
*/
public void setSseEmitterManager(Object sseEmitterManager) {
this.sseEmitterManager = sseEmitterManager;
}
/**
* 处理设备消息(已废弃,使用专用方法)
*
* @param deviceSn 设备SN
* @param message 消息内容
* @deprecated 使用 {@link #handlePropertyReport}
*/
@Deprecated
public void handleDeviceMessage(String deviceSn, String message) {
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data == null) {
if (isInUnsubscribeGracePeriod(deviceSn)) {
log.debug("忽略已取消订阅设备的延迟消息: deviceSn={}", deviceSn);
} else {
log.warn("收到未订阅设备的消息: {}", deviceSn);
}
return;
}
try {
// 解析消息
JSONObject json = JSON.parseObject(message);
// 更新基础状态
data.setOnline(true);
data.setLastMessageTime(System.currentTimeMillis());
// 解析设备数据(根据实际消息格式调整)
if (json.containsKey("temperature")) {
data.setTemperature(json.getDouble("temperature"));
}
if (json.containsKey("humidity")) {
data.setHumidity(json.getDouble("humidity"));
}
if (json.containsKey("battery")) {
data.setBattery(json.getInteger("battery"));
}
if (json.containsKey("flightMode")) {
data.setFlightMode(json.getString("flightMode"));
}
if (json.containsKey("flightStatus")) {
data.setFlightStatus(json.getString("flightStatus"));
}
// 解析GPS数据
if (json.containsKey("gps")) {
JSONObject gpsJson = json.getJSONObject("gps");
GpsData gps = new GpsData();
gps.setLatitude(gpsJson.getDouble("latitude"));
gps.setLongitude(gpsJson.getDouble("longitude"));
gps.setAltitude(gpsJson.getDouble("altitude"));
data.setGps(gps);
}
// 保存原始数据
data.setRawData(json);
log.debug("更新设备 {} 数据: online={}, battery={}, temp={}",
deviceSn, data.isOnline(), data.getBattery(), data.getTemperature());
// 推送到前端(通过SSE)
pushDeviceDataUpdate(data);
} catch (Exception e) {
log.error("解析设备消息失败: deviceSn={}, error={}", deviceSn, e.getMessage());
}
}
/**
* 处理设备属性上报消息
*
* @param deviceSn 设备SN
* @param message 消息内容(JSON字符串)
*/
public void handlePropertyReport(String deviceSn, String message) {
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data == null) {
if (isInUnsubscribeGracePeriod(deviceSn)) {
log.debug("忽略已取消订阅设备的延迟属性上报: deviceSn={}", deviceSn);
} else {
log.warn("收到未订阅设备的属性上报: {}", deviceSn);
}
return;
}
try {
// 解析属性上报消息
PropertyReportMessage propertyMsg = JSON.parseObject(message, PropertyReportMessage.class);
PropertyReportMessage.Payload payload = propertyMsg.getPayload();
if (payload == null) {
log.warn("属性上报消息载荷为空: deviceSn={}", deviceSn);
return;
}
// 更新基础状态
data.setOnline(true);
data.setLastMessageTime(payload.getTimestamp() != null ? payload.getTimestamp() : System.currentTimeMillis());
// 解析属性数据
JSONObject properties = payload.getProperties();
if (properties != null) {
// 根据实际属性字段更新设备数据
if (properties.containsKey("temperature")) {
data.setTemperature(properties.getDouble("temperature"));
}
if (properties.containsKey("humidity")) {
data.setHumidity(properties.getDouble("humidity"));
}
if (properties.containsKey("battery")) {
data.setBattery(properties.getInteger("battery"));
}
if (properties.containsKey("flightMode")) {
data.setFlightMode(properties.getString("flightMode"));
}
if (properties.containsKey("flightStatus")) {
data.setFlightStatus(properties.getString("flightStatus"));
}
// 解析GPS数据
if (properties.containsKey("gps")) {
JSONObject gpsJson = properties.getJSONObject("gps");
GpsData gps = new GpsData();
gps.setLatitude(gpsJson.getDouble("latitude"));
gps.setLongitude(gpsJson.getDouble("longitude"));
gps.setAltitude(gpsJson.getDouble("altitude"));
data.setGps(gps);
}
// 保存原始属性数据
data.setRawData(properties);
}
log.debug("处理设备属性上报: deviceSn={}, messageId={}", deviceSn, payload.getMessageId());
// 推送到前端(通过SSE)
pushDeviceDataUpdate(data);
} catch (Exception e) {
log.error("解析属性上报消息失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
}
}
/**
* 处理设备状态事件消息(fire_alarm 事件)
* 注意:fire_alarm 不是火警告警,而是设备状态事件上报,用于获取设备完整状态信息
*
* 数据缓存合并策略:
* fire_alarm事件会循环推送三种不同结构的数据:
* 1. 飞行任务数据(wireless_link, sdr, tilt_angle等)
* 2. 机库和无人机综合数据(最完整,包含drone_charge_state, sub_device等)
* 3. 机库状态数据(drone_battery_maintenance_info, electric_supply_voltage等)
*
* 策略:
* - 为每个设备缓存三种类型的数据
* - 收到新数据时,更新对应类型的缓存
* - 合并三种缓存后再推送,确保数据完整性
* - 如果某种类型没有收到,使用上次缓存的数据
*
* @param deviceSn 设备SN
* @param message 消息内容(JSON字符串)
*/
public void handleDeviceStateEvent(String deviceSn, String message) {
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data == null) {
// 检查是否是刚刚取消订阅的设备(宽限期内的延迟消息)
if (isInUnsubscribeGracePeriod(deviceSn)) {
log.debug("忽略已取消订阅设备的延迟消息: deviceSn={}", deviceSn);
} else {
log.warn("收到未订阅设备的状态事件: deviceSn={}, deviceDataMap中的设备列表: {}",
deviceSn, deviceDataMap.keySet());
}
return;
}
try {
// 直接解析原始JSON,避免通过对象转换丢失字段信息
JSONObject msgJson = JSON.parseObject(message);
JSONObject payload = msgJson.getJSONObject("payload");
if (payload == null || payload.getJSONObject("data") == null) {
log.warn("设备状态事件消息载荷为空: deviceSn={}", deviceSn);
return;
}
JSONObject eventData = payload.getJSONObject("data");
JSONObject newDockData = eventData.getJSONObject("data");
Long timestamp = eventData.getLong("timestamp");
String messageId = payload.getString("messageId");
// 更新基础状态
data.setOnline(true);
data.setLastMessageTime(timestamp != null ? timestamp : System.currentTimeMillis());
if (newDockData != null && !newDockData.isEmpty()) {
// 判断数据类型并更新对应缓存
int dataType = identifyDataType(newDockData);
// 初始化设备缓存(三种类型)
deviceDataCache.computeIfAbsent(deviceSn, k -> new JSONObject[3]);
JSONObject[] cache = deviceDataCache.get(deviceSn);
// 更新对应类型的缓存
if (dataType >= 0 && dataType < 3 && !newDockData.isEmpty()) {
cache[dataType] = newDockData;
log.debug("更新设备 {} 的第{}种数据缓存,字段数={}", deviceSn, dataType + 1, newDockData.size());
} else if (dataType == -1 && !newDockData.isEmpty()) {
log.warn("设备 {} 收到未识别类型的数据,字段数: {}", deviceSn, newDockData.size());
}
// 检查三种数据是否都已缓存
boolean allCached = cache[0] != null && !cache[0].isEmpty()
&& cache[1] != null && !cache[1].isEmpty()
&& cache[2] != null && !cache[2].isEmpty();
if (!allCached) {
// 三种数据未齐全,不推送SSE,等待数据收集完整
log.debug("设备 {} 数据未齐全,等待收集完整: type1={}, type2={}, type3={}",
deviceSn,
cache[0] != null && !cache[0].isEmpty(),
cache[1] != null && !cache[1].isEmpty(),
cache[2] != null && !cache[2].isEmpty());
return;
}
// 三种数据都齐全了,合并并推送
log.info("设备 {} 三种数据已齐全,开始合并推送", deviceSn);
// 合并三种缓存数据
JSONObject mergedDockData = mergeAllCaches(cache);
// 从合并后的数据中提取关键字段
extractKeyFields(data, mergedDockData);
// 保存合并后的完整设备状态数据
JSONObject rawData = new JSONObject();
rawData.put("eventType", "device_state");
rawData.put("messageId", messageId);
rawData.put("timestamp", timestamp);
rawData.put("dockData", mergedDockData);
data.setRawData(rawData);
// 保存到 Redis(公用存储)
if (alarmDataService != null) {
alarmDataService.saveFireAlarmData(deviceSn, rawData);
}
// 触发 fire_alarm 回调(用于一次性订阅)
BiConsumer<String, JSONObject> fireAlarmCallback = fireAlarmCallbacks.get(deviceSn);
if (fireAlarmCallback != null) {
try {
fireAlarmCallback.accept(deviceSn, rawData);
} catch (Exception callbackEx) {
log.error("fire_alarm 回调执行失败: deviceSn={}, error={}", deviceSn, callbackEx.getMessage());
}
}
// 推送到前端(通过SSE)
pushDeviceDataUpdate(data);
}
} catch (Exception e) {
log.error("解析设备状态事件消息失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
}
}
/**
* 处理无人机遥测数据事件(msg_alarm 事件)
* 包含无人机飞行状态、电池、GPS、相机等完整遥测数据
*
* @param deviceSn 设备SN
* @param message 消息内容(JSON字符串)
*/
public void handleMsgAlarmEvent(String deviceSn, String message) {
try {
// 直接解析原始JSON
JSONObject msgJson = JSON.parseObject(message);
JSONObject payload = msgJson.getJSONObject("payload");
if (payload == null || payload.getJSONObject("data") == null) {
log.warn("msg_alarm 消息载荷为空: deviceSn={}", deviceSn);
return;
}
JSONObject eventData = payload.getJSONObject("data");
JSONObject droneData = eventData.getJSONObject("data");
Long timestamp = eventData.getLong("timestamp");
String messageId = payload.getString("messageId");
if (droneData == null || droneData.isEmpty()) {
log.warn("msg_alarm 无人机数据为空: deviceSn={}", deviceSn);
return;
}
// 构建完整的 msg_alarm 数据
JSONObject msgAlarmData = new JSONObject();
msgAlarmData.put("eventType", "msg_alarm");
msgAlarmData.put("messageId", messageId);
msgAlarmData.put("timestamp", timestamp);
msgAlarmData.put("deviceId", eventData.getString("deviceId"));
msgAlarmData.put("droneData", droneData);
// 缓存到内存
msgAlarmDataCache.put(deviceSn, msgAlarmData);
// 保存到 Redis(公用存储)
if (alarmDataService != null) {
alarmDataService.saveMsgAlarmData(deviceSn, msgAlarmData);
}
log.debug("处理 msg_alarm 事件: deviceSn={}, timestamp={}", deviceSn, timestamp);
// 触发 msg_alarm 回调(用于一次性订阅)
BiConsumer<String, JSONObject> msgAlarmCallback = msgAlarmCallbacks.get(deviceSn);
if (msgAlarmCallback != null) {
try {
msgAlarmCallback.accept(deviceSn, msgAlarmData);
} catch (Exception callbackEx) {
log.error("msg_alarm 回调执行失败: deviceSn={}, error={}", deviceSn, callbackEx.getMessage());
}
}
// 如果设备已在 deviceDataMap 中注册,更新其数据
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data != null) {
data.setOnline(true);
data.setLastMessageTime(timestamp != null ? timestamp : System.currentTimeMillis());
// 从 droneData 提取关键字段更新到 DeviceRealtimeData
extractDroneKeyFields(data, droneData);
}
} catch (Exception e) {
log.error("解析 msg_alarm 消息失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
}
}
/**
* 从无人机数据中提取关键字段到 DeviceRealtimeData
*
* @param data 设备实时数据
* @param droneData 无人机遥测数据
*/
private void extractDroneKeyFields(DeviceRealtimeData data, JSONObject droneData) {
// 提取电池信息
if (droneData.containsKey("battery")) {
JSONObject battery = droneData.getJSONObject("battery");
if (battery != null && battery.containsKey("capacity_percent")) {
data.setBattery(battery.getInteger("capacity_percent"));
}
}
// 提取 GPS 坐标
if (droneData.containsKey("latitude") && droneData.containsKey("longitude")) {
GpsData gps = new GpsData();
gps.setLatitude(droneData.getDouble("latitude"));
gps.setLongitude(droneData.getDouble("longitude"));
gps.setAltitude(droneData.getDouble("height") != null ? droneData.getDouble("height") : 0.0);
data.setGps(gps);
}
}
/**
* 注册 fire_alarm 回调
*
* @param deviceSn 设备SN
* @param callback 回调函数
*/
public void registerFireAlarmCallback(String deviceSn, BiConsumer<String, JSONObject> callback) {
fireAlarmCallbacks.put(deviceSn, callback);
log.debug("注册 fire_alarm 回调: deviceSn={}", deviceSn);
}
/**
* 移除 fire_alarm 回调
*
* @param deviceSn 设备SN
*/
public void removeFireAlarmCallback(String deviceSn) {
fireAlarmCallbacks.remove(deviceSn);
log.debug("移除 fire_alarm 回调: deviceSn={}", deviceSn);
}
/**
* 注册 msg_alarm 回调
*
* @param deviceSn 设备SN
* @param callback 回调函数
*/
public void registerMsgAlarmCallback(String deviceSn, BiConsumer<String, JSONObject> callback) {
msgAlarmCallbacks.put(deviceSn, callback);
log.debug("注册 msg_alarm 回调: deviceSn={}", deviceSn);
}
/**
* 移除 msg_alarm 回调
*
* @param deviceSn 设备SN
*/
public void removeMsgAlarmCallback(String deviceSn) {
msgAlarmCallbacks.remove(deviceSn);
log.debug("移除 msg_alarm 回调: deviceSn={}", deviceSn);
}
/**
* 获取缓存的 msg_alarm 数据
*
* @param deviceSn 设备SN
* @return msg_alarm 数据,如果不存在返回 null
*/
public JSONObject getCachedMsgAlarmData(String deviceSn) {
return msgAlarmDataCache.get(deviceSn);
}
/**
* 识别数据类型
* @param dockData JSON数据
* @return 0=飞行任务数据, 1=机库综合数据, 2=机库状态数据, -1=未知
*/
private int identifyDataType(JSONObject dockData) {
if (dockData == null || dockData.isEmpty()) {
return -1;
}
// 第2种数据:机库综合数据(包含drone_charge_state, sub_device, environment_temperature等)
if (dockData.containsKey("drone_charge_state") || dockData.containsKey("sub_device")
|| dockData.containsKey("environment_temperature") || dockData.containsKey("drone_in_dock")) {
return 1;
}
// 第3种数据:机库状态数据(包含drone_battery_maintenance_info, electric_supply_voltage等)
if (dockData.containsKey("drone_battery_maintenance_info") || dockData.containsKey("electric_supply_voltage")
|| dockData.containsKey("working_current") || dockData.containsKey("acc_time")) {
return 2;
}
// 第1种数据:飞行任务数据(包含wireless_link, sdr, tilt_angle等)
if (dockData.containsKey("wireless_link") || dockData.containsKey("sdr")
|| dockData.containsKey("tilt_angle") || dockData.containsKey("flighttask_step_code")) {
return 0;
}
return -1;
}
/**
* 合并三种缓存数据
* @param cache 三种类型的缓存数组
* @return 合并后的完整数据
*/
private JSONObject mergeAllCaches(JSONObject[] cache) {
JSONObject merged = new JSONObject();
// 按顺序合并:type1 -> type2 -> type3
// 后面的数据会覆盖前面的同名字段
for (int i = 0; i < 3; i++) {
if (cache[i] != null && !cache[i].isEmpty()) {
merged = deepMerge(merged, cache[i]);
}
}
return merged;
}
/**
* 从合并后的dockData中提取关键字段到DeviceRealtimeData
* @param data 设备实时数据
* @param mergedDockData 合并后的dockData
*/
private void extractKeyFields(DeviceRealtimeData data, JSONObject mergedDockData) {
// 提取电池信息
// 优先从drone_charge_state提取(第2种数据)
if (mergedDockData.containsKey("drone_charge_state")) {
JSONObject chargeState = mergedDockData.getJSONObject("drone_charge_state");
if (chargeState != null && chargeState.containsKey("capacity_percent")) {
data.setBattery(chargeState.getInteger("capacity_percent"));
}
}
// 备选从drone_battery_maintenance_info提取(第3种数据)
if (data.getBattery() == null && mergedDockData.containsKey("drone_battery_maintenance_info")) {
JSONObject batteryInfo = mergedDockData.getJSONObject("drone_battery_maintenance_info");
if (batteryInfo != null && batteryInfo.containsKey("batteries")) {
com.alibaba.fastjson.JSONArray batteries = batteryInfo.getJSONArray("batteries");
if (batteries != null && !batteries.isEmpty()) {
JSONObject battery = batteries.getJSONObject(0);
data.setBattery(battery.getInteger("capacity_percent"));
data.setTemperature(battery.getDouble("temperature"));
}
}
}
// 提取GPS坐标
// 优先从latitude/longitude提取(第2种数据)
if (mergedDockData.containsKey("latitude") && mergedDockData.containsKey("longitude")) {
GpsData gps = new GpsData();
gps.setLatitude(mergedDockData.getDouble("latitude"));
gps.setLongitude(mergedDockData.getDouble("longitude"));
gps.setAltitude(mergedDockData.getDouble("height") != null ? mergedDockData.getDouble("height") : 0.0);
data.setGps(gps);
}
// 备选从self_converge_coordinate提取(第3种数据)
else if (mergedDockData.containsKey("self_converge_coordinate")) {
JSONObject coord = mergedDockData.getJSONObject("self_converge_coordinate");
if (coord != null) {
GpsData gps = new GpsData();
gps.setLatitude(coord.getDouble("latitude"));
gps.setLongitude(coord.getDouble("longitude"));
gps.setAltitude(coord.getDouble("height") != null ? coord.getDouble("height") : 0.0);
data.setGps(gps);
}
}
}
/**
* 深度合并两个JSONObject
* 规则:newData覆盖oldData,但保留oldData中newData没有的字段
*
* @param oldData 旧数据
* @param newData 新数据
* @return 合并后的数据
*/
private JSONObject deepMerge(JSONObject oldData, JSONObject newData) {
if (oldData == null) {
return newData;
}
if (newData == null) {
return oldData;
}
JSONObject merged = new JSONObject();
// 先复制旧数据的所有字段
merged.putAll(oldData);
// 用新数据覆盖
for (String key : newData.keySet()) {
Object newValue = newData.get(key);
Object oldValue = merged.get(key);
// 如果新旧值都是JSONObject,递归合并
if (newValue instanceof JSONObject && oldValue instanceof JSONObject) {
merged.put(key, deepMerge((JSONObject) oldValue, (JSONObject) newValue));
} else {
// 否则直接覆盖
merged.put(key, newValue);
}
}
return merged;
}
/**
* 添加设备到数据Map
*
* @param deviceSn 设备SN
* @param scenicId 景区ID
* @param tenantId 租户ID
*/
public void addDevice(String deviceSn, Long scenicId, String tenantId) {
DeviceRealtimeData data = new DeviceRealtimeData();
data.setDeviceSn(deviceSn);
data.setScenicId(scenicId);
data.setTenantId(tenantId);
data.setOnline(false);
data.setLastMessageTime(System.currentTimeMillis());
deviceDataMap.put(deviceSn, data);
log.info("添加设备到数据Map: deviceSn={}, scenicId={}, tenantId={}, 当前Map中设备数: {}",
deviceSn, scenicId, tenantId, deviceDataMap.size());
}
/**
* 移除设备
*
* @param deviceSn 设备SN
*/
public void removeDevice(String deviceSn) {
DeviceRealtimeData data = deviceDataMap.remove(deviceSn);
deviceDataCache.remove(deviceSn); // 同时清理缓存
// 无论设备是否存在于 deviceDataMap,都记录取消订阅时间
// 这样可以抑制后续延迟消息的警告
recentlyUnsubscribedDevices.put(deviceSn, System.currentTimeMillis());
if (data != null) {
log.info("从数据Map移除设备: deviceSn={}, scenicId={}", deviceSn, data.getScenicId());
} else {
log.debug("尝试移除不存在的设备(可能已被其他地方移除): deviceSn={}", deviceSn);
}
}
/**
* 检查设备是否在取消订阅的宽限期内
* 用于判断是否应该抑制"收到未订阅设备消息"的警告
*
* @param deviceSn 设备SN
* @return true 如果设备刚刚取消订阅(在宽限期内)
*/
private boolean isInUnsubscribeGracePeriod(String deviceSn) {
Long unsubscribeTime = recentlyUnsubscribedDevices.get(deviceSn);
if (unsubscribeTime == null) {
return false;
}
long elapsed = System.currentTimeMillis() - unsubscribeTime;
if (elapsed > UNSUBSCRIBE_GRACE_PERIOD_MS) {
// 超过宽限期,移除记录
recentlyUnsubscribedDevices.remove(deviceSn);
return false;
}
return true;
}
/**
* 清理过期的取消订阅记录
* 可以定期调用,或在适当时机调用
*/
public void cleanupExpiredUnsubscribeRecords() {
long now = System.currentTimeMillis();
recentlyUnsubscribedDevices.entrySet().removeIf(entry ->
now - entry.getValue() > UNSUBSCRIBE_GRACE_PERIOD_MS);
}
/**
* 标记设备在线
*
* @param deviceSn 设备SN
*/
public void markDeviceOnline(String deviceSn) {
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data != null) {
data.setOnline(true);
data.setLastMessageTime(System.currentTimeMillis());
log.info("设备 {} 已上线", deviceSn);
// 推送上线状态
pushDeviceDataUpdate(data);
} else if (!isInUnsubscribeGracePeriod(deviceSn)) {
log.debug("收到未订阅设备的上线事件: deviceSn={}", deviceSn);
}
}
/**
* 标记设备离线
*
* @param deviceSn 设备SN
*/
public void markDeviceOffline(String deviceSn) {
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data != null) {
data.setOnline(false);
log.warn("设备 {} 已离线", deviceSn);
// 推送离线状态
pushDeviceDataUpdate(data);
} else if (!isInUnsubscribeGracePeriod(deviceSn)) {
log.debug("收到未订阅设备的离线事件: deviceSn={}", deviceSn);
}
}
/**
* 推送设备数据更新
*/
private void pushDeviceDataUpdate(DeviceRealtimeData data) {
if (sseEmitterManager != null) {
try {
// v3.0: 改为按设备SN推送(不再按景区ID)
sseEmitterManager.getClass()
.getMethod("sendDeviceDataUpdate", String.class, DeviceRealtimeData.class)
.invoke(sseEmitterManager, data.getDeviceSn(), data);
} catch (Exception e) {
log.warn("调用SSE推送失败: {}", e.getMessage());
}
}
}
/**
* 获取设备数据Map(只读)
*/
public ConcurrentHashMap<String, DeviceRealtimeData> getDeviceDataMap() {
return deviceDataMap;
}
/**
* 获取设备数据
*/
public DeviceRealtimeData getDeviceData(String deviceSn) {
return deviceDataMap.get(deviceSn);
}
/**
* 清空景区设备数据
*/
public void clearByScenicId(Long scenicId) {
deviceDataMap.entrySet().removeIf(entry -> {
if (entry.getValue().getScenicId().equals(scenicId)) {
log.debug("清理景区 {} 的设备数据: {}", scenicId, entry.getKey());
return true;
}
return false;
});
}
}
@@ -0,0 +1,378 @@
package com.central.device.websocket.manager;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.config.WebSocketProperties;
import com.central.device.websocket.model.CommandStatus;
import com.central.device.websocket.model.DeviceCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 设备命令管理器(v2.0)
* 负责设备命令队列管理、发送、重试、超时处理
* 使用全局JetLinksWebSocketClient发送命令
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Component
public class DeviceCommandManager {
@Autowired
private WebSocketProperties properties;
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
/**
* 待发送命令队列: deviceSn -> Queue<DeviceCommand>
*/
private final ConcurrentHashMap<String, ConcurrentLinkedQueue<DeviceCommand>> commandQueues = new ConcurrentHashMap<>();
/**
* 已发送等待响应的命令: commandId -> DeviceCommand
*/
private final ConcurrentHashMap<String, DeviceCommand> pendingCommands = new ConcurrentHashMap<>();
/**
* 延迟执行器(用于重试)
*/
private final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(2);
/**
* 初始化
*/
@PostConstruct
public void init() {
// 设置命令管理器引用(解决循环依赖)
jetLinksWebSocketClient.setCommandManager(this);
log.info("命令管理器已初始化");
}
/**
* 发送命令
*
* @param deviceSn 设备SN
* @param commandType 命令类型
* @param params 命令参数
* @return 命令ID
*/
public String sendCommand(String deviceSn, String commandType, JSONObject params) {
// 1. 创建命令对象
DeviceCommand command = DeviceCommand.builder()
.commandId(UUID.randomUUID().toString())
.deviceSn(deviceSn)
.commandType(commandType)
.params(params != null ? params : new JSONObject())
.status(CommandStatus.PENDING)
.createTime(System.currentTimeMillis())
.sendTime(0)
.expireTime(System.currentTimeMillis() + properties.getCommand().getDefaultTimeout())
.retryCount(0)
.maxRetry(properties.getCommand().getMaxRetry())
.build();
log.info("创建设备命令: commandId={}, device={}, type={}",
command.getCommandId(), deviceSn, commandType);
// 2. 检查全局WebSocket连接状态,未连接则自动连接
if (!jetLinksWebSocketClient.isConnected()) {
log.info("WebSocket未连接,自动建立连接: commandId={}", command.getCommandId());
jetLinksWebSocketClient.connect();
// 等待连接建立(最多等待5秒)
int waitCount = 0;
while (!jetLinksWebSocketClient.isConnected() && waitCount < 50) {
try {
Thread.sleep(100);
waitCount++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("等待连接被中断");
addToQueue(command);
return command.getCommandId();
}
}
}
// 3. 连接成功则立即发送,否则加入队列
if (jetLinksWebSocketClient.isConnected()) {
sendCommandImmediately(command);
} else {
log.warn("WebSocket连接失败,命令加入队列: commandId={}, device={}", command.getCommandId(), deviceSn);
addToQueue(command);
}
return command.getCommandId();
}
/**
* 立即发送命令(通过全局WebSocket客户端)
*/
private void sendCommandImmediately(DeviceCommand command) {
try {
command.setStatus(CommandStatus.SENDING);
command.setSendTime(System.currentTimeMillis());
// 构造命令消息
// TODO: 根据JetLinks平台实际API调整消息格式
JSONObject message = new JSONObject();
message.put("messageId", command.getCommandId());
message.put("deviceId", command.getDeviceSn());
message.put("command", command.getCommandType());
message.put("params", command.getParams());
// 通过全局WebSocket发送
jetLinksWebSocketClient.send(message.toJSONString());
command.setStatus(CommandStatus.SENT);
// 放入待响应列表
pendingCommands.put(command.getCommandId(), command);
log.info("命令发送成功: commandId={}, device={}, type={}",
command.getCommandId(), command.getDeviceSn(), command.getCommandType());
} catch (Exception e) {
log.error("命令发送失败: commandId={}, error={}", command.getCommandId(), e.getMessage());
command.setStatus(CommandStatus.FAILED);
command.setErrorMsg(e.getMessage());
// 重试
retryCommand(command);
}
}
/**
* 加入队列
*/
private void addToQueue(DeviceCommand command) {
ConcurrentLinkedQueue<DeviceCommand> queue = commandQueues
.computeIfAbsent(command.getDeviceSn(), k -> new ConcurrentLinkedQueue<>());
// 检查队列长度
if (queue.size() >= properties.getCommand().getQueueMaxSize()) {
log.error("设备 {} 命令队列已满({}), 拒绝新命令: {}",
command.getDeviceSn(), properties.getCommand().getQueueMaxSize(), command.getCommandId());
command.setStatus(CommandStatus.FAILED);
command.setErrorMsg("命令队列已满");
return;
}
queue.offer(command);
log.info("命令已加入队列: commandId={}, device={}, 队列长度={}",
command.getCommandId(), command.getDeviceSn(), queue.size());
}
/**
* WebSocket重连后处理所有队列
* 由 JetLinksWebSocketClient 在重连成功后调用
*/
public void onWebSocketReconnected() {
log.info("WebSocket重连成功,开始处理所有命令队列");
if (commandQueues.isEmpty()) {
log.debug("所有命令队列为空");
return;
}
int totalProcessed = 0;
int totalExpired = 0;
// 处理所有设备的命令队列
for (String deviceSn : commandQueues.keySet()) {
ConcurrentLinkedQueue<DeviceCommand> queue = commandQueues.get(deviceSn);
if (queue == null || queue.isEmpty()) {
continue;
}
int processedCount = 0;
int expiredCount = 0;
// 处理队列中的命令
while (!queue.isEmpty()) {
DeviceCommand command = queue.poll();
// 检查是否过期
if (System.currentTimeMillis() > command.getExpireTime()) {
command.setStatus(CommandStatus.EXPIRED);
expiredCount++;
log.warn("命令已过期: commandId={}, device={}", command.getCommandId(), deviceSn);
continue;
}
// 重发命令
log.info("重发队列命令: commandId={}, device={}, type={}",
command.getCommandId(), deviceSn, command.getCommandType());
sendCommandImmediately(command);
processedCount++;
// 限流:每个命令间隔100ms
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("命令重发被中断");
break;
}
}
totalProcessed += processedCount;
totalExpired += expiredCount;
log.info("设备 {} 命令队列处理完成: 重发={}, 过期={}", deviceSn, processedCount, expiredCount);
}
log.info("所有命令队列处理完成: 总重发={}, 总过期={}", totalProcessed, totalExpired);
}
/**
* 命令重试
*/
private void retryCommand(DeviceCommand command) {
if (command.getRetryCount() >= command.getMaxRetry()) {
log.error("命令重试次数超限: commandId={}, device={}",
command.getCommandId(), command.getDeviceSn());
command.setStatus(CommandStatus.FAILED);
return;
}
command.setRetryCount(command.getRetryCount() + 1);
log.info("命令准备重试 ({}/{}): commandId={}",
command.getRetryCount(), command.getMaxRetry(), command.getCommandId());
// 延迟重试(指数退避)
long delay = (long) Math.pow(2, command.getRetryCount()) * properties.getCommand().getRetryDelayBase();
retryExecutor.schedule(() -> {
if (jetLinksWebSocketClient.isConnected()) {
log.info("命令开始重试: commandId={}", command.getCommandId());
sendCommandImmediately(command);
} else {
log.warn("命令重试时WebSocket未连接,重新加入队列: commandId={}", command.getCommandId());
addToQueue(command);
}
}, delay, TimeUnit.MILLISECONDS);
}
/**
* 接收设备命令响应
*/
public void handleCommandResponse(String commandId, boolean success, String message) {
DeviceCommand command = pendingCommands.remove(commandId);
if (command == null) {
log.warn("收到未知命令响应: commandId={}", commandId);
return;
}
if (success) {
command.setStatus(CommandStatus.SUCCESS);
log.info("命令执行成功: commandId={}, device={}",
commandId, command.getDeviceSn());
} else {
command.setStatus(CommandStatus.FAILED);
command.setErrorMsg(message);
log.error("命令执行失败: commandId={}, device={}, error={}",
commandId, command.getDeviceSn(), message);
}
}
/**
* 定时清理过期命令
*/
@Scheduled(fixedRateString = "${device.websocket.command.cleanup-interval:10000}")
public void cleanupExpiredCommands() {
long now = System.currentTimeMillis();
int queueExpiredCount = 0;
AtomicInteger pendingTimeoutCount = new AtomicInteger(0);
// 清理队列中的过期命令
for (ConcurrentLinkedQueue<DeviceCommand> queue : commandQueues.values()) {
int removed = 0;
for (DeviceCommand command : queue) {
if (now > command.getExpireTime()) {
if (queue.remove(command)) {
command.setStatus(CommandStatus.EXPIRED);
removed++;
log.debug("清理过期命令: commandId={}, device={}",
command.getCommandId(), command.getDeviceSn());
}
}
}
queueExpiredCount += removed;
}
// 清理等待响应的超时命令
pendingCommands.entrySet().removeIf(entry -> {
DeviceCommand command = entry.getValue();
if (now > command.getExpireTime()) {
command.setStatus(CommandStatus.TIMEOUT);
log.warn("命令响应超时: commandId={}, device={}",
command.getCommandId(), command.getDeviceSn());
pendingTimeoutCount.incrementAndGet();
return true;
}
return false;
});
if (queueExpiredCount > 0 || pendingTimeoutCount.get() > 0) {
log.info("清理过期命令完成: 队列过期={}, 响应超时={}", queueExpiredCount, pendingTimeoutCount.get());
}
}
/**
* 查询命令状态
*/
public CommandStatus getCommandStatus(String commandId) {
// 先查待响应列表
DeviceCommand command = pendingCommands.get(commandId);
if (command != null) {
return command.getStatus();
}
// 再查队列
for (ConcurrentLinkedQueue<DeviceCommand> queue : commandQueues.values()) {
Optional<DeviceCommand> found = queue.stream()
.filter(cmd -> cmd.getCommandId().equals(commandId))
.findFirst();
if (found.isPresent()) {
return found.get().getStatus();
}
}
return null;
}
/**
* 获取命令详情
*/
public DeviceCommand getCommand(String commandId) {
// 先查待响应列表
DeviceCommand command = pendingCommands.get(commandId);
if (command != null) {
return command;
}
// 再查队列
for (ConcurrentLinkedQueue<DeviceCommand> queue : commandQueues.values()) {
Optional<DeviceCommand> found = queue.stream()
.filter(cmd -> cmd.getCommandId().equals(commandId))
.findFirst();
if (found.isPresent()) {
return found.get();
}
}
return null;
}
}
@@ -0,0 +1,303 @@
package com.central.device.websocket.manager;
import com.central.device.model.AgeDevice;
import com.central.device.service.IAgeDeviceService;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.config.WebSocketProperties;
import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.model.SubscriptionTopic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 设备订阅管理器(v3.0 - 支持景区级和设备级订阅)
* 负责管理设备订阅,使用全局WebSocket连接(懒加载)
*
* 改进:
* 1. 支持单个设备订阅(按需订阅)
* 2. WebSocket懒加载:只有调用时才连接
* 3. 保留景区级订阅方法(向下兼容)
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Component
public class DeviceSubscriptionManager {
@Autowired
private WebSocketProperties properties;
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
@Autowired
private DeviceMessageHandler messageHandler;
@Autowired
private IAgeDeviceService deviceService;
/**
* 景区订阅计数: scenicId -> count
*/
private final ConcurrentHashMap<Long, AtomicInteger> scenicSubscriptionCount = new ConcurrentHashMap<>();
/**
* 景区设备列表缓存: scenicId -> List<deviceSn>
*/
private final ConcurrentHashMap<Long, List<String>> scenicDevicesCache = new ConcurrentHashMap<>();
/**
* 按景区订阅设备
*
* @param scenicId 景区ID
* @param tenantId 租户ID
*/
public void subscribeForScenic(Long scenicId, String tenantId) {
if (scenicId == null) {
log.warn("景区ID为空,无法订阅");
return;
}
// 1. 增加景区订阅计数
AtomicInteger counter = scenicSubscriptionCount.computeIfAbsent(scenicId, k -> new AtomicInteger(0));
int count = counter.incrementAndGet();
log.info("景区 {} SSE连接建立,订阅计数: {}", scenicId, count);
// 2. 如果是第一个连接,开始订阅
if (count == 1) {
log.info("景区 {} 首次连接,开始订阅设备", scenicId);
// 获取该景区的所有设备
List<AgeDevice> devices = deviceService.listByScenicId(scenicId);
if (devices == null || devices.isEmpty()) {
log.warn("景区 {} 没有设备", scenicId);
return;
}
log.info("景区 {} 共有 {} 个设备待订阅", scenicId, devices.size());
// 缓存设备SN列表
List<String> deviceSnList = devices.stream()
.map(AgeDevice::getDeviceSn)
.toList();
scenicDevicesCache.put(scenicId, deviceSnList);
// 分批订阅(避免瞬时压力)
subscribeDevicesInBatches(devices, scenicId, tenantId);
} else {
log.info("景区 {} 新增SSE连接,复用现有订阅,当前连接数: {}", scenicId, count);
}
}
/**
* 取消景区订阅
*
* @param scenicId 景区ID
*/
public void unsubscribeForScenic(Long scenicId) {
if (scenicId == null) {
return;
}
AtomicInteger counter = scenicSubscriptionCount.get(scenicId);
if (counter == null) {
log.warn("景区 {} 订阅计数不存在", scenicId);
return;
}
// 1. 减少景区订阅计数
int count = counter.decrementAndGet();
log.info("景区 {} SSE连接断开,订阅计数: {}", scenicId, count);
// 2. 如果计数为0,取消订阅
if (count == 0) {
log.info("景区 {} 所有SSE连接已断开,开始取消设备订阅", scenicId);
// 获取缓存的设备列表
List<String> deviceSnList = scenicDevicesCache.remove(scenicId);
if (deviceSnList != null) {
// 通过全局WebSocket客户端取消订阅(取消订阅所有主题)
deviceSnList.forEach(deviceSn -> {
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM
);
messageHandler.removeDevice(deviceSn);
log.debug("取消订阅设备: {}", deviceSn);
});
log.info("景区 {} 设备订阅已全部取消,共取消 {} 个设备订阅", scenicId, deviceSnList.size());
}
// 移除计数器
scenicSubscriptionCount.remove(scenicId);
} else if (count < 0) {
// 异常情况:计数为负数
log.error("景区 {} 订阅计数异常: {}, 强制重置", scenicId, count);
scenicSubscriptionCount.remove(scenicId);
} else {
log.info("景区 {} 仍有 {} 个SSE连接,保持设备订阅", scenicId, count);
}
}
/**
* 分批订阅设备
*/
private void subscribeDevicesInBatches(List<AgeDevice> devices, Long scenicId, String tenantId) {
int batchSize = properties.getSubscribe().getBatchSize();
int intervalMs = properties.getSubscribe().getBatchInterval();
CompletableFuture.runAsync(() -> {
try {
for (int i = 0; i < devices.size(); i += batchSize) {
int end = Math.min(i + batchSize, devices.size());
List<AgeDevice> batch = devices.subList(i, end);
log.info("景区 {} 批量订阅设备: {}/{}", scenicId, end, devices.size());
batch.forEach(device -> subscribeDevice(device, scenicId, tenantId));
// 间隔一段时间再订阅下一批
if (end < devices.size()) {
Thread.sleep(intervalMs);
}
}
log.info("景区 {} 设备订阅完成,总数: {}", scenicId, devices.size());
} catch (Exception e) {
log.error("景区 {} 批量订阅设备失败: {}", scenicId, e.getMessage(), e);
}
});
}
/**
* 订阅单个设备(通过全局WebSocket客户端)
* 订阅设备的核心主题:上线、离线、属性上报、火警事件
*/
private void subscribeDevice(AgeDevice device, Long scenicId, String tenantId) {
String deviceSn = device.getDeviceSn();
try {
// 添加设备到数据Map
messageHandler.addDevice(deviceSn, scenicId, tenantId);
// 通过全局WebSocket客户端订阅设备(指定订阅主题)
jetLinksWebSocketClient.subscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE, // 设备上线
SubscriptionTopic.OFFLINE, // 设备离线
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm事件(最重要)
);
log.info("设备 {} 订阅成功(景区: {})", deviceSn, scenicId);
} catch (Exception e) {
log.error("设备 {} 订阅失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 获取设备实时数据(用于推送初始设备列表)
*/
public List<String> getScenicDevices(Long scenicId) {
return scenicDevicesCache.get(scenicId);
}
/**
* 获取景区订阅计数
*/
public int getSubscriptionCount(Long scenicId) {
AtomicInteger counter = scenicSubscriptionCount.get(scenicId);
return counter != null ? counter.get() : 0;
}
/**
* 检查景区是否已订阅
*/
public boolean isScenicSubscribed(Long scenicId) {
return scenicSubscriptionCount.containsKey(scenicId) && getSubscriptionCount(scenicId) > 0;
}
/**
* 订阅单个设备(v3.0新增)
* 用于SSE懒加载模式,只订阅用户请求的设备
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
*/
public void subscribeDevice(String deviceSn, String tenantId) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
log.warn("设备SN为空,无法订阅");
return;
}
log.info("订阅单个设备: deviceSn={}, tenantId={}", deviceSn, tenantId);
try {
// 添加设备到数据Map(scenicId使用0表示单设备订阅)
// log.info("准备添加设备到数据Map: deviceSn={}, tenantId={}", deviceSn, tenantId);
messageHandler.addDevice(deviceSn, 0L, tenantId);
// log.info("设备已添加到数据Map");
// 通过全局WebSocket客户端订阅设备(会自动触发懒加载连接)
// 只订阅关键主题:上线、离线、fire_alarm(包含设备完整状态数据)
log.info("准备订阅WebSocket主题: deviceSn={}", deviceSn);
jetLinksWebSocketClient.subscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE, // 设备上线
SubscriptionTopic.OFFLINE, // 设备离线
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm事件(最重要,包含电池、GPS等完整数据)
);
log.info("设备 {} 订阅成功(包括WebSocket订阅)", deviceSn);
} catch (Exception e) {
log.error("设备 {} 订阅失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 取消订阅单个设备(v3.0新增)
*
* @param deviceSn 设备SN
*/
public void unsubscribeDevice(String deviceSn) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
log.warn("设备SN为空,无法取消订阅");
return;
}
log.info("取消订阅单个设备: deviceSn={}", deviceSn);
try {
// 通过全局WebSocket客户端取消订阅
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM
);
// 移除设备数据
messageHandler.removeDevice(deviceSn);
log.info("设备 {} 订阅已取消", deviceSn);
} catch (Exception e) {
log.error("取消订阅设备 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
}
@@ -0,0 +1,229 @@
package com.central.device.websocket.manager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.config.WebSocketProperties;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* Token管理器 - 按需获取版本
* 负责OAuth2 Token的获取、缓存和自动刷新
* 完全符合按需订阅理念:只在业务需要时才获取和刷新Token
*
* @author lishilin
* @date 2025-01-01
*/
@Slf4j
@Component
public class TokenManager {
@Autowired
private WebSocketProperties properties;
/**
* 当前Token
*/
private volatile String currentToken;
/**
* Token过期时间戳
*/
private volatile long tokenExpireTime;
/**
* 锁,保证线程安全
*/
private final ReentrantLock lock = new ReentrantLock();
/**
* OkHttpClient
*/
private final OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
/**
* 获取有效Token
* 优先从内存缓存获取,过期则刷新
*
* @return Token字符串
*/
public String getValidToken() {
// 检查Token是否有效
if (currentToken != null && !isTokenExpiring()) {
return currentToken;
}
// Token无效或即将过期,刷新
return refreshToken();
}
/**
* 强制刷新Token(增强版:带重试机制和降级策略)
*
* @return 新的Token字符串
*/
public String refreshToken() {
lock.lock();
try {
// 双重检查,避免重复刷新
if (currentToken != null && !isTokenExpiring()) {
return currentToken;
}
log.info("开始刷新OAuth2 Token...");
// 重试逻辑
int maxRetries = 3;
Exception lastException = null;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
try {
String token = doRefreshToken();
log.info("Token刷新成功(尝试 {}/{})", attempt, maxRetries);
return token;
} catch (Exception e) {
lastException = e;
log.warn("Token获取失败(尝试 {}/{}): {}", attempt, maxRetries, e.getMessage());
if (attempt < maxRetries) {
try {
Thread.sleep(2000); // 间隔2秒重试
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
log.error("Token刷新重试被中断", ie);
break;
}
}
}
}
// 所有重试失败后的降级策略
if (currentToken != null) {
long now = System.currentTimeMillis();
// 如果旧Token还在真实过期时间前60秒内,可以临时使用
if (now < tokenExpireTime + 60 * 1000) {
long remainingSeconds = (tokenExpireTime + 60 * 1000 - now) / 1000;
log.warn("Token刷新失败,使用降级策略:返回即将过期的旧Token(剩余{}秒)", remainingSeconds);
return currentToken;
}
}
throw new RuntimeException("Token获取失败,已重试" + maxRetries + "次", lastException);
} finally {
lock.unlock();
}
}
/**
* 实际执行Token刷新的方法(提取出来便于重试)
*
* @return 新的Token字符串
* @throws IOException 网络异常
*/
private String doRefreshToken() throws IOException {
long startTime = System.currentTimeMillis();
WebSocketProperties.OAuth2Config oauth2 = properties.getOauth2();
// 构建请求体
String requestBody = String.format(
"grant_type=client_credentials&client_id=%s&client_secret=%s",
oauth2.getClientId(),
oauth2.getClientSecret()
);
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, requestBody);
Request request = new Request.Builder()
.url(oauth2.getTokenUrl())
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
try (Response response = httpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Token获取失败, HTTP状态码: " + response.code());
}
String responseBody = response.body() != null ? response.body().string() : "";
JSONObject json = JSON.parseObject(responseBody);
if (json == null) {
throw new IOException("Token响应解析失败");
}
String accessToken = json.getString("access_token");
Integer expiresIn = json.getInteger("expires_in");
if (accessToken == null || expiresIn == null) {
throw new IOException("Token响应格式错误: " + responseBody);
}
// 更新缓存,提前60秒过期
currentToken = accessToken;
tokenExpireTime = System.currentTimeMillis() + (expiresIn - 60) * 1000L;
long duration = System.currentTimeMillis() - startTime;
String expireTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(tokenExpireTime));
log.info("Token获取成功, 有效期: {}秒, 耗时: {}ms, 过期时间: {}", expiresIn, duration, expireTimeStr);
return currentToken;
}
}
/**
* 检查Token是否即将过期(提前60秒)
*
* @return true=即将过期或已过期
*/
private boolean isTokenExpiring() {
return System.currentTimeMillis() >= tokenExpireTime;
}
/**
* 清理资源
* 应用关闭时释放OkHttpClient资源
*/
@PreDestroy
public void destroy() {
if (httpClient != null) {
httpClient.dispatcher().executorService().shutdown();
httpClient.connectionPool().evictAll();
log.info("TokenManager资源已释放");
}
}
// ========== 可选的查询方法 ==========
/**
* 获取Token过期时间
*
* @return 过期时间戳
*/
public long getTokenExpireTime() {
return tokenExpireTime;
}
/**
* 检查Token是否有效
*
* @return true=有效
*/
public boolean isTokenValid() {
return currentToken != null && !isTokenExpiring();
}
}
@@ -0,0 +1,44 @@
package com.central.device.websocket.model;
/**
* 设备命令状态枚举
*
* @author lishilin
* @date 2025-01-01
*/
public enum CommandStatus {
/**
* 待发送
*/
PENDING,
/**
* 发送中
*/
SENDING,
/**
* 已发送
*/
SENT,
/**
* 执行成功
*/
SUCCESS,
/**
* 执行失败
*/
FAILED,
/**
* 响应超时
*/
TIMEOUT,
/**
* 命令已过期
*/
EXPIRED
}
@@ -0,0 +1,71 @@
package com.central.device.websocket.model;
import com.alibaba.fastjson.JSONObject;
import lombok.Builder;
import lombok.Data;
/**
* 设备命令实体
* 封装设备命令信息并跟踪命令状态
*
* @author lishilin
* @date 2025-01-01
*/
@Data
@Builder
public class DeviceCommand {
/**
* 命令ID(UUID)
*/
private String commandId;
/**
* 目标设备SN
*/
private String deviceSn;
/**
* 命令类型(takeoff/land/return等)
*/
private String commandType;
/**
* 命令参数
*/
private JSONObject params;
/**
* 命令状态
*/
private CommandStatus status;
/**
* 创建时间
*/
private long createTime;
/**
* 发送时间(0表示未发送)
*/
private long sendTime;
/**
* 过期时间
*/
private long expireTime;
/**
* 重试次数
*/
private int retryCount;
/**
* 最大重试次数
*/
private int maxRetry;
/**
* 错误信息
*/
private String errorMsg;
}
@@ -0,0 +1,74 @@
package com.central.device.websocket.model;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
/**
* 设备实时数据
* 存储单个设备的实时状态和数据(内存)
*
* @author lishilin
* @date 2025-01-19
*/
@Data
public class DeviceRealtimeData {
/**
* 设备SN
*/
private String deviceSn;
/**
* 所属景区ID
*/
private Long scenicId;
/**
* 所属租户ID
*/
private String tenantId;
/**
* 是否在线(WebSocket连接状态)
*/
private boolean online;
/**
* 最后消息时间戳
*/
private long lastMessageTime;
/**
* 温度(°C)
*/
private Double temperature;
/**
* 湿度(%)
*/
private Double humidity;
/**
* 电量百分比
*/
private Integer battery;
/**
* GPS数据
*/
private GpsData gps;
/**
* 飞行模式
*/
private String flightMode;
/**
* 飞行状态
*/
private String flightStatus;
/**
* 原始消息数据
*/
private JSONObject rawData;
}
@@ -0,0 +1,27 @@
package com.central.device.websocket.model;
import lombok.Data;
/**
* GPS数据
*
* @author lishilin
* @date 2025-01-19
*/
@Data
public class GpsData {
/**
* 纬度
*/
private Double latitude;
/**
* 经度
*/
private Double longitude;
/**
* 海拔高度(米)
*/
private Double altitude;
}
@@ -0,0 +1,35 @@
package com.central.device.websocket.model;
import com.alibaba.fastjson.JSONObject;
import lombok.Builder;
import lombok.Data;
/**
* WebSocket订阅消息
*
* @author lishilin
* @date 2025-01-19
*/
@Data
@Builder
public class SubscriptionMessage {
/**
* 消息类型: sub(订阅) / unsub(取消订阅)
*/
private String type;
/**
* 订阅主题
*/
private String topic;
/**
* 订阅参数(可为空)
*/
private JSONObject parameter;
/**
* 请求ID(随机生成,每次唯一)
*/
private String id;
}
@@ -0,0 +1,88 @@
package com.central.device.websocket.model;
/**
* WebSocket订阅主题
* 基于JetLinks平台的主题订阅模式
*
* @author lishilin
* @date 2025-01-19
*/
public enum SubscriptionTopic {
/**
* 设备上线
*/
ONLINE("/device/D-Dock2/{deviceSn}/online"),
/**
* 设备离线
*/
OFFLINE("/device/D-Dock2/{deviceSn}/offline"),
/**
* 平台主动断开连接
*/
DISCONNECT("/device/D-Dock2/{deviceSn}/disconnect"),
/**
* 平台主动断开连接回复
*/
DISCONNECT_REPLY("/device/D-Dock2/{deviceSn}/disconnect/reply"),
/**
* 设备状态事件(fire_alarm)
* 注意:这不是火警告警,而是设备状态事件上报,用于获取设备完整状态信息
*/
EVENT_FIRE_ALARM("/device/D-Dock2/{deviceSn}/message/event/fire_alarm"),
/**
* 无人机遥测数据事件(msg_alarm)
* 包含无人机飞行状态、电池、GPS、相机等完整遥测数据
*/
EVENT_MSG_ALARM("/device/D-Dock2/{deviceSn}/message/event/msg_alarm"),
/**
* 设备上报属性
*/
PROPERTY_REPORT("/device/D-Dock2/{deviceSn}/message/property/report"),
/**
* 读取属性
*/
PROPERTY_READ("/device/D-Dock2/{deviceSn}/message/send/property/read"),
/**
* 读取属性回复
*/
PROPERTY_READ_REPLY("/device/D-Dock2/{deviceSn}/message/property/read/reply"),
/**
* 修改属性
*/
PROPERTY_WRITE("/device/D-Dock2/{deviceSn}/message/send/property/write"),
/**
* 修改属性回复
*/
PROPERTY_WRITE_REPLY("/device/D-Dock2/{deviceSn}/message/property/write/reply");
private final String topicPattern;
SubscriptionTopic(String topicPattern) {
this.topicPattern = topicPattern;
}
/**
* 获取主题(替换deviceSn占位符)
*/
public String getTopic(String deviceSn) {
return topicPattern.replace("{deviceSn}", deviceSn);
}
/**
* 获取主题模式
*/
public String getTopicPattern() {
return topicPattern;
}
}
@@ -0,0 +1,582 @@
package com.central.device.websocket.model.message;
import lombok.Data;
import java.util.List;
/**
* 设备状态事件消息
* 对应 JetLinks 平台的 /message/event/fire_alarm 主题
* 注意:fire_alarm 不是火警告警,而是设备状态事件上报,用于获取设备完整状态信息
*
* @author lishilin
* @date 2025-01-19
*/
@Data
public class DeviceStateEventMessage {
/**
* 请求ID
*/
private String requestId;
/**
* 主题
*/
private String topic;
/**
* 消息类型
*/
private String type;
/**
* 载荷
*/
private Payload payload;
@Data
public static class Payload {
/**
* 消息头
*/
private Headers headers;
/**
* 消息ID
*/
private String messageId;
/**
* 设备ID
*/
private String deviceId;
/**
* 时间戳
*/
private Long timestamp;
/**
* 事件类型
*/
private String event;
/**
* 消息类型
*/
private String messageType;
/**
* 事件数据
*/
private EventData data;
}
@Data
public static class Headers {
private String deviceName;
private String productName;
private String productId;
private String _uid;
private String creatorId;
private String traceparent;
}
@Data
public static class EventData {
/**
* 设备ID
*/
private String deviceId;
/**
* 时间戳
*/
private Long timestamp;
/**
* 设备数据
*/
private DockData data;
}
@Data
public static class DockData {
// ============ 机库状态数据(第3种数据)============
/**
* 无人机电池维护信息
*/
private DroneBatteryMaintenanceInfo drone_battery_maintenance_info;
/**
* 供电电压(V)
*/
private Integer electric_supply_voltage;
/**
* 工作电流(mA)
*/
private Integer working_current;
/**
* 云台支架状态
*/
private Integer gimbal_holder_state;
/**
* 维护状态
*/
private MaintainStatus maintain_status;
/**
* 激活时间(秒)
*/
private Long activation_time;
/**
* 自主收敛坐标
*/
private Coordinate self_converge_coordinate;
/**
* 累计时间(秒)
*/
private Long acc_time;
/**
* 温度模式状态
*/
private Boolean temp_mode_state;
/**
* 相对备降点
*/
private RelativeAlternateLandPoint relative_alternate_land_point;
/**
* POE 功率输出(W)
*/
private Integer poe_power_output;
/**
* ACDC 功率输入(W)
*/
private Double acdc_power_input;
/**
* 工作电压(mV)
*/
private Integer working_voltage;
/**
* 备用电池
*/
private BackupBattery backup_battery;
/**
* POE 链接状态
*/
private Integer poe_link_status;
/**
* 作业编号
*/
private Integer job_number;
/**
* 部署模式
*/
private Integer deployment_mode;
// ============ 机库综合数据(第2种数据)============
/**
* 纬度
*/
private Double latitude;
/**
* 经度
*/
private Double longitude;
/**
* 高度(m)
*/
private Double height;
/**
* 无人机充电状态
*/
private DroneChargeState drone_charge_state;
/**
* 子设备信息
*/
private SubDevice sub_device;
/**
* 环境温度(℃)
*/
private Double environment_temperature;
/**
* 温度(℃)
*/
private Integer temperature;
/**
* 湿度(%)
*/
private Integer humidity;
/**
* 风速(m/s)
*/
private Double wind_speed;
/**
* 降雨量(mm)
*/
private Double rainfall;
/**
* 朝向(度)
*/
private Double heading;
/**
* 告警状态
*/
private Integer alarm_state;
/**
* 紧急停止状态
*/
private Integer emergency_stop_state;
/**
* 电池存储模式
*/
private Integer battery_store_mode;
/**
* 无人机是否在机库
*/
private Integer drone_in_dock;
/**
* 定位状态
*/
private PositionState position_state;
/**
* 网络状态
*/
private NetworkState network_state;
/**
* 模式代码
*/
private Integer mode_code;
/**
* 备降点
*/
private AlternateLandPoint alternate_land_point;
/**
* 舱门状态
*/
private Integer cover_state;
/**
* 静音模式
*/
private Integer silent_mode;
/**
* 补光灯状态
*/
private Integer supplement_light_state;
/**
* 首次开机时间
*/
private Long first_power_on;
/**
* 推杆状态
*/
private Integer putter_state;
/**
* 空调状态
*/
private AirConditioner air_conditioner;
/**
* Home位置是否有效
*/
private Integer home_position_is_valid;
}
@Data
public static class DroneBatteryMaintenanceInfo {
/**
* 加热状态
*/
private Integer heat_state;
/**
* 电池列表
*/
private List<Battery> batteries;
/**
* 维护剩余时间(秒)
*/
private Integer maintenance_time_left;
/**
* 维护状态
*/
private Integer maintenance_state;
}
@Data
public static class Battery {
/**
* 电量百分比
*/
private Integer capacity_percent;
/**
* 温度(℃)
*/
private Double temperature;
/**
* 电池索引
*/
private Integer index;
/**
* 电压(mV)
*/
private Integer voltage;
}
@Data
public static class MaintainStatus {
/**
* 维护状态数组
*/
private List<MaintainStatusItem> maintain_status_array;
}
@Data
public static class MaintainStatusItem {
/**
* 上次维护类型
*/
private Integer last_maintain_type;
/**
* 上次维护工作架次
*/
private Integer last_maintain_work_sorties;
/**
* 状态
*/
private Integer state;
/**
* 上次维护时间(秒)
*/
private Long last_maintain_time;
}
@Data
public static class Coordinate {
/**
* 纬度
*/
private Double latitude;
/**
* 经度
*/
private Double longitude;
/**
* 高度(m)
*/
private Double height;
}
@Data
public static class RelativeAlternateLandPoint {
/**
* 安全降落高度(m)
*/
private Integer safe_land_height;
/**
* 纬度
*/
private Double latitude;
/**
* 经度
*/
private Double longitude;
/**
* 状态
*/
private Integer status;
}
@Data
public static class BackupBattery {
/**
* 温度(℃)
*/
private Double temperature;
/**
* 电压(mV)
*/
private Integer voltage;
/**
* 开关状态
*/
private Integer switch1;
}
@Data
public static class DroneChargeState {
/**
* 电量百分比
*/
private Integer capacity_percent;
/**
* 充电状态
*/
private Integer state;
}
@Data
public static class SubDevice {
/**
* 设备是否配对
*/
private Integer device_paired;
/**
* 设备SN
*/
private String device_sn;
/**
* 设备在线状态
*/
private Integer device_online_status;
/**
* 设备型号key
*/
private String device_model_key;
}
@Data
public static class PositionState {
/**
* 是否校准
*/
private Integer is_calibration;
/**
* RTK卫星数量
*/
private Integer rtk_number;
/**
* GPS卫星数量
*/
private Integer gps_number;
/**
* 是否固定
*/
private Integer is_fixed;
/**
* 质量
*/
private Integer quality;
}
@Data
public static class NetworkState {
/**
* 速率
*/
private Integer rate;
/**
* 类型
*/
private Integer type;
/**
* 质量
*/
private Integer quality;
}
@Data
public static class AlternateLandPoint {
/**
* 安全降落高度(m)
*/
private Integer safe_land_height;
/**
* 纬度
*/
private Double latitude;
/**
* 是否已配置
*/
private Integer is_configured;
/**
* 经度
*/
private Double longitude;
/**
* 高度(m)
*/
private Double height;
}
@Data
public static class AirConditioner {
/**
* 切换时间
*/
private Integer switch_time;
/**
* 空调状态
*/
private Integer air_conditioner_state;
}
}
@@ -0,0 +1,697 @@
package com.central.device.websocket.model.message;
import lombok.Data;
import java.util.List;
/**
* 无人机遥测数据事件消息
* 对应 JetLinks 平台的 /message/event/msg_alarm 主题
* 包含无人机飞行状态、电池、GPS、相机等完整遥测数据
*
* @author lishilin
* @date 2025-01-19
*/
@Data
public class MsgAlarmEventMessage {
/**
* 请求ID
*/
private String requestId;
/**
* 主题
*/
private String topic;
/**
* 消息类型
*/
private String type;
/**
* 载荷
*/
private Payload payload;
@Data
public static class Payload {
/**
* 消息头
*/
private Headers headers;
/**
* 消息ID
*/
private String messageId;
/**
* 设备ID
*/
private String deviceId;
/**
* 时间戳
*/
private Long timestamp;
/**
* 事件类型
*/
private String event;
/**
* 消息类型
*/
private String messageType;
/**
* 事件数据
*/
private EventData data;
}
@Data
public static class Headers {
private String deviceName;
private String productName;
private String productId;
private String _uid;
private String creatorId;
private String traceparent;
}
@Data
public static class EventData {
/**
* 设备ID
*/
private String deviceId;
/**
* 时间戳
*/
private Long timestamp;
/**
* 无人机遥测数据
*/
private DroneData data;
}
@Data
public static class DroneData {
// ============ 基本飞行数据 ============
/**
* 纬度
*/
private Double latitude;
/**
* 经度
*/
private Double longitude;
/**
* 高度(m)
*/
private Double height;
/**
* 海拔(m)
*/
private Double elevation;
/**
* 返航高度(m)
*/
private Integer rth_altitude;
/**
* 国家代码
*/
private String country;
/**
* 水平速度(m/s)
*/
private Double horizontal_speed;
/**
* 垂直速度(m/s)
*/
private Double vertical_speed;
/**
* 风速(m/s)
*/
private Double wind_speed;
/**
* 风向(度)
*/
private Double wind_direction;
/**
* 飞行模式
*/
private Integer mode_code;
/**
* 档位
*/
private Integer gear;
// ============ 姿态数据 ============
/**
* 偏航角(度)
*/
private Double attitude_head;
/**
* 俯仰角(度)
*/
private Double attitude_pitch;
/**
* 横滚角(度)
*/
private Double attitude_roll;
// ============ 电池信息 ============
/**
* 电池信息
*/
private BatteryInfo battery;
// ============ 存储信息 ============
/**
* 存储信息
*/
private StorageInfo storage;
// ============ 定位状态 ============
/**
* 定位状态
*/
private PositionState position_state;
// ============ 飞行统计 ============
/**
* 累计飞行时间(秒)
*/
private Double total_flight_time;
/**
* 累计飞行距离(米)
*/
private Double total_flight_distance;
/**
* 累计飞行架次
*/
private Integer total_flight_sorties;
/**
* 与Home点的距离(米)
*/
private Double home_distance;
// ============ 限制状态 ============
/**
* 距离限制状态
*/
private DistanceLimitStatus distance_limit_status;
/**
* 高度限制(米)
*/
private Integer height_limit;
/**
* 是否接近高度限制
*/
private Integer is_near_height_limit;
/**
* 是否接近区域限制
*/
private Integer is_near_area_limit;
// ============ 设备状态 ============
/**
* 激活时间(秒)
*/
private Long activation_time;
/**
* 夜间灯光状态
*/
private Integer night_lights_state;
/**
* RID状态
*/
private Boolean rid_state;
/**
* 航迹ID
*/
private String track_id;
/**
* 遥控器丢失动作
*/
private Integer rc_lost_action;
/**
* 最佳链路网关
*/
private String best_link_gateway;
// ============ 避障信息 ============
/**
* 避障状态
*/
private ObstacleAvoidance obstacle_avoidance;
// ============ 维护状态 ============
/**
* 维护状态
*/
private MaintainStatus maintain_status;
// ============ FTS信息 ============
/**
* FTS信息
*/
private FtsInfo fts_info;
// ============ 相机信息 ============
/**
* 相机列表
*/
private List<CameraInfo> cameras;
// ============ 云台信息(动态key,如98-0-0) ============
// 这部分数据需要通过JSONObject动态获取
}
@Data
public static class BatteryInfo {
/**
* 电量百分比
*/
private Integer capacity_percent;
/**
* 剩余飞行时间(秒)
*/
private Integer remain_flight_time;
/**
* 降落电量
*/
private Integer landing_power;
/**
* 返航电量
*/
private Integer return_home_power;
/**
* 剩余作业时间(秒)
*/
private Integer remain_job_time;
/**
* 电池列表
*/
private List<Battery> batteries;
}
@Data
public static class Battery {
/**
* 电量百分比
*/
private Integer capacity_percent;
/**
* 子类型
*/
private Integer sub_type;
/**
* 高压存储天数
*/
private Integer high_voltage_storage_days;
/**
* 温度(℃)
*/
private Double temperature;
/**
* 索引
*/
private Integer index;
/**
* 固件版本
*/
private String firmware_version;
/**
* 序列号
*/
private String sn;
/**
* 类型
*/
private Integer type;
/**
* 循环次数
*/
private Integer loop_times;
/**
* 电压(mV)
*/
private Integer voltage;
}
@Data
public static class StorageInfo {
/**
* 总容量(KB)
*/
private Long total;
/**
* 已用容量(KB)
*/
private Long used;
}
@Data
public static class PositionState {
/**
* RTK卫星数量
*/
private Integer rtk_number;
/**
* GPS卫星数量
*/
private Integer gps_number;
/**
* 是否固定
*/
private Integer is_fixed;
/**
* 定位质量
*/
private Integer quality;
}
@Data
public static class DistanceLimitStatus {
/**
* 距离限制(米)
*/
private Integer distance_limit;
/**
* 是否接近距离限制
*/
private Integer is_near_distance_limit;
/**
* 状态
*/
private Integer state;
}
@Data
public static class ObstacleAvoidance {
/**
* 水平避障
*/
private Integer horizon;
/**
* 下方避障
*/
private Integer downside;
/**
* 上方避障
*/
private Integer upside;
}
@Data
public static class MaintainStatus {
/**
* 维护状态数组
*/
private List<MaintainStatusItem> maintain_status_array;
}
@Data
public static class MaintainStatusItem {
/**
* 上次维护飞行时间
*/
private Integer last_maintain_flight_time;
/**
* 上次维护类型
*/
private Integer last_maintain_type;
/**
* 上次维护飞行架次
*/
private Integer last_maintain_flight_sorties;
/**
* 状态
*/
private Integer state;
/**
* 上次维护时间
*/
private Long last_maintain_time;
}
@Data
public static class FtsInfo {
/**
* FTS序列号
*/
private String fts_sn;
/**
* FTS时间戳
*/
private Long fts_timestamp;
/**
* FTS有效时长
*/
private Integer fts_valid_duration;
/**
* FTS状态
*/
private Integer fts_status;
/**
* FTS验证码
*/
private String fts_verification_code;
/**
* FTS固件版本
*/
private String fts_firmware_version;
}
@Data
public static class CameraInfo {
/**
* 相机模式
*/
private Integer camera_mode;
/**
* 剩余录像时长(秒)
*/
private Integer remain_record_duration;
/**
* 广角对焦值
*/
private Integer wide_focus_value;
/**
* 广角对焦状态
*/
private Integer wide_focus_state;
/**
* 广角曝光模式
*/
private Integer wide_exposure_mode;
/**
* 录像状态
*/
private Integer recording_state;
/**
* 变焦对焦值
*/
private Integer zoom_focus_value;
/**
* 变焦对焦状态
*/
private Integer zoom_focus_state;
/**
* 剩余拍照数量
*/
private Integer remain_photo_num;
/**
* 拍照状态
*/
private Integer photo_state;
/**
* 广角对焦模式
*/
private Integer wide_focus_mode;
/**
* 变焦曝光模式
*/
private Integer zoom_exposure_mode;
/**
* 载荷索引
*/
private String payload_index;
/**
* 变焦倍数
*/
private Double zoom_factor;
/**
* 变焦ISO
*/
private Integer zoom_iso;
/**
* 变焦对焦模式
*/
private Integer zoom_focus_mode;
/**
* 广角ISO
*/
private Integer wide_iso;
/**
* 广角快门速度
*/
private Integer wide_shutter_speed;
/**
* 广角曝光值
*/
private Integer wide_exposure_value;
/**
* 变焦快门速度
*/
private Integer zoom_shutter_speed;
/**
* 变焦曝光值
*/
private Integer zoom_exposure_value;
/**
* 录像时长(秒)
*/
private Integer record_time;
}
/**
* 云台信息(动态数据,如98-0-0)
*/
@Data
public static class GimbalInfo {
/**
* 测量目标误差状态
*/
private Integer measure_target_error_state;
/**
* 测量目标距离(米)
*/
private Double measure_target_distance;
/**
* 测量目标纬度
*/
private Double measure_target_latitude;
/**
* 测量目标经度
*/
private Double measure_target_longitude;
/**
* 测量目标高度(米)
*/
private Double measure_target_altitude;
/**
* 云台偏航角(度)
*/
private Double gimbal_yaw;
/**
* 云台俯仰角(度)
*/
private Double gimbal_pitch;
/**
* 云台横滚角(度)
*/
private Double gimbal_roll;
/**
* 载荷索引
*/
private String payload_index;
/**
* 变焦倍数
*/
private Double zoom_factor;
}
}
@@ -0,0 +1,68 @@
package com.central.device.websocket.model.message;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
/**
* 设备属性上报消息
* 对应 JetLinks 平台的 /message/property/report 主题
*
* @author lishilin
* @date 2025-01-19
*/
@Data
public class PropertyReportMessage {
/**
* 请求ID
*/
private String requestId;
/**
* 主题
*/
private String topic;
/**
* 消息类型
*/
private String type;
/**
* 载荷
*/
private Payload payload;
@Data
public static class Payload {
/**
* 消息头
*/
private JSONObject headers;
/**
* 消息ID
*/
private String messageId;
/**
* 设备ID
*/
private String deviceId;
/**
* 时间戳
*/
private Long timestamp;
/**
* 消息类型
*/
private String messageType;
/**
* 属性数据(动态结构,根据设备类型不同而不同)
*/
private JSONObject properties;
}
}