feat: complete reverse engineering, standard Maven structure, detailed code annotations and IoT-M platform architecture
This commit is contained in:
1 parent
e8dc09fb3c
commit
cd6a4c70e7
3045 files changed
+566733
-1
No files matched your search
@@ -0,0 +1,592 @@
|
||||
package com.midm.websocket.message;
|
||||
|
||||
import com.google.api.client.util.Strings;
|
||||
import com.google.gson.internal.LinkedTreeMap;
|
||||
import com.midm.model.device.Device;
|
||||
import com.midm.model.device.DeviceGroup;
|
||||
import com.midm.model.device.DeviceLicense;
|
||||
import com.midm.model.file.AppFile;
|
||||
import com.midm.model.file.OtaFile;
|
||||
import com.midm.model.message.MIDM_REQUEST;
|
||||
import com.midm.model.message.MidmPacket;
|
||||
import com.midm.model.message.MidmQuery;
|
||||
import com.midm.model.message.MidmResponse;
|
||||
import com.midm.model.org.Site;
|
||||
import com.midm.model.org.User;
|
||||
import com.midm.service.device.DeviceReportService;
|
||||
import com.midm.service.device.DeviceService;
|
||||
import com.midm.service.file.DeviceFilesService;
|
||||
import com.midm.service.file.FileService;
|
||||
import com.midm.service.log.LogService;
|
||||
import com.midm.service.message.MidmWebSocketSession;
|
||||
import com.midm.service.message.WebSocketSessionManager;
|
||||
import com.midm.service.org.SiteService;
|
||||
import com.midm.service.org.UserService;
|
||||
import com.midm.service.system.HostLicenseService;
|
||||
import com.midm.service.system.SettingsService;
|
||||
import com.mitac.cell.data.McDecompress;
|
||||
import com.mitac.cell.db.DbObject;
|
||||
import com.mitac.cell.utils.McDateTimeUtils;
|
||||
import com.mitac.cell.utils.McJsonUtils;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
import org.joda.time.DateTime;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.BinaryMessage;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.PongMessage;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.WebSocketMessage;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
/**
|
||||
* ======================================================================================
|
||||
* WebSocket 核心消息分发网关与连接生命周期处理器 (QueryHandler)
|
||||
* ======================================================================================
|
||||
*
|
||||
* <p>【架构地位与核心职责】
|
||||
* 1. 作为云端与边缘受控移动终端(Android Agent / DPC)及 Web 前端管理端的核心通信网关。
|
||||
* 2. 连接生命周期管理:
|
||||
* - 建立连接认证与识别(区分是设备端 Device 还是管理用户 User);
|
||||
* - 动态配置单连接缓冲区阈值(避免高频遥测或截屏传输导致 OOM);
|
||||
* - 断开连接时清理 Session 路由表,触发设备离线状态变更。
|
||||
* 3. 混合消息协议解析:
|
||||
* - 文本消息(TextMessage):处理轻量级心跳与控制命令 JSON;
|
||||
* - 二进制压缩消息(BinaryMessage):通过 {@link McDecompress} 解压 GZIP 报文,降低蜂窝网络流量开销;
|
||||
* - 心跳帧(PongMessage):维护自适应心跳时间戳,防连接假死。
|
||||
* 4. 业务事件总线(onFeedback):
|
||||
* - ENROLL(设备注册与许可绑定):校验 SN 序列号、租户白名单、自动签发 License、归属分组;
|
||||
* - DEVICE_INFO(遥测与固件检测):更新设备运行属性,检测 OTA 固件镜像与 SKU 版本更新;
|
||||
* - RTC(WebRTC 信令转发):打通 Web 管理员与移动终端的远程桌面/远程控制数据通道;
|
||||
* - COMMAND / EXEC:下发即时控制指令(锁屏、重启、擦除、应用静默安装);
|
||||
* - DEVICE_LOG:受控端运行与排障审计日志远程上报。
|
||||
*
|
||||
* @author MiDM Core Platform Team
|
||||
*/
|
||||
@Component
|
||||
public class QueryHandler implements WebSocketHandler {
|
||||
|
||||
@Autowired
|
||||
private SiteService siteService;
|
||||
|
||||
@Autowired
|
||||
private DeviceFilesService deviceFilesService;
|
||||
|
||||
/** 会话管理器:维护全局在线 Session 拓扑映射与广播路由 */
|
||||
@Autowired
|
||||
private WebSocketSessionManager sessionManager;
|
||||
|
||||
/** 设备核心服务:处理设备注册、更新、分组与授权逻辑 */
|
||||
@Autowired
|
||||
private DeviceService deviceService;
|
||||
|
||||
/** 设备遥测与监控报表服务(Lazy 延迟加载,防止循环依赖注入) */
|
||||
@Autowired
|
||||
@Lazy
|
||||
private DeviceReportService deviceReportService;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private FileService fileService;
|
||||
|
||||
/** 系统授权服务:单租户 / 多租户 License 规则校验 */
|
||||
@Autowired
|
||||
private HostLicenseService hostLicenseService;
|
||||
|
||||
/** 审计日志服务:记录设备注册、策略变更等关键安全事件 */
|
||||
@Autowired
|
||||
private LogService logService;
|
||||
|
||||
@Autowired
|
||||
private SettingsService settingsService;
|
||||
|
||||
/**
|
||||
* WebSocket 连接建立成功后的回调(握手完成)
|
||||
*
|
||||
* @param session 原生 WebSocket 会话对象
|
||||
*/
|
||||
@Override
|
||||
public void afterConnectionEstablished(WebSocketSession session) {
|
||||
try {
|
||||
// 1. 将原生会话包装为系统定制的 MidmWebSocketSession,提取握手 Header/Query 中的鉴权凭证
|
||||
MidmWebSocketSession midmSession = this.sessionManager.toMidmSocketSession(session, true);
|
||||
if (midmSession != null) {
|
||||
// 2. 根据系统配置动态设置二进制与文本消息的最大缓冲区容量(防内存溢出)
|
||||
int bufferSize = this.settingsService.webSocketBufferSize();
|
||||
session.setBinaryMessageSizeLimit(bufferSize);
|
||||
session.setTextMessageSizeLimit(bufferSize);
|
||||
|
||||
// 3. 区分连接主体身份:如果是设备端连接,触发上线事件;如果是后台管理员,注册用户会话
|
||||
if (midmSession.getDevice() != null) {
|
||||
this.sessionManager.onConnected(midmSession);
|
||||
} else {
|
||||
User user = midmSession.getUser();
|
||||
if (user != null) {
|
||||
this.sessionManager.register(midmSession);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WebSocket 连接关闭回调(正常断开或网络异常中止)
|
||||
*
|
||||
* @param session 原生 WebSocket 会话对象
|
||||
* @param status 断开状态码与原因
|
||||
*/
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
|
||||
try {
|
||||
if (this.sessionManager != null) {
|
||||
// 从全局路由表中注销该 Session,标记设备为离线状态并广播通知关注该设备的管理前端
|
||||
this.sessionManager.onDisconnected(session, status);
|
||||
}
|
||||
} catch (Exception var4) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WebSocket 消息接收总入口
|
||||
*
|
||||
* @param session 原生会话
|
||||
* @param message 抽象 WebSocket 消息载荷
|
||||
*/
|
||||
@Override
|
||||
public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {
|
||||
MidmWebSocketSession midmSession = this.sessionManager.toMidmSocketSession(session, false);
|
||||
if (midmSession != null) {
|
||||
// 1. 刷新活跃时间戳(Heartbeat Timestamp)
|
||||
midmSession.updatePongTimeStamp();
|
||||
|
||||
// 2. 流量统计:如果租户开启了移动蜂窝流量采集,根据阈值触发流量上报
|
||||
if (midmSession.getDevice() != null) {
|
||||
Site site = this.siteService.findByUuid(midmSession.getSiteUuid());
|
||||
if (site != null && site.collectDataUsage() && midmSession.needToUpdateDataUsage()) {
|
||||
this.deviceReportService.updateDataUsage(midmSession.getDevice(), (Date)null);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 根据消息协议帧类型进行分别处理
|
||||
if (message instanceof PongMessage) {
|
||||
if (session.isOpen()) {
|
||||
midmSession.pong();
|
||||
this.handlePongMessage(midmSession, (PongMessage)message);
|
||||
} else {
|
||||
midmSession.close(CloseStatus.SESSION_NOT_RELIABLE);
|
||||
}
|
||||
} else if (message instanceof TextMessage) {
|
||||
this.handleTextMessage(midmSession, (TextMessage)message);
|
||||
} else if (message instanceof BinaryMessage) {
|
||||
this.handleBinaryMessage(midmSession, (BinaryMessage)message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理文本格式消息(JSON 报文或轻量心跳字符串)
|
||||
*
|
||||
* @param session 包装会话
|
||||
* @param message 文本消息帧
|
||||
*/
|
||||
public void handleTextMessage(MidmWebSocketSession session, TextMessage message) {
|
||||
String payload = (String)message.getPayload();
|
||||
if (!Strings.isNullOrEmpty(payload)) {
|
||||
if (payload.equals("ping")) {
|
||||
// 轻量文本心跳处理
|
||||
this.sessionManager.onPing(session);
|
||||
} else {
|
||||
// 反序列化为统一定义的业务数据包 MidmPacket
|
||||
MidmPacket packet = (MidmPacket)McJsonUtils.toObject(payload, MidmPacket.class);
|
||||
if (packet != null) {
|
||||
this.sessionManager.sendMessage(packet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 【IoT 网络优化亮点】处理二进制压缩消息帧
|
||||
*
|
||||
* <p>移动设备为了节省 4G/5G 流量并提高吞吐量,将大量遥测数据(如设备所有已安装应用、电池历史等)
|
||||
* 在端侧经过 Deflate/GZIP 压缩后传输。此处进行高性能内存解压后再转为业务包。
|
||||
*
|
||||
* @param session 包装会话
|
||||
* @param message 二进制消息帧
|
||||
*/
|
||||
public void handleBinaryMessage(MidmWebSocketSession session, BinaryMessage message) {
|
||||
ByteBuffer buffer = (ByteBuffer)message.getPayload();
|
||||
if (buffer != null) {
|
||||
// 调用自研压缩工具类进行数据解压
|
||||
byte[] decompressed = McDecompress.decompress(buffer.asReadOnlyBuffer());
|
||||
if (decompressed != null && decompressed.length != 0) {
|
||||
MidmPacket packet = (MidmPacket)McJsonUtils.toObject(decompressed, MidmPacket.class);
|
||||
if (packet != null) {
|
||||
String request = packet.getQuery().getRequest();
|
||||
if (!Strings.isNullOrEmpty(request) && request.equals("ping")) {
|
||||
this.sessionManager.onPing(session);
|
||||
} else if (packet.getFeedback() != null) {
|
||||
// 转发给业务反馈分发总线
|
||||
this.onFeedback(session, packet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理客户端响应的 Pong 心跳帧
|
||||
*/
|
||||
protected void handlePongMessage(MidmWebSocketSession session, PongMessage message) {
|
||||
this.sessionManager.onPong(session);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
|
||||
}
|
||||
|
||||
/**
|
||||
* 【核心业务路由器】处理边缘终端返回的各类操作响应(Feedback)
|
||||
*
|
||||
* @param midmSession 触发该事件的设备连接会话
|
||||
* @param packet 包含 Query 原请求信息与 Feedback 执行结果的数据包
|
||||
*/
|
||||
private void onFeedback(MidmWebSocketSession midmSession, MidmPacket packet) {
|
||||
MidmQuery query = packet.getQuery();
|
||||
MidmResponse feedback = packet.getFeedback();
|
||||
String serialNo = midmSession.serialNo();
|
||||
|
||||
switch (MIDM_REQUEST.get(query.getCode())) {
|
||||
case ENROLL:
|
||||
// -------------------------------------------------------------
|
||||
// 1. 设备注册与入网接入(Device Enrollment)
|
||||
// -------------------------------------------------------------
|
||||
if (Strings.isNullOrEmpty(serialNo)) {
|
||||
// 必须包含出厂硬件唯一序列号 SN
|
||||
midmSession.sendFeedback(461, "No serial no. defined.", (Object)null);
|
||||
midmSession.close(CloseStatus.NOT_ACCEPTABLE);
|
||||
} else {
|
||||
Device device = (Device)McJsonUtils.toObject(McJsonUtils.toJson(feedback.getData()), Device.class);
|
||||
Device existDevice = this.deviceService.findBySerialNo(midmSession.serialNo());
|
||||
UUID siteUuid = existDevice == null ? device.getSiteUuid() : existDevice.getSiteUuid();
|
||||
|
||||
// 若设备更换了序列号,同步更新索引
|
||||
if (existDevice != null && !serialNo.equals(existDevice.getSerialNo())) {
|
||||
existDevice.setSerialNo(serialNo);
|
||||
this.deviceService.updateSerialNo(existDevice, serialNo);
|
||||
existDevice = this.deviceService.findBySerialNo(serialNo);
|
||||
}
|
||||
|
||||
Site currentSite = this.siteService.findByUuid(siteUuid);
|
||||
if (currentSite == null) {
|
||||
midmSession.sendFeedback(451, "No site available.", (Object)null);
|
||||
midmSession.close(CloseStatus.NOT_ACCEPTABLE);
|
||||
} else if (currentSite.limitRegisteredDeviceOnly() && existDevice == null) {
|
||||
// 开启了安全白名单:只允许后台预导入的设备接入
|
||||
midmSession.sendFeedback(463, "Enrollement rejected due to un-registered device.", (Object)null);
|
||||
midmSession.close(CloseStatus.NOT_ACCEPTABLE);
|
||||
} else {
|
||||
String siteModel = currentSite.getModel();
|
||||
boolean isSelfEnroll = midmSession.selfEnroll();
|
||||
|
||||
if (existDevice == null) {
|
||||
// 新设备首次注册
|
||||
device.init();
|
||||
if (device.getGroupUuid() != null) {
|
||||
DeviceGroup group = this.deviceService.findDeviceGroup(device.getGroupUuid());
|
||||
device.setDeviceGroup(group);
|
||||
}
|
||||
|
||||
// 自动签发并激活试用/指定 License 许可
|
||||
if (!this.hostLicenseService.isStandalone() && (siteModel == null || siteModel.equals("midm"))) {
|
||||
DeviceLicense license = this.deviceService.setTrialLicense(device);
|
||||
device.setLicense(license);
|
||||
String licenseIdName = midmSession.licenseId();
|
||||
if (!Strings.isNullOrEmpty(licenseIdName)) {
|
||||
boolean autoRenew = midmSession.autoRenew();
|
||||
boolean renewToSameModel = midmSession.renewToSameModel();
|
||||
license = this.deviceService.setLicense(device, licenseIdName, autoRenew, renewToSameModel);
|
||||
if (license != null) {
|
||||
device.setLicense(license);
|
||||
}
|
||||
}
|
||||
this.deviceService.activateLicense(license);
|
||||
}
|
||||
existDevice = device;
|
||||
} else {
|
||||
// 存量设备重新连接/注册
|
||||
if (!device.getProfile().isEmpty()) {
|
||||
existDevice.getProfile().putAll(device.getProfile());
|
||||
}
|
||||
|
||||
if (midmSession.ifExistsOption().option != 0) {
|
||||
// 校验 License 是否过期
|
||||
if (!this.hostLicenseService.isStandalone() && existDevice.getLicense().isExpired()) {
|
||||
midmSession.sendFeedback(115, "Device license expired.", (Object)null);
|
||||
midmSession.close(CloseStatus.NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
if (isSelfEnroll && !device.isAssociated() && device.getGroupUuid() != null) {
|
||||
DeviceGroup group = this.deviceService.findDeviceGroup(device.getGroupUuid());
|
||||
existDevice.setDeviceGroup(group);
|
||||
}
|
||||
|
||||
existDevice.setUpdated();
|
||||
// 关联设备所属企业员工(User Owner)
|
||||
Object jOwner = device.getProfile("owner");
|
||||
if (jOwner != null) {
|
||||
LinkedTreeMap<String, ?> map = (LinkedTreeMap)jOwner;
|
||||
String email = String.valueOf(map.get("email"));
|
||||
if (!Strings.isNullOrEmpty(email)) {
|
||||
User user = this.userService.findUserByEmail(siteUuid, email);
|
||||
if (user != null) {
|
||||
existDevice.setOwner(user);
|
||||
} else {
|
||||
existDevice.setProfile("owner", jOwner);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 激活或延长 License
|
||||
if (!this.hostLicenseService.isStandalone() && (siteModel == null || siteModel.equals("midm"))) {
|
||||
DeviceLicense license = existDevice.getLicense();
|
||||
if (license != null) {
|
||||
if (!license.isActivated() || !existDevice.isEnrolled() && existDevice.getLastCheckedIn() == null) {
|
||||
license = this.deviceService.activateLicense(license);
|
||||
}
|
||||
if (license != null) {
|
||||
existDevice.setLicense(license);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 保存并更新设备在 MongoDB 中的最新状态
|
||||
boolean wasEnrolled = existDevice.isEnrolled();
|
||||
existDevice.setEnabled(true);
|
||||
existDevice.setEnrolled(new Date());
|
||||
existDevice.setLastCheckedIn();
|
||||
existDevice.setClientVersion(midmSession.clientVersion());
|
||||
this.deviceService.save(existDevice);
|
||||
|
||||
// 记录设备入网审计日志
|
||||
this.logService.saveDeviceLog(existDevice.getUuid(), "event", wasEnrolled ? "Re-enrolled" : "Enrolled.", new Date());
|
||||
|
||||
// 注册全局路由 Session
|
||||
midmSession.setHolder(existDevice);
|
||||
this.sessionManager.register(midmSession);
|
||||
|
||||
if (!this.hostLicenseService.isStandalone() && existDevice.getLicense().isExpired()) {
|
||||
midmSession.sendFeedback(115, "Device license is expired.", (Object)null);
|
||||
midmSession.close(CloseStatus.NOT_ACCEPTABLE);
|
||||
} else {
|
||||
// 注册成功,下发指令与精简设备配置(状态码 111)
|
||||
midmSession.sendFeedback(111, (String)null, this.sessionManager.optimizeDeviceInfo(existDevice));
|
||||
}
|
||||
}
|
||||
}
|
||||
case CHECKIN:
|
||||
default:
|
||||
break;
|
||||
|
||||
case DEVICE_INFO:
|
||||
// -------------------------------------------------------------
|
||||
// 2. 设备状态与硬件属性上报(包含 OTA 固件变更检测)
|
||||
// -------------------------------------------------------------
|
||||
DbObject feedBackData = feedback.getDataAsDbObject();
|
||||
DbObject newProfile = feedBackData.getDbObject(new String[]{"profile"});
|
||||
Device currentDev = midmSession.getDevice();
|
||||
if (currentDev.getProfileCategory(new String[]{"software_info"}) != null && newProfile.containsKey("software_info")) {
|
||||
// 检查设备是否刚完成了系统镜像(System Image)或区域镜像(Region Image)的 OTA 升级
|
||||
this.checkImageUpdate(currentDev, newProfile.getDbObject(new String[]{"software_info"}));
|
||||
}
|
||||
this.deviceService.updateDeviceInfo(currentDev, newProfile);
|
||||
break;
|
||||
|
||||
case QUERY:
|
||||
// -------------------------------------------------------------
|
||||
// 3. 通用查询与文件抓取响应(如远程拉取设备日志或截图)
|
||||
// -------------------------------------------------------------
|
||||
if (feedback.getCode() == 138) {
|
||||
DbObject data = feedback.getDataAsDbObject();
|
||||
String hostFile = data.getString("hostFile");
|
||||
String fileName = data.getString("fileName");
|
||||
Device existDev = this.deviceService.findBySerialNo(serialNo);
|
||||
User user = this.userService.findUserByUserUuid(packet.getQuery().getSenderUuid());
|
||||
Site site = this.siteService.findByUuid(existDev.getSiteUuid());
|
||||
String forWhat = query.getCommand();
|
||||
this.deviceFilesService.saveFile(UUID.fromString(hostFile), fileName, user, site, existDev, forWhat);
|
||||
}
|
||||
|
||||
UUID receiverUuid = packet.getRecieverUuid();
|
||||
UUID senderUuid = query.getSenderUuid();
|
||||
if (senderUuid != null) {
|
||||
// 将查询响应精准路由回最初发起查询的 Web 用户 Session
|
||||
this.sessionManager.sendFeedback(midmSession, receiverUuid, senderUuid, packet);
|
||||
} else {
|
||||
this.applyFeedback(midmSession, packet);
|
||||
}
|
||||
break;
|
||||
|
||||
case COMMAND:
|
||||
case EXEC:
|
||||
// -------------------------------------------------------------
|
||||
// 4. 控制指令执行结果回传(如锁机、重启、清除数据等)
|
||||
// -------------------------------------------------------------
|
||||
UUID cmdReceiver = packet.getRecieverUuid();
|
||||
UUID cmdSender = query.getSenderUuid();
|
||||
if (cmdSender != null) {
|
||||
this.sessionManager.sendFeedback(midmSession, cmdReceiver, cmdSender, packet);
|
||||
} else {
|
||||
this.applyFeedback(midmSession, packet);
|
||||
}
|
||||
break;
|
||||
|
||||
case RTC:
|
||||
// -------------------------------------------------------------
|
||||
// 5. WebRTC 信令转发(用于远程桌面与远程操作投屏)
|
||||
// -------------------------------------------------------------
|
||||
UUID rtcReceiver = packet.getRecieverUuid();
|
||||
UUID rtcSender = query.getSenderUuid();
|
||||
if (rtcSender != null) {
|
||||
this.sessionManager.sendFeedback(midmSession, rtcSender, rtcReceiver, packet);
|
||||
}
|
||||
break;
|
||||
|
||||
case DEVICE_STATE:
|
||||
// -------------------------------------------------------------
|
||||
// 6. 设备运行状态推送(广播给关注此租户的管理员界面)
|
||||
// -------------------------------------------------------------
|
||||
UUID stateSender = query.getSenderUuid();
|
||||
this.sessionManager.updateDeviceStatus(midmSession.getSiteUuid(), stateSender, packet);
|
||||
break;
|
||||
|
||||
case DEVICE_LOG:
|
||||
// -------------------------------------------------------------
|
||||
// 7. 设备审计日志入库存储
|
||||
// -------------------------------------------------------------
|
||||
UUID logDevUuid = query.getSenderUuid();
|
||||
String category = query.getParam("category").toString();
|
||||
String log = query.getParam("log").toString();
|
||||
String date = query.getParam("loggedAt").toString();
|
||||
DateTime loggedAt = McDateTimeUtils.parseDate(date, (String)null);
|
||||
this.logService.saveDeviceLog(logDevUuid, category, log, loggedAt != null ? loggedAt.toDate() : null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用设备的业务反馈(网络状态变化、蜂窝数据消耗等)
|
||||
*/
|
||||
private void applyFeedback(MidmWebSocketSession session, MidmPacket packet) {
|
||||
String request = packet.getQuery().getRequest();
|
||||
MidmResponse feedback = packet.getFeedback();
|
||||
String command = (String)packet.getParam("command");
|
||||
Device device = session.getDevice();
|
||||
|
||||
switch (request) {
|
||||
case "network":
|
||||
if (Strings.isNullOrEmpty(command)) {
|
||||
this.deviceService.updateProfile(device.getUuid(), "network", feedback.getRefereceAsDbObject());
|
||||
} else {
|
||||
switch (command) {
|
||||
case "active_network":
|
||||
// 更新设备当前活跃网络(Wi-Fi / 移动蜂窝网络类型)
|
||||
DbObject data = feedback.getDataAsDbObject();
|
||||
this.deviceService.updateActiveNetwork(device.getUuid(), session.getRemoteIpAddress(), data);
|
||||
String type = data.getString("type");
|
||||
boolean isMobileConnected = "MOBILE".equals(type);
|
||||
if (isMobileConnected) {
|
||||
int clientVersion = session.clientVersion();
|
||||
// 兼容性保护:若旧版客户端在移动蜂窝网络下存在漫游漏洞,推送最新客户端升级包
|
||||
if (this.deviceService.hasRoamingProblem((long)clientVersion)) {
|
||||
AppFile app = this.fileService.findLatest(device.getUuid(), "com.mitac.midm.client", clientVersion);
|
||||
if (app != null && app.getVersionCode() > (long)clientVersion) {
|
||||
session.sendClientUpdateRequest(device, app);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "data_usage":
|
||||
// 记录移动数据用量统计
|
||||
this.deviceReportService.saveDataUsage(device, feedback.getDataAsDbObject());
|
||||
}
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 【IoT 固件检测算法】对比设备上报的 Build 版本号与镜像信息,判定是否发生了 OTA 固件更新
|
||||
*
|
||||
* @param device 设备持久化实体
|
||||
* @param data 设备最新上报的软件与固件构建信息
|
||||
*/
|
||||
private void checkImageUpdate(Device device, DbObject data) {
|
||||
if (device.getProfileCategory(new String[]{"software_info"}) != null) {
|
||||
String curDisplayId = data.getString("display_id");
|
||||
if (curDisplayId == null) {
|
||||
curDisplayId = data.getString("build_no");
|
||||
}
|
||||
|
||||
String curSkuId = OtaFile.parseSkuId(curDisplayId);
|
||||
String prevSkuId = device.getSkuId();
|
||||
String prevDisplayId = device.getDisplayId();
|
||||
if (prevDisplayId == null) {
|
||||
prevDisplayId = device.getBuildNo();
|
||||
}
|
||||
|
||||
boolean isSameSku = true;
|
||||
// 1. 检查硬件 SKU 是否变更(例如跨产品固件刷机)
|
||||
if (curSkuId != null && !curSkuId.equals(prevSkuId)) {
|
||||
isSameSku = false;
|
||||
this.deviceReportService.resetDevice(device.getUuid());
|
||||
this.deviceService.systemImageUpdated(device, isSameSku, prevDisplayId, curDisplayId, -1L, -1L);
|
||||
} else {
|
||||
// 2. 检查系统镜像 Build 日期是否有升级
|
||||
Long curBuildDate = data.getLong("build_date");
|
||||
long prevBuildDate = device.getBuildDate();
|
||||
boolean systemImageUpdated = curBuildDate != prevBuildDate;
|
||||
if (systemImageUpdated) {
|
||||
boolean isUpgraded = curBuildDate > prevBuildDate;
|
||||
if (!isUpgraded) {
|
||||
// 若为固件降级,重置设备状态
|
||||
this.deviceReportService.resetDevice(device.getUuid());
|
||||
}
|
||||
this.deviceService.systemImageUpdated(device, isSameSku, prevDisplayId, curDisplayId, prevBuildDate, curBuildDate);
|
||||
}
|
||||
|
||||
// 3. 检查区域化脚本与定制镜像(Region Image)版本
|
||||
String curScriptVersion = data.getString("script_version");
|
||||
String preScriptVersion = device.getScriptVersion();
|
||||
boolean regionImageUpdated = false;
|
||||
if (preScriptVersion == null) {
|
||||
if (curScriptVersion != null) {
|
||||
regionImageUpdated = true;
|
||||
}
|
||||
} else {
|
||||
regionImageUpdated = curScriptVersion == null || !preScriptVersion.equals(curScriptVersion);
|
||||
}
|
||||
|
||||
if (regionImageUpdated) {
|
||||
String prevRegionVersion = device.getRegionImgVersion();
|
||||
String curRegionVersion = data.getString("region_version");
|
||||
this.deviceService.regionImageUpdated(device, prevRegionVersion, curRegionVersion, preScriptVersion, curScriptVersion);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsPartialMessages() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user