浇水bug修改
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
package org.dromara.app.controller;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.app.domain.bo.AppVersionBo;
|
||||
import org.dromara.app.domain.vo.AppVersionVo;
|
||||
import org.dromara.app.service.IAppVersionService;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.validate.AddGroup;
|
||||
import org.dromara.common.core.validate.EditGroup;
|
||||
import org.dromara.common.excel.utils.ExcelUtil;
|
||||
import org.dromara.common.idempotent.annotation.RepeatSubmit;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* APP版本
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2026-07-01
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/app/version")
|
||||
public class AppVersionController extends BaseController {
|
||||
|
||||
private final IAppVersionService appVersionService;
|
||||
|
||||
/**
|
||||
* 查询APP版本列表
|
||||
*/
|
||||
@SaCheckPermission("app:version:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<AppVersionVo> list(AppVersionBo bo, PageQuery pageQuery) {
|
||||
return appVersionService.queryPageList(bo, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出APP版本列表
|
||||
*/
|
||||
@SaCheckPermission("app:version:export")
|
||||
@Log(title = "APP版本", businessType = BusinessType.EXPORT)
|
||||
@PostMapping("/export")
|
||||
public void export(AppVersionBo bo, HttpServletResponse response) {
|
||||
List<AppVersionVo> list = appVersionService.queryList(bo);
|
||||
ExcelUtil.exportExcel(list, "APP版本", AppVersionVo.class, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取APP版本详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@SaCheckPermission("app:version:query")
|
||||
@GetMapping("/{id}")
|
||||
public R<AppVersionVo> getInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
return R.ok(appVersionService.queryById(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增APP版本
|
||||
*/
|
||||
@SaCheckPermission("app:version:add")
|
||||
@Log(title = "APP版本", businessType = BusinessType.INSERT)
|
||||
@RepeatSubmit()
|
||||
@PostMapping()
|
||||
public R<Void> add(@Validated(AddGroup.class) @RequestBody AppVersionBo bo) {
|
||||
return toAjax(appVersionService.insertByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改APP版本
|
||||
*/
|
||||
@SaCheckPermission("app:version:edit")
|
||||
@Log(title = "APP版本", businessType = BusinessType.UPDATE)
|
||||
@RepeatSubmit()
|
||||
@PutMapping()
|
||||
public R<Void> edit(@Validated(EditGroup.class) @RequestBody AppVersionBo bo) {
|
||||
return toAjax(appVersionService.updateByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除APP版本
|
||||
*
|
||||
* @param ids 主键串
|
||||
*/
|
||||
@SaCheckPermission("app:version:remove")
|
||||
@Log(title = "APP版本", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{ids}")
|
||||
public R<Void> remove(@NotEmpty(message = "主键不能为空")
|
||||
@PathVariable Long[] ids) {
|
||||
return toAjax(appVersionService.deleteWithValidByIds(List.of(ids), true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package org.dromara.app.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* APP版本对象 app_version
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("app_version")
|
||||
public class AppVersion extends BaseEntity {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@TableId(value = "id")
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 平台 android/ios
|
||||
*/
|
||||
private String platform;
|
||||
|
||||
/**
|
||||
* 最新版本号
|
||||
*/
|
||||
private String latestVersion;
|
||||
|
||||
/**
|
||||
* 版本序号
|
||||
*/
|
||||
private Integer versionCode;
|
||||
|
||||
/**
|
||||
* 是否强制更新 0否 1是
|
||||
*/
|
||||
private String forceUpdate;
|
||||
|
||||
/**
|
||||
* 下载地址
|
||||
*/
|
||||
private String downloadUrl;
|
||||
|
||||
/**
|
||||
* 更新说明
|
||||
*/
|
||||
private String releaseNotes;
|
||||
|
||||
/**
|
||||
* 状态 0停用 1启用
|
||||
*/
|
||||
private String status;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package org.dromara.app.domain.bo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.dromara.app.domain.AppVersion;
|
||||
import org.dromara.common.core.validate.AddGroup;
|
||||
import org.dromara.common.core.validate.EditGroup;
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
|
||||
/**
|
||||
* APP版本业务对象 app_version
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2026-07-01
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@AutoMapper(target = AppVersion.class, reverseConvertGenerate = false)
|
||||
public class AppVersionBo extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@NotNull(message = "主键不能为空", groups = { EditGroup.class })
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 平台 android/ios
|
||||
*/
|
||||
@NotBlank(message = "平台 android/ios不能为空", groups = { AddGroup.class, EditGroup.class })
|
||||
private String platform;
|
||||
|
||||
/**
|
||||
* 最新版本号
|
||||
*/
|
||||
@NotBlank(message = "最新版本号不能为空", groups = { AddGroup.class, EditGroup.class })
|
||||
private String latestVersion;
|
||||
|
||||
/**
|
||||
* 版本序号,用于排序取最新版本
|
||||
*/
|
||||
@NotNull(message = "版本序号,用于排序取最新版本不能为空", groups = { AddGroup.class, EditGroup.class })
|
||||
private Long versionCode;
|
||||
|
||||
/**
|
||||
* 是否强制更新 0否 1是
|
||||
*/
|
||||
@NotBlank(message = "是否强制更新 0否 1是不能为空", groups = { AddGroup.class, EditGroup.class })
|
||||
private String forceUpdate;
|
||||
|
||||
/**
|
||||
* 下载地址
|
||||
*/
|
||||
private String downloadUrl;
|
||||
|
||||
/**
|
||||
* 更新说明
|
||||
*/
|
||||
private String releaseNotes;
|
||||
|
||||
/**
|
||||
* 状态 0停用 1启用
|
||||
*/
|
||||
@NotBlank(message = "状态 0停用 1启用不能为空", groups = { AddGroup.class, EditGroup.class })
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package org.dromara.app.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Data
|
||||
public class AppVersionCheckVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 平台类型:android 或 ios
|
||||
*/
|
||||
private String platform;
|
||||
|
||||
/**
|
||||
* APP当前版本号,由客户端上传
|
||||
*/
|
||||
private String currentVersion;
|
||||
|
||||
/**
|
||||
* 后台配置的最新版本号
|
||||
*/
|
||||
private String latestVersion;
|
||||
|
||||
/**
|
||||
* 最新版本序号,用于版本排序
|
||||
*/
|
||||
private Integer versionCode;
|
||||
|
||||
/**
|
||||
* 是否存在可更新版本
|
||||
*/
|
||||
private Boolean updateAvailable;
|
||||
|
||||
/**
|
||||
* 是否强制更新
|
||||
*/
|
||||
private Boolean forceUpdate;
|
||||
|
||||
/**
|
||||
* APP安装包下载地址
|
||||
*/
|
||||
private String downloadUrl;
|
||||
|
||||
/**
|
||||
* 更新说明
|
||||
*/
|
||||
private String releaseNotes;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package org.dromara.app.domain.vo;
|
||||
|
||||
import cn.idev.excel.annotation.ExcelIgnoreUnannotated;
|
||||
import cn.idev.excel.annotation.ExcelProperty;
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import org.dromara.app.domain.AppVersion;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
@ExcelIgnoreUnannotated
|
||||
@AutoMapper(target = AppVersion.class)
|
||||
public class AppVersionVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long id;
|
||||
|
||||
@ExcelProperty(value = "平台 android/ios")
|
||||
private String platform;
|
||||
|
||||
@ExcelProperty(value = "最新版本号")
|
||||
private String latestVersion;
|
||||
|
||||
@ExcelProperty(value = "版本序号,用于排序取最新版本")
|
||||
private Integer versionCode;
|
||||
|
||||
@ExcelProperty(value = "是否强制更新 0否 1是")
|
||||
private String forceUpdate;
|
||||
|
||||
@ExcelProperty(value = "下载地址")
|
||||
private String downloadUrl;
|
||||
|
||||
@ExcelProperty(value = "更新说明")
|
||||
private String releaseNotes;
|
||||
|
||||
@ExcelProperty(value = "状态 0停用 1启用")
|
||||
private String status;
|
||||
|
||||
@ExcelProperty(value = "备注")
|
||||
private String remark;
|
||||
|
||||
@ExcelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
}
|
||||
@@ -1,25 +1,15 @@
|
||||
package org.dromara.app.handler;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.app.domain.AppDevice;
|
||||
import org.dromara.app.domain.bo.AppDeviceBo;
|
||||
import org.dromara.app.mapper.AppDeviceMapper;
|
||||
import org.dromara.app.mqtt.MqttTopicHandler;
|
||||
import org.dromara.app.service.IAppDeviceService;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.redisson.api.RLock;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -32,14 +22,6 @@ public class DeviceDataHandler implements MqttTopicHandler {
|
||||
|
||||
private static final Pattern PATTERN = Pattern.compile("^/([^/]+)/publish/power$");
|
||||
private final IAppDeviceService appDeviceService;
|
||||
private final AppDeviceMapper appDeviceMapper;
|
||||
private static final String DEVICE_STATUS_LOCK_PREFIX = "lock:mqtt:device:status:";
|
||||
|
||||
@Value("${mqtt.command-ack.device-status-cache-prefix}")
|
||||
private String deviceStatusCachePrefix;
|
||||
|
||||
@Value("${mqtt.command-ack.device-status-cache-ttl-seconds}")
|
||||
private int deviceStatusCacheTtlSeconds;
|
||||
private final DeviceIdentityResolver deviceIdentityResolver;
|
||||
|
||||
@Override
|
||||
@@ -60,7 +42,6 @@ public class DeviceDataHandler implements MqttTopicHandler {
|
||||
Map<String, Object> dto = JsonUtils.parseObject(payload, Map.class);
|
||||
if (dto == null || dto.get("powerLevel") == null) {
|
||||
log.warn("[MQTT] 设备电量上报缺少电量字段 时间={} 设备编号={} 消息体={}", HandlerLogTime.now(), deviceNo, payload);
|
||||
refreshDeviceOnline(deviceNo);
|
||||
return;
|
||||
}
|
||||
// 更新设备电量 + 同步在线状态到数据库
|
||||
@@ -68,50 +49,11 @@ public class DeviceDataHandler implements MqttTopicHandler {
|
||||
appDeviceBo.setDeviceNo(deviceNo);
|
||||
appDeviceBo.setPowerLevel(dto.get("powerLevel").toString());
|
||||
appDeviceBo.setPowerLevelUpdatatime(new Date());
|
||||
appDeviceBo.setStatus("1"); // 收到数据 = 在线
|
||||
appDeviceService.updateByBo(appDeviceBo);
|
||||
// 同步刷新 Redis 在线缓存(定时任务离线检测依赖此 Key)
|
||||
refreshDeviceOnline(deviceNo);
|
||||
log.info("[MQTT] 设备电量更新 时间={} 设备编号={} 消息体={}", HandlerLogTime.now(), deviceNo, payload);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQTT] 设备电量更新失败 时间={} 设备标识={} 设备编号={} 消息体={}",
|
||||
HandlerLogTime.now(), deviceIdentity, deviceNo, payload, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新设备在线状态到 Redis(与 MqttCommandAckService 逻辑一致)
|
||||
* 写入幂等,未拿到锁则跳过由后续上报兜底
|
||||
*/
|
||||
private void refreshDeviceOnline(String deviceNo) {
|
||||
RLock lock = RedisUtils.getClient().getLock(DEVICE_STATUS_LOCK_PREFIX + deviceNo);
|
||||
boolean locked = false;
|
||||
try {
|
||||
locked = lock.tryLock(0, 10, TimeUnit.SECONDS);
|
||||
if (!locked) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> statusCache = new HashMap<>();
|
||||
statusCache.put("deviceNo", deviceNo);
|
||||
statusCache.put("status", "1");
|
||||
statusCache.put("lastReportTime", Instant.now().toString());
|
||||
RedisUtils.setCacheObject(
|
||||
deviceStatusCachePrefix + deviceNo,
|
||||
statusCache,
|
||||
Duration.ofSeconds(deviceStatusCacheTtlSeconds)
|
||||
);
|
||||
appDeviceMapper.update(null,
|
||||
new LambdaUpdateWrapper<AppDevice>()
|
||||
.set(AppDevice::getStatus, "1")
|
||||
.eq(AppDevice::getDeviceNo, deviceNo)
|
||||
);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("[MQTT] 刷新设备在线状态被中断 设备编号={}", deviceNo);
|
||||
} finally {
|
||||
if (locked && lock.isHeldByCurrentThread()) {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.dromara.app.handler;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.app.domain.AppDevice;
|
||||
@@ -11,19 +10,12 @@ import org.dromara.app.mqtt.MqttTopicHandler;
|
||||
import org.dromara.app.service.IAppDeviceService;
|
||||
import org.dromara.app.service.IDeviceCommandPublisher;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.redisson.api.RLock;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -39,14 +31,7 @@ DeviceRegisterHandler implements MqttTopicHandler {
|
||||
|
||||
private final IAppDeviceService appDeviceService;
|
||||
private final AppDeviceMapper appDeviceMapper;
|
||||
private static final String DEVICE_STATUS_LOCK_PREFIX = "lock:mqtt:device:status:";
|
||||
private final ObjectProvider<IDeviceCommandPublisher> commandPublisherProvider;
|
||||
|
||||
@Value("${mqtt.command-ack.device-status-cache-prefix}")
|
||||
private String deviceStatusCachePrefix;
|
||||
|
||||
@Value("${mqtt.command-ack.device-status-cache-ttl-seconds}")
|
||||
private int deviceStatusCacheTtlSeconds;
|
||||
private final DeviceIdentityResolver deviceIdentityResolver;
|
||||
|
||||
@Override
|
||||
@@ -59,7 +44,7 @@ DeviceRegisterHandler implements MqttTopicHandler {
|
||||
try {
|
||||
Map<String, Object> dto = JsonUtils.parseObject(payload, Map.class);
|
||||
AppDevice exists = deviceIdentityResolver.resolve(deviceIdentity);
|
||||
String normalizedDeviceMac = resolveDeviceMac(deviceIdentity, dto);
|
||||
String normalizedDeviceMac = resolveDeviceMac(deviceIdentity, dto, exists);
|
||||
if (exists == null && normalizedDeviceMac != null) {
|
||||
exists = appDeviceMapper.selectByMac(normalizedDeviceMac);
|
||||
}
|
||||
@@ -75,7 +60,6 @@ DeviceRegisterHandler implements MqttTopicHandler {
|
||||
}
|
||||
AppDeviceBo device = buildRegisterDevice(deviceNo, normalizedDeviceMac, dto);
|
||||
appDeviceService.registerByMqtt(device);
|
||||
refreshDeviceOnline(deviceNo);
|
||||
sendDeviceNoToDevice(deviceNo, normalizedDeviceMac);
|
||||
log.info("[MQTT] 设备注册 时间={} MAC={} 设备编号={} 消息体={}",
|
||||
HandlerLogTime.now(), normalizedDeviceMac, deviceNo, payload);
|
||||
@@ -88,11 +72,9 @@ DeviceRegisterHandler implements MqttTopicHandler {
|
||||
AppDeviceBo device = new AppDeviceBo();
|
||||
device.setDeviceNo(deviceNo);
|
||||
device.setMacAddress(deviceMac);
|
||||
device.setStatus("1"); // 注册即在线
|
||||
if (dto == null) {
|
||||
return device;
|
||||
}
|
||||
device.setDeviceName(valueAsString(dto.get("deviceName")));
|
||||
device.setDeviceInitName(valueAsString(dto.get("deviceName")));
|
||||
device.setPowerLevel(valueAsString(dto.get("powerLevel")));
|
||||
device.setDeviceEm(valueAsString(dto.get("deviceEm")));
|
||||
@@ -101,9 +83,15 @@ DeviceRegisterHandler implements MqttTopicHandler {
|
||||
return device;
|
||||
}
|
||||
|
||||
private String resolveDeviceMac(String topicDeviceMac, Map<String, Object> dto) {
|
||||
private String resolveDeviceMac(String topicDeviceMac, Map<String, Object> dto, AppDevice exists) {
|
||||
String payloadMac = dto == null ? null : firstNotBlank(dto.get("deviceMac"), dto.get("macAddress"));
|
||||
return normalizeMacAddress(firstNotBlank(payloadMac, topicDeviceMac));
|
||||
if (payloadMac != null && !payloadMac.isBlank()) {
|
||||
return normalizeMacAddress(payloadMac);
|
||||
}
|
||||
if (exists != null && exists.getMacAddress() != null && !exists.getMacAddress().isBlank()) {
|
||||
return normalizeMacAddress(exists.getMacAddress());
|
||||
}
|
||||
return normalizeMacAddress(topicDeviceMac);
|
||||
}
|
||||
|
||||
private String normalizeMacAddress(String macAddress) {
|
||||
@@ -157,39 +145,4 @@ DeviceRegisterHandler implements MqttTopicHandler {
|
||||
private String valueAsString(Object value) {
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新设备在线状态到 Redis;状态写入幂等,未拿到锁则跳过由后续上报兜底
|
||||
*/
|
||||
private void refreshDeviceOnline(String deviceNo) {
|
||||
RLock lock = RedisUtils.getClient().getLock(DEVICE_STATUS_LOCK_PREFIX + deviceNo);
|
||||
boolean locked = false;
|
||||
try {
|
||||
locked = lock.tryLock(0, 10, TimeUnit.SECONDS);
|
||||
if (!locked) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> statusCache = new HashMap<>();
|
||||
statusCache.put("deviceNo", deviceNo);
|
||||
statusCache.put("status", "1");
|
||||
statusCache.put("lastReportTime", Instant.now().toString());
|
||||
RedisUtils.setCacheObject(
|
||||
deviceStatusCachePrefix + deviceNo,
|
||||
statusCache,
|
||||
Duration.ofSeconds(deviceStatusCacheTtlSeconds)
|
||||
);
|
||||
appDeviceMapper.update(null,
|
||||
new LambdaUpdateWrapper<AppDevice>()
|
||||
.set(AppDevice::getStatus, "1")
|
||||
.eq(AppDevice::getDeviceNo, deviceNo)
|
||||
);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("[MQTT] 刷新设备在线状态被中断 设备编号={}", deviceNo);
|
||||
} finally {
|
||||
if (locked && lock.isHeldByCurrentThread()) {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package org.dromara.app.handler;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.app.mqtt.MqttTopicHandler;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 设备在线/离线状态处理器,匹配 /{deviceIdentity}/publish/status。
|
||||
* <p>
|
||||
* deviceIdentity 支持设备编号;设备遗嘱消息允许使用 MAC 地址,处理前统一解析为设备编号。
|
||||
* 设备通过 status=online 标记上线,通过 LWT status=offline 标记异常离线。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DeviceStatusHandler implements MqttTopicHandler {
|
||||
|
||||
private static final Pattern PATTERN = Pattern.compile("^/([^/]+)/publish/status$");
|
||||
private static final String OFFLINE_REASON = "设备 MQTT 状态离线";
|
||||
|
||||
private final DeviceIdentityResolver deviceIdentityResolver;
|
||||
private final MqttDeviceStatusService deviceStatusService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public Pattern topicPattern() {
|
||||
return PATTERN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(String deviceIdentity, String payload) {
|
||||
handle(deviceIdentity, payload, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(String deviceIdentity, String payload, boolean retained) {
|
||||
String deviceNo = deviceIdentityResolver.resolveDeviceNo(deviceIdentity);
|
||||
if (deviceNo == null) {
|
||||
log.warn("[MQTT] 设备状态上报未找到设备 时间={} 设备标识={} 消息体={}",
|
||||
HandlerLogTime.now(), deviceIdentity, payload);
|
||||
return;
|
||||
}
|
||||
|
||||
String status = parseStatus(payload);
|
||||
if ("online".equals(status) || "1".equals(status)) {
|
||||
deviceStatusService.markOnline(deviceNo);
|
||||
log.info("[MQTT] 设备状态在线 时间={} 设备编号={} 消息体={}", HandlerLogTime.now(), deviceNo, payload);
|
||||
return;
|
||||
}
|
||||
if ("offline".equals(status) || "0".equals(status)) {
|
||||
if (retained) {
|
||||
log.warn("[MQTT] 忽略 retained 离线状态 时间={} 设备编号={} 消息体={}", HandlerLogTime.now(), deviceNo, payload);
|
||||
return;
|
||||
}
|
||||
deviceStatusService.markOffline(deviceNo, OFFLINE_REASON);
|
||||
log.info("[MQTT] 设备状态离线 时间={} 设备编号={} 消息体={}", HandlerLogTime.now(), deviceNo, payload);
|
||||
return;
|
||||
}
|
||||
|
||||
log.warn("[MQTT] 设备状态上报状态未知 时间={} 设备编号={} 消息体={}",
|
||||
HandlerLogTime.now(), deviceNo, payload);
|
||||
}
|
||||
|
||||
private String parseStatus(String payload) {
|
||||
if (StringUtils.isBlank(payload)) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = payload.trim();
|
||||
if (!trimmed.startsWith("{")) {
|
||||
return trimmed.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
try {
|
||||
Map<String, Object> body = objectMapper.readValue(trimmed, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
Object status = body.get("status");
|
||||
return status == null ? null : String.valueOf(status).trim().toLowerCase(Locale.ROOT);
|
||||
} catch (Exception e) {
|
||||
log.warn("[MQTT] 设备状态上报 JSON 格式错误 时间={} 消息体={}", HandlerLogTime.now(), payload, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package org.dromara.app.handler;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.app.domain.AppDevice;
|
||||
import org.dromara.app.mapper.AppDeviceMapper;
|
||||
import org.dromara.app.service.IAppWateringLogService;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.redisson.api.RLock;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MqttDeviceStatusService {
|
||||
|
||||
private static final String DEVICE_STATUS_LOCK_PREFIX = "lock:mqtt:device:status:";
|
||||
|
||||
private final AppDeviceMapper appDeviceMapper;
|
||||
private final IAppWateringLogService wateringLogService;
|
||||
|
||||
@Value("${mqtt.command-ack.device-status-cache-prefix}")
|
||||
private String deviceStatusCachePrefix;
|
||||
|
||||
@Value("${mqtt.command-ack.device-status-cache-ttl-seconds:900}")
|
||||
private long deviceStatusCacheTtlSeconds;
|
||||
|
||||
public void markOnline(String deviceNo) {
|
||||
if (StringUtils.isBlank(deviceNo)) {
|
||||
return;
|
||||
}
|
||||
withDeviceStatusLock(deviceNo, () -> {
|
||||
Map<String, Object> statusCache = new HashMap<>();
|
||||
statusCache.put("deviceNo", deviceNo);
|
||||
statusCache.put("status", "1");
|
||||
statusCache.put("lastReportTime", Instant.now().toString());
|
||||
RedisUtils.setCacheObject(
|
||||
deviceStatusCachePrefix + deviceNo,
|
||||
statusCache,
|
||||
Duration.ofSeconds(deviceStatusCacheTtlSeconds)
|
||||
);
|
||||
appDeviceMapper.update(null,
|
||||
new LambdaUpdateWrapper<AppDevice>()
|
||||
.set(AppDevice::getStatus, "1")
|
||||
.eq(AppDevice::getDeviceNo, deviceNo)
|
||||
);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public void markOffline(String deviceNo, String reason) {
|
||||
if (StringUtils.isBlank(deviceNo)) {
|
||||
return;
|
||||
}
|
||||
markOfflineWithLock(deviceNo, reason, false);
|
||||
}
|
||||
|
||||
public boolean markOfflineIfCacheMissing(String deviceNo, String reason) {
|
||||
if (StringUtils.isBlank(deviceNo)) {
|
||||
return false;
|
||||
}
|
||||
return markOfflineWithLock(deviceNo, reason, true);
|
||||
}
|
||||
|
||||
private boolean markOfflineWithLock(String deviceNo, String reason, boolean skipWhenCacheExists) {
|
||||
return withDeviceStatusLock(deviceNo, () -> {
|
||||
if (skipWhenCacheExists && RedisUtils.hasKey(deviceStatusCachePrefix + deviceNo)) {
|
||||
return false;
|
||||
}
|
||||
RedisUtils.deleteObject(deviceStatusCachePrefix + deviceNo);
|
||||
int updated = appDeviceMapper.update(null,
|
||||
new LambdaUpdateWrapper<AppDevice>()
|
||||
.set(AppDevice::getStatus, "0")
|
||||
.set(AppDevice::getWorkStatus, "0")
|
||||
.ne(AppDevice::getStatus, "0")
|
||||
.eq(AppDevice::getDeviceNo, deviceNo)
|
||||
);
|
||||
if (updated > 0) {
|
||||
int count = wateringLogService.finishRunningLogsByDevice(deviceNo, new Date(), reason);
|
||||
if (count > 0) {
|
||||
log.info("[MQTT] 已结束设备进行中的浇水记录 设备编号={} 记录数={} 原因={}", deviceNo, count, reason);
|
||||
}
|
||||
}
|
||||
return updated > 0;
|
||||
});
|
||||
}
|
||||
|
||||
private boolean withDeviceStatusLock(String deviceNo, java.util.function.BooleanSupplier action) {
|
||||
RLock lock = RedisUtils.getClient().getLock(DEVICE_STATUS_LOCK_PREFIX + deviceNo);
|
||||
boolean locked = false;
|
||||
try {
|
||||
locked = lock.tryLock(0, 10, TimeUnit.SECONDS);
|
||||
if (!locked) {
|
||||
log.debug("[MQTT] 获取设备状态锁失败,本次跳过 设备编号={}", deviceNo);
|
||||
return false;
|
||||
}
|
||||
return action.getAsBoolean();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("[MQTT] 获取设备状态锁被中断 设备编号={}", deviceNo);
|
||||
return false;
|
||||
} finally {
|
||||
if (locked && lock.isHeldByCurrentThread()) {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.dromara.app.mapper;
|
||||
|
||||
import org.dromara.app.domain.AppVersion;
|
||||
import org.dromara.app.domain.vo.AppVersionVo;
|
||||
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
|
||||
/**
|
||||
* APP版本Mapper接口
|
||||
*/
|
||||
public interface AppVersionMapper extends BaseMapperPlus<AppVersion, AppVersionVo> {
|
||||
}
|
||||
@@ -33,13 +33,17 @@ public class MqttMessageDispatcher {
|
||||
* @param payload 消息体
|
||||
*/
|
||||
public void dispatch(String topic, String payload) {
|
||||
dispatch(topic, payload, false);
|
||||
}
|
||||
|
||||
public void dispatch(String topic, String payload, boolean retained) {
|
||||
log.debug("[MQTT] 收到消息 主题={} 消息体={}", topic, payload);
|
||||
|
||||
for (MqttTopicHandler handler : handlers) {
|
||||
Matcher matcher = handler.topicPattern().matcher(topic);
|
||||
if (matcher.matches()) {
|
||||
String deviceIdentity = matcher.group(1);
|
||||
handler.handle(deviceIdentity, payload);
|
||||
handler.handle(deviceIdentity, payload, retained);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,4 +25,11 @@ public interface MqttTopicHandler {
|
||||
* @param payload 消息体(JSON)
|
||||
*/
|
||||
void handle(String deviceIdentity, String payload);
|
||||
|
||||
/**
|
||||
* 处理匹配到的消息,并携带 MQTT 消息属性。
|
||||
*/
|
||||
default void handle(String deviceIdentity, String payload, boolean retained) {
|
||||
handle(deviceIdentity, payload);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package org.dromara.app.service;
|
||||
|
||||
import org.dromara.app.domain.bo.AppVersionBo;
|
||||
import org.dromara.app.domain.vo.AppVersionVo;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* APP版本Service接口
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2026-07-01
|
||||
*/
|
||||
public interface IAppVersionService {
|
||||
|
||||
/**
|
||||
* 查询APP版本
|
||||
*
|
||||
* @param id 主键
|
||||
* @return APP版本
|
||||
*/
|
||||
AppVersionVo queryById(Long id);
|
||||
|
||||
/**
|
||||
* 分页查询APP版本列表
|
||||
*
|
||||
* @param bo 查询条件
|
||||
* @param pageQuery 分页参数
|
||||
* @return APP版本分页列表
|
||||
*/
|
||||
TableDataInfo<AppVersionVo> queryPageList(AppVersionBo bo, PageQuery pageQuery);
|
||||
|
||||
/**
|
||||
* 查询符合条件的APP版本列表
|
||||
*
|
||||
* @param bo 查询条件
|
||||
* @return APP版本列表
|
||||
*/
|
||||
List<AppVersionVo> queryList(AppVersionBo bo);
|
||||
|
||||
/**
|
||||
* 新增APP版本
|
||||
*
|
||||
* @param bo APP版本
|
||||
* @return 是否新增成功
|
||||
*/
|
||||
Boolean insertByBo(AppVersionBo bo);
|
||||
|
||||
/**
|
||||
* 修改APP版本
|
||||
*
|
||||
* @param bo APP版本
|
||||
* @return 是否修改成功
|
||||
*/
|
||||
Boolean updateByBo(AppVersionBo bo);
|
||||
|
||||
/**
|
||||
* 校验并批量删除APP版本信息
|
||||
*
|
||||
* @param ids 待删除的主键集合
|
||||
* @param isValid 是否进行有效性校验
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
|
||||
|
||||
/**
|
||||
* 查询指定平台启用中的最新版本
|
||||
*
|
||||
* @param platform 平台 android/ios
|
||||
* @return 最新版本配置,不存在返回 null
|
||||
*/
|
||||
AppVersionVo queryLatestByPlatform(String platform);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import org.dromara.app.mapper.AppWateringLogMapper;
|
||||
import org.dromara.app.service.IAppDeviceService;
|
||||
import org.dromara.app.service.IAppWateringLogService;
|
||||
import org.dromara.app.service.IDeviceCommandService;
|
||||
import org.dromara.common.core.enums.UserType;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.MapstructUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
@@ -147,8 +148,10 @@ public class AppDeviceServiceImpl implements IAppDeviceService {
|
||||
device.setPowerLevelUpdatatime(new Date());
|
||||
// applyRegisterBindToken(device, bo, exists);
|
||||
if (StringUtils.isBlank(device.getStatus())) {
|
||||
device.setStatus("1"); // 注册默认在线
|
||||
device.setWorkStatus("2");
|
||||
device.setStatus(exists == null || StringUtils.isBlank(exists.getStatus()) ? "0" : exists.getStatus());
|
||||
}
|
||||
if (StringUtils.isBlank(device.getWorkStatus())) {
|
||||
device.setWorkStatus(exists == null || StringUtils.isBlank(exists.getWorkStatus()) ? "2" : exists.getWorkStatus());
|
||||
}
|
||||
|
||||
if (exists == null) {
|
||||
@@ -282,6 +285,7 @@ public class AppDeviceServiceImpl implements IAppDeviceService {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("bindDeviceStatus", 200);
|
||||
params.put("bindDeviceStatusName", "");
|
||||
|
||||
if (bo == null) {
|
||||
params.put("bindDeviceStatus", 300);
|
||||
params.put("bindDeviceStatusName", "设备信息不能为空");
|
||||
@@ -296,12 +300,18 @@ public class AppDeviceServiceImpl implements IAppDeviceService {
|
||||
params.put("bindDevice", null);
|
||||
Long userId = LoginHelper.getUserId();
|
||||
AppDevice exists = findDeviceForBindStatus(bo);
|
||||
|
||||
if (exists == null) {
|
||||
params.put("bindDeviceStatus", 302);
|
||||
params.put("bindDeviceStatusName", "设备未入库注册,请先进行入库");
|
||||
return params;
|
||||
}
|
||||
params.put("bindDevice", exists);
|
||||
if (exists.getUserId() == null && exists.getWorkStatus().equals("2") && exists.getStatus().equals("0") ) {
|
||||
params.put("bindDeviceStatus", 305);
|
||||
params.put("bindDeviceStatusName", "设备未配网,请先去配置网络");
|
||||
return params;
|
||||
}
|
||||
if (exists.getUserId() != null && !exists.getUserId().equals(userId)) {
|
||||
params.put("bindDeviceStatus", 303);
|
||||
params.put("bindDeviceStatusName", "设备已被其他用户绑定");
|
||||
@@ -312,11 +322,7 @@ public class AppDeviceServiceImpl implements IAppDeviceService {
|
||||
params.put("bindDeviceStatusName", "设备未绑定,请先绑定用户");
|
||||
return params;
|
||||
}
|
||||
if (exists.getUserId() == null && exists.getWorkStatus().equals("2") && exists.getStatus().equals("0") ) {
|
||||
params.put("bindDeviceStatus", 305);
|
||||
params.put("bindDeviceStatusName", "设备未配网,请先去配置网络");
|
||||
return params;
|
||||
}
|
||||
|
||||
|
||||
return params;
|
||||
}
|
||||
@@ -421,7 +427,7 @@ public class AppDeviceServiceImpl implements IAppDeviceService {
|
||||
throw new ServiceException("设备编号不能为空");
|
||||
}
|
||||
|
||||
boolean platformAdmin = LoginHelper.isSuperAdmin() || LoginHelper.isTenantAdmin();
|
||||
boolean platformAdmin = isPlatformAdmin();
|
||||
Long userId = platformAdmin ? null : LoginHelper.getUserId();
|
||||
if (!platformAdmin) {
|
||||
if (userId == null) {
|
||||
@@ -452,6 +458,17 @@ public class AppDeviceServiceImpl implements IAppDeviceService {
|
||||
return flag;
|
||||
}
|
||||
|
||||
private boolean isPlatformAdmin() {
|
||||
if (LoginHelper.isSuperAdmin() || LoginHelper.isTenantAdmin()) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
return UserType.SYS_USER == LoginHelper.getUserType();
|
||||
} catch (RuntimeException ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Boolean unbindDevices(Collection<String> deviceNos, Long userId) {
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package org.dromara.app.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.app.domain.AppVersion;
|
||||
import org.dromara.app.domain.bo.AppVersionBo;
|
||||
import org.dromara.app.domain.vo.AppVersionVo;
|
||||
import org.dromara.app.mapper.AppVersionMapper;
|
||||
import org.dromara.app.service.IAppVersionService;
|
||||
import org.dromara.common.core.utils.MapstructUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* APP版本Service业务层处理
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2026-07-01
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class AppVersionServiceImpl implements IAppVersionService {
|
||||
|
||||
private static final String STATUS_ENABLED = "1";
|
||||
|
||||
private final AppVersionMapper baseMapper;
|
||||
|
||||
/**
|
||||
* 查询APP版本
|
||||
*
|
||||
* @param id 主键
|
||||
* @return APP版本
|
||||
*/
|
||||
@Override
|
||||
public AppVersionVo queryById(Long id){
|
||||
return baseMapper.selectVoById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询APP版本列表
|
||||
*
|
||||
* @param bo 查询条件
|
||||
* @param pageQuery 分页参数
|
||||
* @return APP版本分页列表
|
||||
*/
|
||||
@Override
|
||||
public TableDataInfo<AppVersionVo> queryPageList(AppVersionBo bo, PageQuery pageQuery) {
|
||||
LambdaQueryWrapper<AppVersion> lqw = buildQueryWrapper(bo);
|
||||
Page<AppVersionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
|
||||
return TableDataInfo.build(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询符合条件的APP版本列表
|
||||
*
|
||||
* @param bo 查询条件
|
||||
* @return APP版本列表
|
||||
*/
|
||||
@Override
|
||||
public List<AppVersionVo> queryList(AppVersionBo bo) {
|
||||
LambdaQueryWrapper<AppVersion> lqw = buildQueryWrapper(bo);
|
||||
return baseMapper.selectVoList(lqw);
|
||||
}
|
||||
|
||||
private LambdaQueryWrapper<AppVersion> buildQueryWrapper(AppVersionBo bo) {
|
||||
Map<String, Object> params = bo.getParams();
|
||||
LambdaQueryWrapper<AppVersion> lqw = Wrappers.lambdaQuery();
|
||||
lqw.orderByAsc(AppVersion::getId);
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getPlatform()), AppVersion::getPlatform, bo.getPlatform());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getLatestVersion()), AppVersion::getLatestVersion, bo.getLatestVersion());
|
||||
lqw.eq(bo.getVersionCode() != null, AppVersion::getVersionCode, bo.getVersionCode());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getForceUpdate()), AppVersion::getForceUpdate, bo.getForceUpdate());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getDownloadUrl()), AppVersion::getDownloadUrl, bo.getDownloadUrl());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getReleaseNotes()), AppVersion::getReleaseNotes, bo.getReleaseNotes());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppVersion::getStatus, bo.getStatus());
|
||||
return lqw;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增APP版本
|
||||
*
|
||||
* @param bo APP版本
|
||||
* @return 是否新增成功
|
||||
*/
|
||||
@Override
|
||||
public Boolean insertByBo(AppVersionBo bo) {
|
||||
AppVersion add = MapstructUtils.convert(bo, AppVersion.class);
|
||||
validEntityBeforeSave(add);
|
||||
boolean flag = baseMapper.insert(add) > 0;
|
||||
if (flag) {
|
||||
bo.setId(add.getId());
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改APP版本
|
||||
*
|
||||
* @param bo APP版本
|
||||
* @return 是否修改成功
|
||||
*/
|
||||
@Override
|
||||
public Boolean updateByBo(AppVersionBo bo) {
|
||||
AppVersion update = MapstructUtils.convert(bo, AppVersion.class);
|
||||
validEntityBeforeSave(update);
|
||||
return baseMapper.updateById(update) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存前的数据校验
|
||||
*/
|
||||
private void validEntityBeforeSave(AppVersion entity){
|
||||
//TODO 做一些数据校验,如唯一约束
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并批量删除APP版本信息
|
||||
*
|
||||
* @param ids 待删除的主键集合
|
||||
* @param isValid 是否进行有效性校验
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@Override
|
||||
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
|
||||
if(isValid){
|
||||
//TODO 做一些业务上的校验,判断是否需要校验
|
||||
}
|
||||
return baseMapper.deleteByIds(ids) > 0;
|
||||
}
|
||||
@Override
|
||||
public AppVersionVo queryLatestByPlatform(String platform) {
|
||||
if (StringUtils.isBlank(platform)) {
|
||||
return null;
|
||||
}
|
||||
AppVersion version = baseMapper.selectOne(
|
||||
Wrappers.<AppVersion>lambdaQuery()
|
||||
.eq(AppVersion::getPlatform, platform)
|
||||
.eq(AppVersion::getStatus, STATUS_ENABLED)
|
||||
.orderByDesc(AppVersion::getVersionCode)
|
||||
.orderByDesc(AppVersion::getId)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (version == null) {
|
||||
return null;
|
||||
}
|
||||
return MapstructUtils.convert(version, AppVersionVo.class);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,25 @@
|
||||
package org.dromara.app.task;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.app.domain.AppDevice;
|
||||
import org.dromara.app.handler.MqttDeviceStatusService;
|
||||
import org.dromara.app.mapper.AppDeviceMapper;
|
||||
import org.dromara.app.service.IAppWateringLogService;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.redisson.api.RLock;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 设备离线检测定时任务
|
||||
* <p>
|
||||
* 逻辑:Redis 中 mqtt:device:status:{deviceNo} Key 的 TTL 由 device-status-cache-ttl-seconds 控制。
|
||||
* 设备断电/断网后不再上报数据,TTL 到期 Key 自动消失。
|
||||
* 逻辑:默认通过设备 LWT 离线消息更新状态。
|
||||
* 兼容旧设备时,可打开 ttl-compat-enabled,继续使用 Redis 在线 Key 过期兜底离线。
|
||||
* 本任务定期扫描数据库中非离线状态的设备,如果对应 Redis Key 已不存在,
|
||||
* 则将数据库 status 更新为 0(离线)。
|
||||
* </p>
|
||||
@@ -36,22 +32,26 @@ import java.util.stream.Collectors;
|
||||
public class DeviceOfflineCheckTask {
|
||||
|
||||
private final AppDeviceMapper appDeviceMapper;
|
||||
private static final String DEVICE_STATUS_LOCK_PREFIX = "lock:mqtt:device:status:";
|
||||
private final MqttDeviceStatusService deviceStatusService;
|
||||
|
||||
@Value("${mqtt.command-ack.device-status-cache-prefix}")
|
||||
private String deviceStatusCachePrefix;
|
||||
|
||||
@Value("${mqtt.command-ack.device-status-cache-ttl-seconds:900}")
|
||||
private long deviceStatusCacheTtlSeconds;
|
||||
|
||||
@Value("${mqtt.offline-check.enabled:true}")
|
||||
private boolean enabled;
|
||||
private final IAppWateringLogService wateringLogService;
|
||||
@Value("${mqtt.offline-check.ttl-compat-enabled:false}")
|
||||
private boolean ttlCompatEnabled;
|
||||
|
||||
/**
|
||||
* 每 90 秒检查一次(Redis TTL 默认 300s,90s 间隔确保 1.5 个周期内同步)
|
||||
* 每 90 秒检查一次。默认不开启 TTL 兼容离线检测,避免低功耗长连接设备被误判离线。
|
||||
* 可通过 mqtt.offline-check.interval-ms 覆盖(单位 ms)
|
||||
*/
|
||||
@Scheduled(fixedDelayString = "${mqtt.offline-check.interval-ms:90000}")
|
||||
public void checkOfflineDevices() {
|
||||
if (!enabled) {
|
||||
if (!enabled || !ttlCompatEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -66,11 +66,28 @@ public class DeviceOfflineCheckTask {
|
||||
return;
|
||||
}
|
||||
|
||||
// 过滤出 Redis Key 已过期(不存在)的设备
|
||||
List<String> offlineDeviceNos = onlineDevices.stream()
|
||||
.map(AppDevice::getDeviceNo)
|
||||
.filter(deviceNo -> !RedisUtils.hasKey(deviceStatusCachePrefix + deviceNo))
|
||||
.collect(Collectors.toList());
|
||||
List<String> offlineDeviceNos = new ArrayList<>();
|
||||
int migratedPermanentKeys = 0;
|
||||
for (AppDevice device : onlineDevices) {
|
||||
String deviceNo = device.getDeviceNo();
|
||||
String statusKey = deviceStatusCachePrefix + deviceNo;
|
||||
if (!RedisUtils.hasKey(statusKey)) {
|
||||
offlineDeviceNos.add(deviceNo);
|
||||
continue;
|
||||
}
|
||||
|
||||
long ttl = RedisUtils.getTimeToLive(statusKey);
|
||||
if (ttl == -1L) {
|
||||
RedisUtils.expire(statusKey, Duration.ofSeconds(deviceStatusCacheTtlSeconds));
|
||||
migratedPermanentKeys++;
|
||||
} else if (ttl == -2L) {
|
||||
offlineDeviceNos.add(deviceNo);
|
||||
}
|
||||
}
|
||||
|
||||
if (migratedPermanentKeys > 0) {
|
||||
log.info("[设备离线] 已为旧版永久在线缓存补充 TTL,设备数:{}", migratedPermanentKeys);
|
||||
}
|
||||
|
||||
if (offlineDeviceNos.isEmpty()) {
|
||||
log.debug("[设备离线] 本次检测未发现离线设备,扫描设备数:{}", onlineDevices.size());
|
||||
@@ -79,7 +96,7 @@ public class DeviceOfflineCheckTask {
|
||||
|
||||
List<String> updatedDeviceNos = new ArrayList<>();
|
||||
for (String deviceNo : offlineDeviceNos) {
|
||||
if (markOfflineIfStillExpired(deviceNo)) {
|
||||
if (deviceStatusService.markOfflineIfCacheMissing(deviceNo, "设备掉线")) {
|
||||
updatedDeviceNos.add(deviceNo);
|
||||
}
|
||||
}
|
||||
@@ -89,43 +106,4 @@ public class DeviceOfflineCheckTask {
|
||||
updatedDeviceNos.size(), updatedDeviceNos);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean markOfflineIfStillExpired(String deviceNo) {
|
||||
RLock lock = RedisUtils.getClient().getLock(DEVICE_STATUS_LOCK_PREFIX + deviceNo);
|
||||
boolean locked = false;
|
||||
try {
|
||||
locked = lock.tryLock(100, 10000, TimeUnit.MILLISECONDS);
|
||||
if (!locked) {
|
||||
log.debug("[设备离线] 获取设备状态锁失败,本轮跳过 设备编号={}", deviceNo);
|
||||
return false;
|
||||
}
|
||||
// 获取锁后再次确认 Redis 在线 Key 仍不存在,避免设备刚注册上线时被旧扫描结果覆盖为离线
|
||||
if (RedisUtils.hasKey(deviceStatusCachePrefix + deviceNo)) {
|
||||
return false;
|
||||
}
|
||||
return appDeviceMapper.update(null,
|
||||
new LambdaUpdateWrapper<AppDevice>()
|
||||
.set(AppDevice::getStatus, "0")
|
||||
.set(AppDevice::getWorkStatus, "0")
|
||||
.ne(AppDevice::getStatus, "0")
|
||||
.eq(AppDevice::getDeviceNo, deviceNo)
|
||||
) > 0 && finishOfflineWateringLogs(deviceNo);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("[设备离线] 获取设备状态锁被中断 设备编号={}", deviceNo);
|
||||
return false;
|
||||
} finally {
|
||||
if (locked && lock.isHeldByCurrentThread()) {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean finishOfflineWateringLogs(String deviceNo) {
|
||||
int count = wateringLogService.finishRunningLogsByDevice(deviceNo, new Date(), "设备掉线");
|
||||
if (count > 0) {
|
||||
log.info("[设备离线] 已结束设备进行中的浇水记录 设备编号={} 记录数={}", deviceNo, count);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user