浇水bug修改

This commit is contained in:
yuhaiming
2026-07-13 14:22:11 +08:00
parent 1e1f1042fe
commit 86e511f418
50 changed files with 4976 additions and 280 deletions

View File

@@ -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));
}
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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();
}
}
}
}

View File

@@ -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();
}
}
}
}

View File

@@ -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;
}
}
}

View File

@@ -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();
}
}
}
}

View File

@@ -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> {
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}

View File

@@ -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) {

View File

@@ -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);
}
}

View File

@@ -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 默认 300s90s 间隔确保 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;
}
}

View File

@@ -0,0 +1,434 @@
package org.dromara.app.controller;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dromara.app.domain.bo.AppScheduleBo;
import org.dromara.app.domain.bo.AppSchedulingDeviceBo;
import org.dromara.app.domain.bo.AppWateringLogBo;
import org.dromara.app.domain.vo.*;
import org.dromara.app.service.*;
import org.dromara.common.core.domain.R;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.vo.SysOssUploadVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.dromara.system.service.ISysUserService;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.mock.web.MockMultipartFile;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
public class AppControllerTest {
@Mock private IAppDeviceService appDeviceService;
@Mock private IAppScheduleService appScheduleService;
@Mock private IAppScheduleDetailService appScheduleDetailService;
@Mock private org.dromara.app.service.impl.AppScheduleServiceImpl appScheduleServiceimpl;
@Mock private IAppSchedulingDeviceService appSchedulingDeviceService;
@Mock private ISysUserService userService;
@Mock private IAppWateringLogService appWateringLogService;
@Mock private IDeviceCommandService deviceCommandService;
@Mock private ISysOssService ossService;
@Mock private IAppVersionService appVersionService;
@Test
public void checkVersion_returnsUpdateAvailableWhenConfiguredVersionDiffers() {
AppController controller = newController();
AppVersionVo latestVersion = new AppVersionVo();
latestVersion.setPlatform("android");
latestVersion.setLatestVersion("1.0.1");
latestVersion.setVersionCode(2);
latestVersion.setForceUpdate("1");
latestVersion.setDownloadUrl("https://example.com/app.apk");
latestVersion.setReleaseNotes("修复已知问题");
when(appVersionService.queryLatestByPlatform("android")).thenReturn(latestVersion);
R<AppVersionCheckVo> result = callWithLogin(1L, () -> controller.checkVersion("android", "1.0.0"));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
assertThat(result.getData().getPlatform()).isEqualTo("android");
assertThat(result.getData().getCurrentVersion()).isEqualTo("1.0.0");
assertThat(result.getData().getLatestVersion()).isEqualTo("1.0.1");
assertThat(result.getData().getUpdateAvailable()).isTrue();
assertThat(result.getData().getForceUpdate()).isTrue();
assertThat(result.getData().getDownloadUrl()).isEqualTo("https://example.com/app.apk");
assertThat(result.getData().getReleaseNotes()).isEqualTo("修复已知问题");
}
@Test
public void checkVersion_returnsNoUpdateWhenConfiguredVersionMatches() {
AppController controller = newController();
AppVersionVo latestVersion = new AppVersionVo();
latestVersion.setPlatform("ios");
latestVersion.setLatestVersion("2.0.0");
latestVersion.setVersionCode(3);
latestVersion.setForceUpdate("0");
latestVersion.setDownloadUrl("https://example.com/app");
latestVersion.setReleaseNotes("最新版本");
when(appVersionService.queryLatestByPlatform("ios")).thenReturn(latestVersion);
R<AppVersionCheckVo> result = callWithLogin(1L, () -> controller.checkVersion("ios", "2.0.0"));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
assertThat(result.getData().getPlatform()).isEqualTo("ios");
assertThat(result.getData().getCurrentVersion()).isEqualTo("2.0.0");
assertThat(result.getData().getLatestVersion()).isEqualTo("2.0.0");
assertThat(result.getData().getUpdateAvailable()).isFalse();
assertThat(result.getData().getForceUpdate()).isFalse();
}
@Test
public void checkVersion_rejectsMissingCurrentVersion() {
AppController controller = newController();
R<AppVersionCheckVo> result = callWithLogin(1L, () -> controller.checkVersion("android", " "));
assertThat(result.getCode()).isEqualTo(500);
assertThat(result.getMsg()).isEqualTo("当前版本不能为空");
verify(appVersionService, never()).queryLatestByPlatform(any());
}
@Test
public void checkVersion_rejectsUnsupportedPlatform() {
AppController controller = newController();
R<AppVersionCheckVo> result = callWithLogin(1L, () -> controller.checkVersion("harmony", "1.0.0"));
assertThat(result.getCode()).isEqualTo(500);
assertThat(result.getMsg()).isEqualTo("平台类型仅支持 android 或 ios");
verify(appVersionService, never()).queryLatestByPlatform(any());
}
@Test
public void checkVersion_rejectsMissingVersionConfig() {
AppController controller = newController();
when(appVersionService.queryLatestByPlatform("android")).thenReturn(null);
R<AppVersionCheckVo> result = callWithLogin(1L, () -> controller.checkVersion("android", "1.0.0"));
assertThat(result.getCode()).isEqualTo(500);
assertThat(result.getMsg()).isEqualTo("版本配置不存在");
}
@Test
public void uploadImage_uploadsToOssAndReturnsBackendVisibleInfo() {
AppController controller = newController();
MockMultipartFile file = new MockMultipartFile(
"file",
"plant.png",
"image/png",
new byte[]{1, 2, 3}
);
SysOssVo oss = new SysOssVo();
oss.setOssId(123L);
oss.setOriginalName("plant.png");
oss.setUrl("https://bucket.oss-cn-hangzhou.aliyuncs.com/plant.png");
when(ossService.upload(file)).thenReturn(oss);
R<SysOssUploadVo> result = callWithLogin(1L, () -> controller.uploadImage(file));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
assertThat(result.getData().getOssId()).isEqualTo("123");
assertThat(result.getData().getFileName()).isEqualTo("plant.png");
assertThat(result.getData().getUrl()).isEqualTo("https://bucket.oss-cn-hangzhou.aliyuncs.com/plant.png");
verify(ossService).upload(file);
}
@Test
public void uploadImage_rejectsNonImageFile() {
AppController controller = newController();
MockMultipartFile file = new MockMultipartFile(
"file",
"readme.txt",
"text/plain",
new byte[]{1, 2, 3}
);
R<SysOssUploadVo> result = callWithLogin(1L, () -> controller.uploadImage(file));
assertThat(result.getCode()).isEqualTo(500);
assertThat(result.getMsg()).isEqualTo("只能上传图片文件");
verify(ossService, never()).upload(any(org.springframework.web.multipart.MultipartFile.class));
}
@Test
public void switchDevice_usesCurrentTimeWithSecondsAsStartTime() throws Exception {
AppController controller = newController();
when(appDeviceService.switchDevice(eq("D01"), eq("1"), any(), eq(10))).thenReturn(true);
waitUntilCurrentSecondIsSafelyNonZero();
R<Void> result = callWithLogin(99L,
() -> controller.switchDevice("{\"deviceNo\":\"D01\",\"workStatus\":\"1\",\"durationMin\":\"10\"}"));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
ArgumentCaptor<String> startTimeCaptor = ArgumentCaptor.forClass(String.class);
verify(appDeviceService).switchDevice(eq("D01"), eq("1"), startTimeCaptor.capture(), eq(10));
assertThat(startTimeCaptor.getValue()).matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
assertThat(startTimeCaptor.getValue()).doesNotEndWith(":00");
}
@Test
public void addScheduleDevice_dispatchesSchedulePayloadAfterBinding() {
AppController controller = newController();
Long userId = 99L;
AppScheduleVo schedule = new AppScheduleVo();
schedule.setId(10L);
schedule.setUserId(userId);
schedule.setName("Morning");
schedule.setStatus("1");
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo("D01");
device.setUserId(userId);
AppScheduleDetailVo detail = new AppScheduleDetailVo();
detail.setId(101L);
detail.setWeekday(1);
detail.setTimeData("[{\"startTime\":\"08:00\",\"durationMin\":15}]");
detail.setTriggerType("0");
detail.setStatus("1");
when(appScheduleService.queryById(10L)).thenReturn(schedule);
when(appDeviceService.queryById("D01")).thenReturn(device);
lenient().when(appScheduleDetailService.queryByScheduleIdByStatus(10L)).thenReturn(List.of(detail));
when(appSchedulingDeviceService.insertByBo(any(AppSchedulingDeviceBo.class))).thenReturn(true);
R<Void> result = callWithLogin(userId,
() -> controller.addScheduleDevice("{\"scheduleId\":10,\"deviceNos\":[\"D01\"]}"));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
ArgumentCaptor<Map<String, Object>> payloadCaptor = ArgumentCaptor.forClass(Map.class);
verify(deviceCommandService).sendScheduleBindCommand(eq("D01"), payloadCaptor.capture());
Map<String, Object> payload = payloadCaptor.getValue();
assertThat(payload.get("deviceNo")).isEqualTo("D01");
assertThat(payload).containsKey("details").doesNotContainKeys("cmd", "schedule");
List<Map<String, Object>> details = (List<Map<String, Object>>) payload.get("details");
assertThat(details).hasSize(1);
Map<String, Object> detailPayload = details.get(0);
assertThat(detailPayload)
.containsEntry("weekday", 1)
.containsEntry("triggerType", "0")
.containsEntry("status", "1")
.doesNotContainKey("id")
.doesNotContainKey("zones");
List<Object> timeData = (List<Object>) detailPayload.get("timeData");
assertThat(timeData).hasSize(1);
JSONObject timeSlot = (JSONObject) timeData.get(0);
assertThat(timeSlot.getStr("startTime")).isEqualTo("08:00");
assertThat(timeSlot.getInt("durationMin")).isEqualTo(15);
}
@Test
public void addScheduleDevice_doesNotDispatchWhenBindingAlreadyExists() {
AppController controller = newController();
Long userId = 99L;
AppScheduleVo schedule = ownedSchedule(10L, userId);
AppDeviceVo device = ownedDevice("D01", userId);
AppSchedulingDeviceVo existingBinding = new AppSchedulingDeviceVo();
when(appScheduleService.queryById(10L)).thenReturn(schedule);
when(appDeviceService.queryById("D01")).thenReturn(device);
when(appSchedulingDeviceService.queryByScheduleIdAndDeviceNo(10L, "D01")).thenReturn(existingBinding);
R<Void> result = callWithLogin(userId,
() -> controller.addScheduleDevice("{\"scheduleId\":10,\"deviceNos\":[\"D01\"]}"));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
verify(appSchedulingDeviceService, never()).insertByBo(any(AppSchedulingDeviceBo.class));
verify(deviceCommandService, never()).sendScheduleBindCommand(eq("D01"), any());
}
@Test
public void removeSchedule_dispatchesUnbindOnlyAfterDeleteSucceeds() {
AppController controller = newController();
Long userId = 99L;
AppScheduleVo schedule = ownedSchedule(10L, userId);
AppSchedulingDeviceVo binding = new AppSchedulingDeviceVo();
binding.setDeviceNo("D01");
when(appScheduleService.queryById(10L)).thenReturn(schedule);
when(appSchedulingDeviceService.queryList(any(AppSchedulingDeviceBo.class))).thenReturn(List.of(binding));
when(appScheduleService.deleteWithValidByIds(List.of(10L), true)).thenReturn(true);
R<Void> result = callWithLogin(userId, () -> controller.removeSchedule(new Long[]{10L}));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
var ordered = inOrder(appScheduleService, deviceCommandService);
ordered.verify(appScheduleService).deleteWithValidByIds(List.of(10L), true);
ordered.verify(deviceCommandService).sendScheduleUnbindCommand("D01", 10L);
}
@Test
public void removeSchedule_doesNotDispatchUnbindWhenDeleteFails() {
AppController controller = newController();
Long userId = 99L;
AppScheduleVo schedule = ownedSchedule(10L, userId);
AppSchedulingDeviceVo binding = new AppSchedulingDeviceVo();
binding.setDeviceNo("D01");
when(appScheduleService.queryById(10L)).thenReturn(schedule);
when(appSchedulingDeviceService.queryList(any(AppSchedulingDeviceBo.class))).thenReturn(List.of(binding));
when(appScheduleService.deleteWithValidByIds(List.of(10L), true)).thenReturn(false);
R<Void> result = callWithLogin(userId, () -> controller.removeSchedule(new Long[]{10L}));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(500);
verify(deviceCommandService, never()).sendScheduleUnbindCommand("D01", 10L);
}
@Test
public void editScheduleStatus_dispatchesCanceledCommandWhenScheduleClosed() {
AppController controller = newController();
Long userId = 99L;
AppScheduleVo schedule = ownedSchedule(10L, userId);
AppSchedulingDeviceVo binding = new AppSchedulingDeviceVo();
binding.setDeviceNo("D01");
AppScheduleBo bo = new AppScheduleBo();
bo.setId(10L);
bo.setStatus("0");
when(appScheduleService.queryById(10L)).thenReturn(schedule);
when(appScheduleService.updateStatusByBo(bo)).thenReturn(true);
when(appSchedulingDeviceService.queryList(any(AppSchedulingDeviceBo.class))).thenReturn(List.of(binding));
R<Void> result = callWithLogin(userId, () -> controller.editScheduleStatus(bo));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
verify(deviceCommandService).sendScheduleCanceledCommand("D01", 10L);
verify(deviceCommandService, never()).sendScheduleBindCommand(eq("D01"), any());
}
@Test
public void editScheduleStatus_dispatchesSchedulePayloadWhenScheduleOpened() {
AppController controller = newController();
Long userId = 99L;
AppScheduleVo schedule = ownedSchedule(10L, userId);
AppSchedulingDeviceVo binding = new AppSchedulingDeviceVo();
binding.setDeviceNo("D01");
AppScheduleDetailVo detail = new AppScheduleDetailVo();
detail.setWeekday(1);
detail.setTimeData("[{\"startTime\":\"08:00\",\"durationMin\":15}]");
detail.setTriggerType("0");
detail.setStatus("1");
AppScheduleBo bo = new AppScheduleBo();
bo.setId(10L);
bo.setStatus("1");
when(appScheduleService.queryById(10L)).thenReturn(schedule);
when(appScheduleService.updateStatusByBo(bo)).thenReturn(true);
when(appSchedulingDeviceService.queryList(any(AppSchedulingDeviceBo.class))).thenReturn(List.of(binding));
when(appScheduleDetailService.queryByScheduleIdByStatus(10L)).thenReturn(List.of(detail));
R<Void> result = callWithLogin(userId, () -> controller.editScheduleStatus(bo));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
verify(deviceCommandService).sendScheduleBindCommand(eq("D01"), any());
verify(deviceCommandService, never()).sendScheduleCanceledCommand("D01", 10L);
}
@Test
public void latestWaterLog_returnsLatestRunningLogById() throws Exception {
AppController controller = newController();
Long userId = 99L;
AppDeviceVo device = ownedDevice("D01", userId);
AppWateringLogVo laterStartTime = new AppWateringLogVo();
laterStartTime.setId(1L);
laterStartTime.setDeviceNo("D01");
laterStartTime.setStatus("1");
laterStartTime.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2026-07-06 16:39:00"));
laterStartTime.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2026-07-06 16:49:00"));
AppWateringLogVo latest = new AppWateringLogVo();
latest.setId(2L);
latest.setDeviceNo("D01");
latest.setStatus("1");
latest.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2026-07-06 08:30:00"));
latest.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2026-07-06 08:40:00"));
when(appDeviceService.queryById("D01")).thenReturn(device);
when(appWateringLogService.queryList(any(AppWateringLogBo.class))).thenReturn(List.of(laterStartTime, latest));
R<Map<String, Object>> result = callWithLogin(userId, () -> controller.latestWaterLog("D01"));
assertThat(result.getCode()).as(result.getMsg()).isEqualTo(200);
assertThat(result.getData())
.containsEntry("startTime", "2026-07-06 08:30:00")
.containsEntry("endTime", "2026-07-06 08:40:00");
ArgumentCaptor<AppWateringLogBo> captor = ArgumentCaptor.forClass(AppWateringLogBo.class);
verify(appWateringLogService).queryList(captor.capture());
assertThat(captor.getValue().getUserId()).isEqualTo(userId);
assertThat(captor.getValue().getDeviceNo()).isEqualTo("D01");
assertThat(captor.getValue().getStatus()).isEqualTo("1");
}
private AppController newController() {
return new AppController(
appDeviceService,
appScheduleService,
appScheduleDetailService,
appScheduleServiceimpl,
appSchedulingDeviceService,
userService,
appWateringLogService,
deviceCommandService,
ossService,
appVersionService
);
}
private <T> R<T> callWithLogin(Long userId, Supplier<R<T>> action) {
try (GenericApplicationContext applicationContext = new GenericApplicationContext();
MockedStatic<LoginHelper> loginHelper = mockStatic(LoginHelper.class)) {
applicationContext.registerBean(ObjectMapper.class, (Supplier<ObjectMapper>) ObjectMapper::new);
applicationContext.refresh();
new SpringUtil().setApplicationContext(applicationContext);
loginHelper.when(LoginHelper::getUserId).thenReturn(userId);
return action.get();
}
}
private AppScheduleVo ownedSchedule(Long scheduleId, Long userId) {
AppScheduleVo schedule = new AppScheduleVo();
schedule.setId(scheduleId);
schedule.setUserId(userId);
return schedule;
}
private AppDeviceVo ownedDevice(String deviceNo, Long userId) {
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo(deviceNo);
device.setUserId(userId);
return device;
}
private void waitUntilCurrentSecondIsSafelyNonZero() throws InterruptedException {
while (true) {
int second = Calendar.getInstance().get(Calendar.SECOND);
if (second > 1 && second < 59) {
return;
}
Thread.sleep(50);
}
}
}

View File

@@ -0,0 +1,79 @@
package org.dromara.app.handler;
import org.dromara.app.domain.AppDevice;
import org.dromara.app.domain.bo.AppDeviceBo;
import org.dromara.app.domain.mqtt.DeviceCommand;
import org.dromara.app.mapper.AppDeviceMapper;
import org.dromara.app.service.IAppDeviceService;
import org.dromara.app.service.IDeviceCommandPublisher;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.ObjectProvider;
import java.lang.reflect.Method;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class DeviceRegisterHandlerTest {
@Mock private IAppDeviceService appDeviceService;
@Mock private AppDeviceMapper appDeviceMapper;
@Mock private ObjectProvider<IDeviceCommandPublisher> commandPublisherProvider;
@Mock private IDeviceCommandPublisher commandPublisher;
@Mock private DeviceIdentityResolver deviceIdentityResolver;
@Test
void firstRegistrationReplyStillUsesMacTopic() throws Exception {
DeviceRegisterHandler handler = new DeviceRegisterHandler(
appDeviceService,
appDeviceMapper,
commandPublisherProvider,
deviceIdentityResolver
);
when(commandPublisherProvider.getIfAvailable()).thenReturn(commandPublisher);
when(commandPublisher.send(any(DeviceCommand.class))).thenReturn("cmd-1");
Method method = DeviceRegisterHandler.class.getDeclaredMethod(
"sendDeviceNoToDevice", String.class, String.class
);
method.setAccessible(true);
method.invoke(handler, "D01", "AA:BB:CC");
ArgumentCaptor<DeviceCommand> captor = ArgumentCaptor.forClass(DeviceCommand.class);
verify(commandPublisher).send(captor.capture());
assertThat(captor.getValue().getTopic()).isEqualTo("/aa:bb:cc/subscriber/cmd");
assertThat(captor.getValue().getCommandType()).isEqualTo("registerDeviceNo");
assertThat(captor.getValue().getDeviceNo()).isEqualTo("D01");
}
@Test
void handleKeepsExistingMacWhenTopicUsesDeviceNoAndPayloadOmitsMac() {
DeviceRegisterHandler handler = new DeviceRegisterHandler(
appDeviceService,
appDeviceMapper,
commandPublisherProvider,
deviceIdentityResolver
);
AppDevice existing = new AppDevice();
existing.setDeviceNo("2075423638947475457");
existing.setMacAddress("aa:bb:cc");
when(deviceIdentityResolver.resolve("2075423638947475457")).thenReturn(existing);
when(commandPublisherProvider.getIfAvailable()).thenReturn(null);
handler.handle("2075423638947475457", "{}");
org.mockito.ArgumentCaptor<AppDeviceBo> captor = org.mockito.ArgumentCaptor.forClass(AppDeviceBo.class);
verify(appDeviceService).registerByMqtt(captor.capture());
assertThat(captor.getValue().getDeviceNo()).isEqualTo("2075423638947475457");
assertThat(captor.getValue().getMacAddress()).isEqualTo("aa:bb:cc");
}
}

View File

@@ -0,0 +1,104 @@
package org.dromara.app.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dromara.app.domain.AppDevice;
import org.dromara.app.mapper.AppDeviceMapper;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class DeviceStatusHandlerTest {
@Mock
private DeviceIdentityResolver deviceIdentityResolver;
@Mock
private MqttDeviceStatusService deviceStatusService;
@Mock
private AppDeviceMapper appDeviceMapper;
@Test
void topicPatternMatchesDeviceStatusTopic() {
DeviceStatusHandler handler = newHandler();
assertThat(handler.topicPattern().matcher("/D01/publish/status").matches()).isTrue();
assertThat(handler.topicPattern().matcher("/D01/publish/power").matches()).isFalse();
}
@Test
void handleMarksDeviceOnlineFromPlainPayload() {
DeviceStatusHandler handler = newHandler();
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
handler.handle("D01", "online");
verify(deviceStatusService).markOnline("D01");
verify(deviceStatusService, never()).markOffline(anyString(), anyString());
}
@Test
void handleMarksDeviceOfflineFromJsonPayload() {
DeviceStatusHandler handler = newHandler();
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
handler.handle("D01", "{\"status\":\"offline\"}");
verify(deviceStatusService).markOffline("D01", "设备 MQTT 状态离线");
verify(deviceStatusService, never()).markOnline(anyString());
}
@Test
void handleResolvesLastWillTopicMacToDeviceNo() {
String macAddress = "DC:DA:0C:FA:29:5E";
AppDevice device = new AppDevice();
device.setDeviceNo("D01");
when(appDeviceMapper.selectById(macAddress)).thenReturn(null);
when(appDeviceMapper.selectByMac("dc:da:0c:fa:29:5e")).thenReturn(device);
DeviceIdentityResolver resolver = new DeviceIdentityResolver(appDeviceMapper);
DeviceStatusHandler handler = new DeviceStatusHandler(resolver, deviceStatusService, new ObjectMapper());
handler.handle(macAddress, "{\"status\":\"offline\"}", false);
verify(appDeviceMapper).selectByMac("dc:da:0c:fa:29:5e");
verify(deviceStatusService).markOffline("D01", "设备 MQTT 状态离线");
verify(deviceStatusService, never()).markOffline(macAddress, "设备 MQTT 状态离线");
}
@Test
void handleDoesNotUpdateStatusWhenLastWillMacIsUnknown() {
String macAddress = "DC:DA:0C:FA:29:5E";
when(appDeviceMapper.selectById(macAddress)).thenReturn(null);
when(appDeviceMapper.selectByMac("dc:da:0c:fa:29:5e")).thenReturn(null);
DeviceIdentityResolver resolver = new DeviceIdentityResolver(appDeviceMapper);
DeviceStatusHandler handler = new DeviceStatusHandler(resolver, deviceStatusService, new ObjectMapper());
handler.handle(macAddress, "{\"status\":\"offline\"}", false);
verify(deviceStatusService, never()).markOffline(anyString(), anyString());
verify(deviceStatusService, never()).markOnline(anyString());
}
@Test
void handleIgnoresUnknownStatusPayload() {
DeviceStatusHandler handler = newHandler();
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
handler.handle("D01", "{\"status\":\"sleeping\"}");
verify(deviceStatusService, never()).markOnline(anyString());
verify(deviceStatusService, never()).markOffline(anyString(), anyString());
}
private DeviceStatusHandler newHandler() {
return new DeviceStatusHandler(deviceIdentityResolver, deviceStatusService, new ObjectMapper());
}
}

View File

@@ -0,0 +1,73 @@
package org.dromara.app.handler;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dromara.app.domain.bo.AppDeviceBo;
import org.dromara.app.domain.bo.AppWateringLogBo;
import org.dromara.app.domain.vo.AppDeviceVo;
import org.dromara.app.mapper.AppSchedulingDeviceMapper;
import org.dromara.app.service.IAppDeviceService;
import org.dromara.app.service.IAppWateringLogService;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.support.GenericApplicationContext;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class KeyFinishHandlerTest {
@Mock private IAppWateringLogService appWateringLogService;
@Mock private IAppDeviceService appDeviceService;
@Mock private AppSchedulingDeviceMapper schedulingDeviceMapper;
@Mock private DeviceIdentityResolver deviceIdentityResolver;
@Test
void handle_setsDeviceWorkStatusIdleWhenKeyWateringFinished() {
KeyFinishHandler handler = new KeyFinishHandler(
appWateringLogService,
appDeviceService,
schedulingDeviceMapper,
deviceIdentityResolver
);
AppDeviceVo device = new AppDeviceVo();
device.setUserId(99L);
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
when(appDeviceService.queryById("D01")).thenReturn(device);
withJsonContext(() -> {
handler.handle("D01", "{\"startTime\":\"2026-07-06 08:30:00\",\"durationMin\":10}");
return null;
});
ArgumentCaptor<AppWateringLogBo> logCaptor = ArgumentCaptor.forClass(AppWateringLogBo.class);
verify(appWateringLogService).confirmScheduleLog(logCaptor.capture());
assertThat(logCaptor.getValue().getStatus()).isEqualTo("0");
assertThat(logCaptor.getValue().getTriggerType()).isEqualTo("1");
ArgumentCaptor<AppDeviceBo> deviceCaptor = ArgumentCaptor.forClass(AppDeviceBo.class);
verify(appDeviceService).updateByBo(deviceCaptor.capture());
AppDeviceBo updateBo = deviceCaptor.getValue();
assertThat(updateBo.getDeviceNo()).isEqualTo("D01");
assertThat(updateBo.getWorkStatus()).isEqualTo("0");
}
private <T> T withJsonContext(Supplier<T> action) {
try (GenericApplicationContext applicationContext = new GenericApplicationContext()) {
applicationContext.registerBean(ObjectMapper.class, (Supplier<ObjectMapper>) ObjectMapper::new);
applicationContext.refresh();
new SpringUtil().setApplicationContext(applicationContext);
return action.get();
}
}
}

View File

@@ -0,0 +1,134 @@
package org.dromara.app.handler;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;
import org.dromara.app.domain.AppDevice;
import org.dromara.app.mapper.AppDeviceMapper;
import org.dromara.app.service.IAppWateringLogService;
import org.dromara.common.redis.utils.RedisUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.Duration;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class MqttDeviceStatusServiceTest {
private static GenericApplicationContext applicationContext;
@Mock
private AppDeviceMapper appDeviceMapper;
@Mock
private IAppWateringLogService wateringLogService;
@Mock
private RedissonClient redissonClient;
@Mock
private RLock lock;
@BeforeAll
static void initializeRedisUtils() {
if (TableInfoHelper.getTableInfo(AppDevice.class) == null) {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new Configuration(), ""), AppDevice.class);
}
applicationContext = new GenericApplicationContext();
applicationContext.registerBean(RedissonClient.class, () -> org.mockito.Mockito.mock(RedissonClient.class));
applicationContext.refresh();
new SpringUtil().setApplicationContext(applicationContext);
}
@AfterAll
static void closeApplicationContext() {
applicationContext.close();
}
@Test
void markOnlineCachesOnlineStatusWithTtlAndUpdatesDatabase() throws Exception {
MqttDeviceStatusService service = newService();
when(redissonClient.getLock("lock:mqtt:device:status:D01")).thenReturn(lock);
when(lock.tryLock(0, 10, TimeUnit.SECONDS)).thenReturn(true);
when(lock.isHeldByCurrentThread()).thenReturn(true);
try (MockedStatic<RedisUtils> redis = mockStatic(RedisUtils.class)) {
redis.when(RedisUtils::getClient).thenReturn(redissonClient);
service.markOnline("D01");
redis.verify(() -> RedisUtils.setCacheObject(
eq("mqtt:device:status:D01"),
any(Map.class),
eq(Duration.ofSeconds(900))
));
verify(appDeviceMapper).update(eq(null), any(LambdaUpdateWrapper.class));
verify(lock).unlock();
}
}
@Test
void markOfflineDeletesOnlineCacheUpdatesDatabaseAndFinishesRunningLogs() throws Exception {
MqttDeviceStatusService service = newService();
when(redissonClient.getLock("lock:mqtt:device:status:D01")).thenReturn(lock);
when(lock.tryLock(0, 10, TimeUnit.SECONDS)).thenReturn(true);
when(lock.isHeldByCurrentThread()).thenReturn(true);
when(appDeviceMapper.update(eq(null), any(LambdaUpdateWrapper.class))).thenReturn(1);
try (MockedStatic<RedisUtils> redis = mockStatic(RedisUtils.class)) {
redis.when(RedisUtils::getClient).thenReturn(redissonClient);
service.markOffline("D01", "设备 MQTT 状态离线");
redis.verify(() -> RedisUtils.deleteObject("mqtt:device:status:D01"));
verify(appDeviceMapper).update(eq(null), any(LambdaUpdateWrapper.class));
verify(wateringLogService).finishRunningLogsByDevice(eq("D01"), any(Date.class), eq("设备 MQTT 状态离线"));
verify(lock).unlock();
}
}
@Test
void markOfflineIfCacheMissingSkipsWhenDeviceCameBackOnline() throws Exception {
MqttDeviceStatusService service = newService();
when(redissonClient.getLock("lock:mqtt:device:status:D01")).thenReturn(lock);
when(lock.tryLock(0, 10, TimeUnit.SECONDS)).thenReturn(true);
when(lock.isHeldByCurrentThread()).thenReturn(true);
try (MockedStatic<RedisUtils> redis = mockStatic(RedisUtils.class)) {
redis.when(RedisUtils::getClient).thenReturn(redissonClient);
redis.when(() -> RedisUtils.hasKey("mqtt:device:status:D01")).thenReturn(true);
service.markOfflineIfCacheMissing("D01", "设备掉线");
redis.verify(RedisUtils::getClient);
redis.verify(() -> RedisUtils.hasKey("mqtt:device:status:D01"));
redis.verify(() -> RedisUtils.deleteObject("mqtt:device:status:D01"), never());
verify(appDeviceMapper, never()).update(eq(null), any(LambdaUpdateWrapper.class));
verify(wateringLogService, never()).finishRunningLogsByDevice(eq("D01"), any(Date.class), eq("设备掉线"));
verify(lock).unlock();
}
}
private MqttDeviceStatusService newService() {
MqttDeviceStatusService service = new MqttDeviceStatusService(appDeviceMapper, wateringLogService);
ReflectionTestUtils.setField(service, "deviceStatusCachePrefix", "mqtt:device:status:");
ReflectionTestUtils.setField(service, "deviceStatusCacheTtlSeconds", 900L);
return service;
}
}

View File

@@ -0,0 +1,115 @@
package org.dromara.app.handler;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dromara.app.domain.AppSchedulingDevice;
import org.dromara.app.domain.bo.AppDeviceBo;
import org.dromara.app.domain.bo.AppWateringLogBo;
import org.dromara.app.domain.vo.AppDeviceVo;
import org.dromara.app.mapper.AppSchedulingDeviceMapper;
import org.dromara.app.service.IAppDeviceService;
import org.dromara.app.service.IAppWateringLogService;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.support.GenericApplicationContext;
import java.util.Calendar;
import java.util.List;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class ScheduleFinishHandlerTest {
@Mock private IAppWateringLogService appWateringLogService;
@Mock private IAppDeviceService appDeviceService;
@Mock private AppSchedulingDeviceMapper schedulingDeviceMapper;
@Mock private DeviceIdentityResolver deviceIdentityResolver;
@Test
void handle_setsDeviceWorkStatusIdleWhenScheduleWateringFinished() {
ScheduleFinishHandler handler = new ScheduleFinishHandler(
appWateringLogService,
appDeviceService,
schedulingDeviceMapper,
deviceIdentityResolver
);
AppDeviceVo device = new AppDeviceVo();
device.setUserId(99L);
AppSchedulingDevice binding = new AppSchedulingDevice();
binding.setDeviceNo("D01");
binding.setScheduleId(10L);
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
when(appDeviceService.queryById("D01")).thenReturn(device);
when(schedulingDeviceMapper.selectList(any())).thenReturn(List.of(binding));
withJsonContext(() -> {
handler.handle("D01", "{\"startTime\":\"2026-07-06 08:30:00\",\"durationMin\":10}");
return null;
});
ArgumentCaptor<AppWateringLogBo> logCaptor = ArgumentCaptor.forClass(AppWateringLogBo.class);
verify(appWateringLogService).confirmScheduleLog(logCaptor.capture());
assertThat(logCaptor.getValue().getStatus()).isEqualTo("0");
ArgumentCaptor<AppDeviceBo> deviceCaptor = ArgumentCaptor.forClass(AppDeviceBo.class);
verify(appDeviceService).updateByBo(deviceCaptor.capture());
AppDeviceBo updateBo = deviceCaptor.getValue();
assertThat(updateBo.getDeviceNo()).isEqualTo("D01");
assertThat(updateBo.getWorkStatus()).isEqualTo("0");
}
@Test
void handle_preservesSecondsWhenScheduleFinishReportsTimeOnly() {
ScheduleFinishHandler handler = new ScheduleFinishHandler(
appWateringLogService,
appDeviceService,
schedulingDeviceMapper,
deviceIdentityResolver
);
AppDeviceVo device = new AppDeviceVo();
device.setUserId(99L);
AppSchedulingDevice binding = new AppSchedulingDevice();
binding.setDeviceNo("D01");
binding.setScheduleId(10L);
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
when(appDeviceService.queryById("D01")).thenReturn(device);
when(schedulingDeviceMapper.selectList(any())).thenReturn(List.of(binding));
withJsonContext(() -> {
handler.handle("D01", "{\"startTime\":\"08:30:27\",\"durationMin\":10}");
return null;
});
ArgumentCaptor<AppWateringLogBo> logCaptor = ArgumentCaptor.forClass(AppWateringLogBo.class);
verify(appWateringLogService).confirmScheduleLog(logCaptor.capture());
AppWateringLogBo logBo = logCaptor.getValue();
assertThat(secondOf(logBo.getStartTime())).isEqualTo(27);
}
private <T> T withJsonContext(Supplier<T> action) {
try (GenericApplicationContext applicationContext = new GenericApplicationContext()) {
applicationContext.registerBean(ObjectMapper.class, (Supplier<ObjectMapper>) ObjectMapper::new);
applicationContext.refresh();
new SpringUtil().setApplicationContext(applicationContext);
return action.get();
}
}
private int secondOf(java.util.Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.SECOND);
}
}

View File

@@ -0,0 +1,193 @@
package org.dromara.app.handler;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.dromara.app.domain.AppSchedulingDevice;
import org.dromara.app.domain.bo.AppDeviceBo;
import org.dromara.app.domain.bo.AppWateringLogBo;
import org.dromara.app.domain.vo.AppDeviceVo;
import org.dromara.app.domain.vo.AppWateringLogVo;
import org.dromara.app.mapper.AppSchedulingDeviceMapper;
import org.dromara.app.service.IAppDeviceService;
import org.dromara.app.service.IAppWateringLogService;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.support.GenericApplicationContext;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class StartWaterHandlerTest {
@Mock private IAppWateringLogService appWateringLogService;
@Mock private IAppDeviceService appDeviceService;
@Mock private AppSchedulingDeviceMapper schedulingDeviceMapper;
@Mock private DeviceIdentityResolver deviceIdentityResolver;
@Test
void handle_insertsRunningScheduleWateringLog() throws Exception {
StartWaterHandler handler = new StartWaterHandler(
appWateringLogService,
appDeviceService,
schedulingDeviceMapper,
deviceIdentityResolver
);
AppDeviceVo device = new AppDeviceVo();
device.setUserId(99L);
AppSchedulingDevice binding = new AppSchedulingDevice();
binding.setDeviceNo("D01");
binding.setScheduleId(10L);
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
when(appDeviceService.queryById("D01")).thenReturn(device);
when(schedulingDeviceMapper.selectList(any())).thenReturn(List.of(binding));
withJsonContext(() -> {
handler.handle("D01", "{\"startTime\":\"2026-07-06 08:30:00\",\"triggerON\":\"schedule\"}");
return null;
});
ArgumentCaptor<AppWateringLogBo> captor = ArgumentCaptor.forClass(AppWateringLogBo.class);
verify(appWateringLogService).insertByBo(captor.capture());
AppWateringLogBo logBo = captor.getValue();
assertThat(logBo.getDeviceNo()).isEqualTo("D01");
assertThat(logBo.getUserId()).isEqualTo(99L);
assertThat(logBo.getScheduleId()).isEqualTo(10L);
assertThat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(logBo.getStartTime()))
.isEqualTo("2026-07-06 08:30:00");
assertThat(logBo.getTriggerType()).isEqualTo("0");
assertThat(logBo.getStatus()).isEqualTo("1");
assertThat(logBo.getEndTime()).isNull();
assertThat(logBo.getRemark()).isEqualTo("设备上报排程开始浇水");
ArgumentCaptor<AppDeviceBo> deviceCaptor = ArgumentCaptor.forClass(AppDeviceBo.class);
verify(appDeviceService).updateByBo(deviceCaptor.capture());
AppDeviceBo deviceBo = deviceCaptor.getValue();
assertThat(deviceBo.getDeviceNo()).isEqualTo("D01");
assertThat(deviceBo.getWorkStatus()).isEqualTo("1");
}
@Test
void handle_skipsDuplicateRunningWateringLogWithSameStartTime() throws Exception {
StartWaterHandler handler = new StartWaterHandler(
appWateringLogService,
appDeviceService,
schedulingDeviceMapper,
deviceIdentityResolver
);
AppDeviceVo device = new AppDeviceVo();
device.setUserId(99L);
AppWateringLogVo activeLog = new AppWateringLogVo();
activeLog.setDeviceNo("D01");
activeLog.setUserId(99L);
activeLog.setTriggerType("1");
activeLog.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2026-07-06 08:30:00"));
activeLog.setEndTime(null);
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
when(appDeviceService.queryById("D01")).thenReturn(device);
lenient().when(appWateringLogService.queryList(any(AppWateringLogBo.class))).thenReturn(List.of(activeLog));
withJsonContext(() -> {
handler.handle("D01", "{\"startTime\":\"2026-07-06 08:30:00\",\"triggerON\":\"manual\"}");
return null;
});
verify(appWateringLogService, never()).insertByBo(any(AppWateringLogBo.class));
ArgumentCaptor<AppDeviceBo> deviceCaptor = ArgumentCaptor.forClass(AppDeviceBo.class);
verify(appDeviceService).updateByBo(deviceCaptor.capture());
assertThat(deviceCaptor.getValue().getDeviceNo()).isEqualTo("D01");
assertThat(deviceCaptor.getValue().getWorkStatus()).isEqualTo("1");
}
@Test
void handle_skipsDuplicateRunningWateringLogWithinSameMinute() throws Exception {
StartWaterHandler handler = new StartWaterHandler(
appWateringLogService,
appDeviceService,
schedulingDeviceMapper,
deviceIdentityResolver
);
AppDeviceVo device = new AppDeviceVo();
device.setUserId(99L);
AppWateringLogVo activeLog = new AppWateringLogVo();
activeLog.setDeviceNo("D01");
activeLog.setUserId(99L);
activeLog.setScheduleId(0L);
activeLog.setTriggerType("1");
activeLog.setStatus("1");
activeLog.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2026-07-06 08:30:00"));
activeLog.setEndTime(null);
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
when(appDeviceService.queryById("D01")).thenReturn(device);
lenient().when(appWateringLogService.queryList(any(AppWateringLogBo.class))).thenReturn(List.of(activeLog));
withJsonContext(() -> {
handler.handle("D01", "{\"startTime\":\"2026-07-06 08:30:27\",\"triggerON\":\"manual\"}");
return null;
});
verify(appWateringLogService, never()).insertByBo(any(AppWateringLogBo.class));
ArgumentCaptor<AppDeviceBo> deviceCaptor = ArgumentCaptor.forClass(AppDeviceBo.class);
verify(appDeviceService).updateByBo(deviceCaptor.capture());
assertThat(deviceCaptor.getValue().getDeviceNo()).isEqualTo("D01");
assertThat(deviceCaptor.getValue().getWorkStatus()).isEqualTo("1");
}
@Test
void handle_setsTodayEndTimeFromHourMinuteStartTimeAndDurationMin() {
StartWaterHandler handler = new StartWaterHandler(
appWateringLogService,
appDeviceService,
schedulingDeviceMapper,
deviceIdentityResolver
);
AppDeviceVo device = new AppDeviceVo();
device.setUserId(99L);
String today = new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
when(deviceIdentityResolver.resolveDeviceNo("D01")).thenReturn("D01");
when(appDeviceService.queryById("D01")).thenReturn(device);
withJsonContext(() -> {
handler.handle("D01", "{\"deviceNo\":\"D01\",\"startTime\":\"16:39\",\"durationMin\":10,\"triggerON\":\"manual\"}");
return null;
});
ArgumentCaptor<AppWateringLogBo> captor = ArgumentCaptor.forClass(AppWateringLogBo.class);
verify(appWateringLogService).insertByBo(captor.capture());
AppWateringLogBo logBo = captor.getValue();
assertThat(logBo.getDurationMin()).isEqualTo("10");
assertThat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(logBo.getStartTime()))
.isEqualTo(today + " 16:39:00");
assertThat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(logBo.getEndTime()))
.isEqualTo(today + " 16:49:00");
assertThat(logBo.getStatus()).isEqualTo("1");
ArgumentCaptor<AppDeviceBo> deviceCaptor = ArgumentCaptor.forClass(AppDeviceBo.class);
verify(appDeviceService).updateByBo(deviceCaptor.capture());
assertThat(deviceCaptor.getValue().getDeviceNo()).isEqualTo("D01");
assertThat(deviceCaptor.getValue().getWorkStatus()).isEqualTo("1");
}
private <T> T withJsonContext(Supplier<T> action) {
try (GenericApplicationContext applicationContext = new GenericApplicationContext()) {
applicationContext.registerBean(ObjectMapper.class, (Supplier<ObjectMapper>) ObjectMapper::new);
applicationContext.refresh();
new SpringUtil().setApplicationContext(applicationContext);
return action.get();
}
}
}

View File

@@ -0,0 +1,188 @@
package org.dromara.app.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.dromara.app.domain.AppDevice;
import org.dromara.app.domain.bo.AppDeviceBo;
import org.dromara.app.mapper.AppDeviceMapper;
import org.dromara.app.mapper.AppSchedulingDeviceMapper;
import org.dromara.app.mapper.AppWateringLogMapper;
import org.dromara.app.service.IAppWateringLogService;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.satoken.utils.LoginHelper;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class AppDeviceServiceImplTest {
@Mock
private AppDeviceMapper appDeviceMapper;
@Mock
private AppSchedulingDeviceMapper schedulingDeviceMapper;
@Mock
private AppWateringLogMapper wateringLogMapper;
@Mock
private IAppWateringLogService wateringLogService;
@Test
void renderQrCodeImage_addsDeviceNoBelowQrCode() throws Exception {
byte[] imageBytes = AppDeviceServiceImpl.renderQrCodeImage("{\"deviceNo\":\"D20260702001\"}", "D20260702001");
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
assertThat(image.getWidth()).isEqualTo(300);
assertThat(image.getHeight()).isEqualTo(320);
assertThat(countNonWhitePixels(image, 300, 320)).isGreaterThan(0);
}
@Test
void deleteWithValidByIds_allowsSuperAdminToDeleteDeviceOwnedByAnotherUser() {
AppDeviceServiceImpl service = new AppDeviceServiceImpl(
appDeviceMapper,
schedulingDeviceMapper,
wateringLogMapper,
wateringLogService
);
when(appDeviceMapper.delete(any(Wrapper.class))).thenReturn(1);
try (MockedStatic<LoginHelper> loginHelper = mockStatic(LoginHelper.class)) {
loginHelper.when(LoginHelper::isSuperAdmin).thenReturn(true);
Boolean result = service.deleteWithValidByIds(List.of("D01"), true);
assertThat(result).isTrue();
verify(appDeviceMapper, never()).selectCount(any(Wrapper.class));
verify(appDeviceMapper).delete(any(Wrapper.class));
}
}
@Test
void deleteWithValidByIds_allowsAuthorizedSystemUserToDeleteDeviceOwnedByAnotherUser() {
AppDeviceServiceImpl service = new AppDeviceServiceImpl(
appDeviceMapper,
schedulingDeviceMapper,
wateringLogMapper,
wateringLogService
);
when(appDeviceMapper.delete(any(Wrapper.class))).thenReturn(1);
try (MockedStatic<LoginHelper> loginHelper = mockStatic(LoginHelper.class)) {
loginHelper.when(LoginHelper::isSuperAdmin).thenReturn(false);
loginHelper.when(LoginHelper::isTenantAdmin).thenReturn(false);
loginHelper.when(LoginHelper::getUserType).thenReturn(UserType.SYS_USER);
Boolean result = service.deleteWithValidByIds(List.of("D01"), true);
assertThat(result).isTrue();
verify(appDeviceMapper, never()).selectCount(any(Wrapper.class));
verify(appDeviceMapper).delete(any(Wrapper.class));
}
}
@Test
void bindDeviceStatus_findsDeviceByDeviceNo() {
AppDeviceServiceImpl service = new AppDeviceServiceImpl(
appDeviceMapper,
schedulingDeviceMapper,
wateringLogMapper,
wateringLogService
);
AppDeviceBo bo = new AppDeviceBo();
bo.setDeviceNo("D01");
AppDevice device = new AppDevice();
device.setDeviceNo("D01");
device.setUserId(100L);
when(appDeviceMapper.selectById("D01")).thenReturn(device);
try (MockedStatic<LoginHelper> loginHelper = mockStatic(LoginHelper.class)) {
loginHelper.when(LoginHelper::getUserId).thenReturn(100L);
Map<String, Object> result = service.bindDeviceStatus(bo);
assertThat(result.get("bindDeviceStatus")).isEqualTo(200);
assertThat(result.get("bindDevice")).isSameAs(device);
verify(appDeviceMapper).selectById("D01");
verify(appDeviceMapper, never()).selectByMac(any());
}
}
@Test
void bindDeviceStatus_findsDeviceByDeviceInitName() {
AppDeviceServiceImpl service = new AppDeviceServiceImpl(
appDeviceMapper,
schedulingDeviceMapper,
wateringLogMapper,
wateringLogService
);
AppDeviceBo bo = new AppDeviceBo();
bo.setDeviceInitName("INIT-01");
AppDevice device = new AppDevice();
device.setDeviceNo("D01");
device.setDeviceInitName("INIT-01");
device.setUserId(100L);
when(appDeviceMapper.selectByDeviceInitName("INIT-01")).thenReturn(device);
try (MockedStatic<LoginHelper> loginHelper = mockStatic(LoginHelper.class)) {
loginHelper.when(LoginHelper::getUserId).thenReturn(100L);
Map<String, Object> result = service.bindDeviceStatus(bo);
assertThat(result.get("bindDeviceStatus")).isEqualTo(200);
assertThat(result.get("bindDevice")).isSameAs(device);
verify(appDeviceMapper).selectByDeviceInitName("INIT-01");
verify(appDeviceMapper, never()).selectByMac(any());
}
}
@Test
void bindDeviceStatus_returnsUnboundWhenNetworkStatusFieldsAreNull() {
AppDeviceServiceImpl service = new AppDeviceServiceImpl(
appDeviceMapper,
schedulingDeviceMapper,
wateringLogMapper,
wateringLogService
);
AppDeviceBo bo = new AppDeviceBo();
bo.setDeviceNo("D01");
AppDevice device = new AppDevice();
device.setDeviceNo("D01");
when(appDeviceMapper.selectById("D01")).thenReturn(device);
try (MockedStatic<LoginHelper> loginHelper = mockStatic(LoginHelper.class)) {
loginHelper.when(LoginHelper::getUserId).thenReturn(100L);
Map<String, Object> result = service.bindDeviceStatus(bo);
assertThat(result.get("bindDeviceStatus")).isEqualTo(304);
assertThat(result.get("bindDeviceStatusName")).isEqualTo("设备未绑定,请先绑定用户");
}
}
private int countNonWhitePixels(BufferedImage image, int startY, int endY) {
int count = 0;
for (int y = startY; y < endY; y++) {
for (int x = 0; x < image.getWidth(); x++) {
if ((image.getRGB(x, y) & 0x00FFFFFF) != 0x00FFFFFF) {
count++;
}
}
}
return count;
}
}

View File

@@ -0,0 +1,413 @@
package org.dromara.app.service.impl;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import io.github.linpeilie.Converter;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;
import org.dromara.app.domain.AppWateringLog;
import org.dromara.app.domain.bo.AppWateringLogBo;
import org.dromara.app.mapper.AppWateringLogMapper;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.support.GenericApplicationContext;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class AppWateringLogServiceImplTest {
@Mock
private AppWateringLogMapper baseMapper;
@BeforeAll
static void initMybatisPlusTableInfo() {
if (TableInfoHelper.getTableInfo(AppWateringLog.class) == null) {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new Configuration(), ""), AppWateringLog.class);
}
}
@Test
void confirmScheduleLog_updatesMatchingRunningScheduleLogBeforeInsert() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AppWateringLogBo bo = new AppWateringLogBo();
bo.setDeviceNo("D01");
bo.setScheduleId(10L);
bo.setUserId(99L);
bo.setStartTime(format.parse("2026-07-07 08:30:00"));
bo.setDurationMin("10");
bo.setEndTime(format.parse("2026-07-07 08:40:00"));
bo.setTriggerType("0");
bo.setStatus("0");
bo.setRemark("排程浇水完成");
AppWateringLog runningLog = new AppWateringLog();
runningLog.setId(100L);
runningLog.setDeviceNo("D01");
runningLog.setScheduleId(10L);
runningLog.setStartTime(bo.getStartTime());
runningLog.setDurationMin("10");
runningLog.setEndTime(bo.getEndTime());
runningLog.setTriggerType("0");
runningLog.setStatus("1");
when(baseMapper.selectOne(any(Wrapper.class))).thenReturn(null, runningLog);
when(baseMapper.updateById(any(AppWateringLog.class))).thenReturn(1);
Boolean result = withConverterContext(() -> {
AppWateringLogServiceImpl service = new AppWateringLogServiceImpl(baseMapper);
return service.confirmScheduleLog(bo);
});
assertThat(result).isTrue();
ArgumentCaptor<AppWateringLog> updateCaptor = ArgumentCaptor.forClass(AppWateringLog.class);
verify(baseMapper).updateById(updateCaptor.capture());
AppWateringLog update = updateCaptor.getValue();
assertThat(update.getId()).isEqualTo(100L);
assertThat(update.getStatus()).isEqualTo("0");
assertThat(update.getRemark()).isEqualTo("排程浇水完成");
verify(baseMapper, never()).insert(any(AppWateringLog.class));
}
@Test
void confirmScheduleLog_updatesMatchingRunningManualLogBeforeInsert() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AppWateringLogBo bo = new AppWateringLogBo();
bo.setDeviceNo("D01");
bo.setScheduleId(0L);
bo.setUserId(99L);
bo.setStartTime(format.parse("2026-07-07 08:30:00"));
bo.setDurationMin("10");
bo.setEndTime(format.parse("2026-07-07 08:40:00"));
bo.setTriggerType("1");
bo.setStatus("0");
bo.setRemark("设备按键完成浇水");
AppWateringLog runningLog = new AppWateringLog();
runningLog.setId(101L);
runningLog.setDeviceNo("D01");
runningLog.setScheduleId(0L);
runningLog.setStartTime(bo.getStartTime());
runningLog.setDurationMin("10");
runningLog.setEndTime(bo.getEndTime());
runningLog.setTriggerType("1");
runningLog.setStatus("1");
when(baseMapper.selectOne(any(Wrapper.class))).thenReturn(null, runningLog);
when(baseMapper.updateById(any(AppWateringLog.class))).thenReturn(1);
Boolean result = withConverterContext(() -> {
AppWateringLogServiceImpl service = new AppWateringLogServiceImpl(baseMapper);
return service.confirmScheduleLog(bo);
});
assertThat(result).isTrue();
ArgumentCaptor<AppWateringLog> updateCaptor = ArgumentCaptor.forClass(AppWateringLog.class);
verify(baseMapper).updateById(updateCaptor.capture());
AppWateringLog update = updateCaptor.getValue();
assertThat(update.getId()).isEqualTo(101L);
assertThat(update.getTriggerType()).isEqualTo("1");
assertThat(update.getStatus()).isEqualTo("0");
assertThat(update.getRemark()).isEqualTo("设备按键完成浇水");
verify(baseMapper, never()).insert(any(AppWateringLog.class));
}
@Test
void confirmScheduleLog_matchesRunningLogByMinuteRange() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AppWateringLogBo bo = new AppWateringLogBo();
bo.setDeviceNo("D01");
bo.setScheduleId(10L);
bo.setUserId(99L);
bo.setStartTime(format.parse("2026-07-07 09:20:27"));
bo.setDurationMin("10");
bo.setEndTime(format.parse("2026-07-07 09:30:27"));
bo.setTriggerType("0");
bo.setStatus("0");
bo.setRemark("排程浇水完成");
AppWateringLog runningLog = new AppWateringLog();
runningLog.setId(102L);
runningLog.setDeviceNo("D01");
runningLog.setStartTime(format.parse("2026-07-07 09:20:00"));
runningLog.setDurationMin("10");
runningLog.setEndTime(format.parse("2026-07-07 09:30:00"));
runningLog.setStatus("1");
when(baseMapper.selectOne(any(Wrapper.class))).thenReturn(null, runningLog);
when(baseMapper.updateById(any(AppWateringLog.class))).thenReturn(1);
Boolean result = withConverterContext(() -> {
AppWateringLogServiceImpl service = new AppWateringLogServiceImpl(baseMapper);
return service.confirmScheduleLog(bo);
});
assertThat(result).isTrue();
ArgumentCaptor<Wrapper> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(baseMapper, times(2)).selectOne(wrapperCaptor.capture());
List<Wrapper> wrappers = wrapperCaptor.getAllValues();
String runningQuery = wrappers.get(1).getCustomSqlSegment().toLowerCase();
assertThat(runningQuery).contains("starttime between");
assertThat(runningQuery).doesNotContain("starttime =");
}
@Test
void confirmScheduleLog_matchesRunningManualLogWithoutDurationEquality() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AppWateringLogBo bo = new AppWateringLogBo();
bo.setDeviceNo("D01");
bo.setScheduleId(0L);
bo.setUserId(99L);
bo.setStartTime(format.parse("2026-07-07 09:20:15"));
bo.setDurationMin("3");
bo.setEndTime(format.parse("2026-07-07 09:23:45"));
bo.setTriggerType("1");
bo.setStatus("0");
bo.setRemark("设备按键完成浇水");
AppWateringLog runningLog = new AppWateringLog();
runningLog.setId(103L);
runningLog.setDeviceNo("D01");
runningLog.setScheduleId(0L);
runningLog.setStartTime(format.parse("2026-07-07 09:20:00"));
runningLog.setDurationMin("10");
runningLog.setEndTime(format.parse("2026-07-07 09:30:00"));
runningLog.setTriggerType("1");
runningLog.setStatus("1");
when(baseMapper.selectOne(any(Wrapper.class))).thenReturn(null, runningLog);
when(baseMapper.updateById(any(AppWateringLog.class))).thenReturn(1);
Boolean result = withConverterContext(() -> {
AppWateringLogServiceImpl service = new AppWateringLogServiceImpl(baseMapper);
return service.confirmScheduleLog(bo);
});
assertThat(result).isTrue();
ArgumentCaptor<Wrapper> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(baseMapper, times(2)).selectOne(wrapperCaptor.capture());
String runningQuery = wrapperCaptor.getAllValues().get(1).getCustomSqlSegment().toLowerCase();
assertThat(runningQuery).contains("starttime between");
assertThat(runningQuery).contains("triggertype =");
assertThat(runningQuery).doesNotContain("durationmin =");
ArgumentCaptor<AppWateringLog> updateCaptor = ArgumentCaptor.forClass(AppWateringLog.class);
verify(baseMapper).updateById(updateCaptor.capture());
assertThat(updateCaptor.getValue().getId()).isEqualTo(103L);
verify(baseMapper, never()).insert(any(AppWateringLog.class));
}
@Test
void confirmScheduleLog_matchesRunningScheduleLogWithoutDurationEqualityWhenFinishedEarly() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AppWateringLogBo bo = new AppWateringLogBo();
bo.setDeviceNo("D01");
bo.setScheduleId(10L);
bo.setUserId(99L);
bo.setStartTime(format.parse("2026-07-07 09:20:15"));
bo.setDurationMin("3");
bo.setEndTime(format.parse("2026-07-07 09:23:45"));
bo.setTriggerType("0");
bo.setStatus("0");
bo.setRemark("设备上报排程浇水完成");
AppWateringLog runningLog = new AppWateringLog();
runningLog.setId(104L);
runningLog.setDeviceNo("D01");
runningLog.setScheduleId(10L);
runningLog.setStartTime(format.parse("2026-07-07 09:20:00"));
runningLog.setDurationMin("10");
runningLog.setEndTime(format.parse("2026-07-07 09:30:00"));
runningLog.setTriggerType("0");
runningLog.setStatus("1");
when(baseMapper.selectOne(any(Wrapper.class))).thenReturn(null, runningLog);
when(baseMapper.updateById(any(AppWateringLog.class))).thenReturn(1);
Boolean result = withConverterContext(() -> {
AppWateringLogServiceImpl service = new AppWateringLogServiceImpl(baseMapper);
return service.confirmScheduleLog(bo);
});
assertThat(result).isTrue();
ArgumentCaptor<Wrapper> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(baseMapper, times(2)).selectOne(wrapperCaptor.capture());
String runningQuery = wrapperCaptor.getAllValues().get(1).getCustomSqlSegment().toLowerCase();
assertThat(runningQuery).contains("starttime between");
assertThat(runningQuery).contains("triggertype =");
assertThat(runningQuery).doesNotContain("durationmin =");
ArgumentCaptor<AppWateringLog> updateCaptor = ArgumentCaptor.forClass(AppWateringLog.class);
verify(baseMapper).updateById(updateCaptor.capture());
assertThat(updateCaptor.getValue().getId()).isEqualTo(104L);
verify(baseMapper, never()).insert(any(AppWateringLog.class));
}
@Test
void confirmScheduleLog_updatesExistingFinishedManualLogByMinuteBeforeInsert() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AppWateringLogBo bo = new AppWateringLogBo();
bo.setDeviceNo("D01");
bo.setScheduleId(0L);
bo.setUserId(99L);
bo.setStartTime(format.parse("2026-07-07 10:31:27"));
bo.setDurationMin("3");
bo.setEndTime(format.parse("2026-07-07 10:34:27"));
bo.setTriggerType("1");
bo.setStatus("0");
bo.setRemark("设备按键完成浇水");
AppWateringLog finishedLog = new AppWateringLog();
finishedLog.setId(106L);
finishedLog.setDeviceNo("D01");
finishedLog.setScheduleId(0L);
finishedLog.setStartTime(format.parse("2026-07-07 10:31:00"));
finishedLog.setDurationMin("2");
finishedLog.setEndTime(format.parse("2026-07-07 10:33:30"));
finishedLog.setTriggerType("1");
finishedLog.setStatus("0");
when(baseMapper.selectOne(any(Wrapper.class))).thenReturn(null, null, finishedLog);
when(baseMapper.updateById(any(AppWateringLog.class))).thenReturn(1);
Boolean result = withConverterContext(() -> {
AppWateringLogServiceImpl service = new AppWateringLogServiceImpl(baseMapper);
return service.confirmScheduleLog(bo);
});
assertThat(result).isTrue();
ArgumentCaptor<Wrapper> wrapperCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(baseMapper, times(3)).selectOne(wrapperCaptor.capture());
String existingQuery = wrapperCaptor.getAllValues().get(2).getCustomSqlSegment().toLowerCase();
assertThat(existingQuery).contains("starttime between");
assertThat(existingQuery).contains("triggertype =");
assertThat(existingQuery).contains("status =");
ArgumentCaptor<AppWateringLog> updateCaptor = ArgumentCaptor.forClass(AppWateringLog.class);
verify(baseMapper).updateById(updateCaptor.capture());
assertThat(updateCaptor.getValue().getId()).isEqualTo(106L);
assertThat(updateCaptor.getValue().getStatus()).isEqualTo("0");
verify(baseMapper, never()).insert(any(AppWateringLog.class));
}
@Test
void finishRunningLogsByDevice_finishesLatestStatusOneLogWithPlannedEndTime() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AppWateringLog runningLog = new AppWateringLog();
runningLog.setId(105L);
runningLog.setDeviceNo("D01");
runningLog.setStartTime(format.parse("2026-07-07 09:20:00"));
runningLog.setEndTime(format.parse("2026-07-07 09:30:00"));
runningLog.setDurationMin("10");
runningLog.setTriggerType("0");
runningLog.setStatus("1");
when(baseMapper.selectOne(any(Wrapper.class))).thenReturn(runningLog);
when(baseMapper.update(eq(null), any(Wrapper.class))).thenReturn(1);
AppWateringLogServiceImpl service = new AppWateringLogServiceImpl(baseMapper);
int result = service.finishRunningLogsByDevice(
"D01",
format.parse("2026-07-07 09:23:30"),
"手动停止浇水"
);
assertThat(result).isEqualTo(1);
ArgumentCaptor<Wrapper> queryCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(baseMapper).selectOne(queryCaptor.capture());
String query = queryCaptor.getValue().getCustomSqlSegment().toLowerCase();
assertThat(query).contains("status =");
assertThat(query).contains("order by");
assertThat(query).contains("limit 1");
assertThat(query).doesNotContain("endtime is null");
ArgumentCaptor<Wrapper> updateCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(baseMapper).update(eq(null), updateCaptor.capture());
LambdaUpdateWrapper<AppWateringLog> updateWrapper = (LambdaUpdateWrapper<AppWateringLog>) updateCaptor.getValue();
String sqlSet = updateWrapper.getSqlSet().toLowerCase();
assertThat(sqlSet).contains("status");
assertThat(sqlSet).contains("endtime");
assertThat(updateWrapper.getParamNameValuePairs().values()).contains("0");
}
@Test
void saveEstimatedScheduleLog_defaultsStatusZeroBeforeInsert() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AppWateringLogBo bo = new AppWateringLogBo();
bo.setDeviceNo("D01");
bo.setScheduleId(10L);
bo.setUserId(99L);
bo.setStartTime(format.parse("2026-07-07 09:20:00"));
bo.setEndTime(format.parse("2026-07-07 09:30:00"));
bo.setDurationMin("10");
when(baseMapper.exists(any(Wrapper.class))).thenReturn(false);
when(baseMapper.insert(any(AppWateringLog.class))).thenReturn(1);
Boolean result = withConverterContext(() -> {
AppWateringLogServiceImpl service = new AppWateringLogServiceImpl(baseMapper);
return service.saveEstimatedScheduleLog(bo);
});
assertThat(result).isTrue();
ArgumentCaptor<AppWateringLog> insertCaptor = ArgumentCaptor.forClass(AppWateringLog.class);
verify(baseMapper).insert(insertCaptor.capture());
AppWateringLog insert = insertCaptor.getValue();
assertThat(insert.getTriggerType()).isEqualTo("0");
assertThat(insert.getStatus()).isEqualTo("0");
assertThat(insert.getRemark()).isEqualTo("设备离线,按排程自动补记");
}
private <T> T withConverterContext(Supplier<T> action) {
try (GenericApplicationContext applicationContext = new GenericApplicationContext()) {
Converter converter = mock(Converter.class);
lenient().when(converter.convert(any(AppWateringLogBo.class), eq(AppWateringLog.class)))
.thenAnswer(invocation -> toEntity(invocation.getArgument(0)));
applicationContext.registerBean(Converter.class, () -> converter);
applicationContext.refresh();
new SpringUtil().setApplicationContext(applicationContext);
return action.get();
}
}
private AppWateringLog toEntity(AppWateringLogBo bo) {
AppWateringLog entity = new AppWateringLog();
entity.setId(bo.getId());
entity.setUserId(bo.getUserId());
entity.setDeviceNo(bo.getDeviceNo());
entity.setCommandId(bo.getCommandId());
entity.setScheduleId(bo.getScheduleId());
entity.setStartTime(bo.getStartTime());
entity.setEndTime(bo.getEndTime());
entity.setDurationMin(bo.getDurationMin());
entity.setZones(bo.getZones());
entity.setTriggerType(bo.getTriggerType());
entity.setRemark(bo.getRemark());
entity.setStatus(bo.getStatus());
entity.setCreateTime(bo.getCreateTime());
return entity;
}
}

View File

@@ -0,0 +1,192 @@
package org.dromara.app.service.impl;
import org.dromara.app.domain.bo.AppWateringLogBo;
import org.dromara.app.domain.mqtt.DeviceCommand;
import org.dromara.app.domain.vo.AppDeviceVo;
import org.dromara.app.service.IAppDeviceService;
import org.dromara.app.service.IAppWateringLogService;
import org.dromara.app.service.IDeviceCommandPublisher;
import org.dromara.common.satoken.utils.LoginHelper;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class DeviceCommandServiceImplTest {
@Mock private IAppDeviceService deviceService;
@Mock private IAppWateringLogService wateringLogService;
@Mock private IDeviceCommandPublisher commandPublisher;
@Test
void sendScheduleBindCommand_buildsScheduleTopicAndPayload() {
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo("D01");
device.setUserId(99L);
device.setMacAddress("AABBCC");
Map<String, Object> payload = new HashMap<>();
payload.put("cmd", -1);
payload.put("deviceNo", "D01");
when(deviceService.queryById("D01")).thenReturn(device);
when(commandPublisher.send(any(DeviceCommand.class))).thenReturn("cmd-1");
DeviceCommandServiceImpl service = new DeviceCommandServiceImpl(deviceService, wateringLogService);
ReflectionTestUtils.setField(service, "commandPublisher", commandPublisher);
String commandId = service.sendScheduleBindCommand("D01", payload);
assertThat(commandId).isEqualTo("cmd-1");
ArgumentCaptor<DeviceCommand> commandCaptor = ArgumentCaptor.forClass(DeviceCommand.class);
verify(commandPublisher).send(commandCaptor.capture());
DeviceCommand command = commandCaptor.getValue();
assertThat(command.getDeviceNo()).isEqualTo("D01");
assertThat(command.getDeviceMac()).isEqualTo("AABBCC");
assertThat(command.getCommandType()).isEqualTo("bindSchedule");
assertThat(command.getTopic()).isEqualTo("/d01/subscriber/schedule");
assertThat(command.getPayload()).containsEntry("cmd", -1).containsEntry("deviceNo", "D01");
}
@Test
void sendScheduleCanceledCommand_buildsScheduleCanceledTopicAndPayload() {
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo("D01");
device.setUserId(99L);
device.setMacAddress("AABBCC");
when(deviceService.queryById("D01")).thenReturn(device);
when(commandPublisher.send(any(DeviceCommand.class))).thenReturn("cmd-1");
DeviceCommandServiceImpl service = new DeviceCommandServiceImpl(deviceService, wateringLogService);
ReflectionTestUtils.setField(service, "commandPublisher", commandPublisher);
String commandId = service.sendScheduleCanceledCommand("D01", 10L);
assertThat(commandId).isEqualTo("cmd-1");
ArgumentCaptor<DeviceCommand> commandCaptor = ArgumentCaptor.forClass(DeviceCommand.class);
verify(commandPublisher).send(commandCaptor.capture());
DeviceCommand command = commandCaptor.getValue();
assertThat(command.getDeviceNo()).isEqualTo("D01");
assertThat(command.getDeviceMac()).isEqualTo("AABBCC");
assertThat(command.getCommandType()).isEqualTo("cancelSchedule");
assertThat(command.getTopic()).isEqualTo("/d01/schedule/canceled");
assertThat(command.getPayload())
.containsEntry("deviceNo", "D01")
.containsEntry("scheduleId", 10L)
.containsEntry("canceled", true);
}
@Test
void sendBindDeviceCommand_defaultsTopicToDeviceNo() {
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo("D01");
device.setUserId(99L);
device.setMacAddress("AABBCC");
when(deviceService.queryById("D01")).thenReturn(device);
when(commandPublisher.send(any(DeviceCommand.class))).thenReturn("cmd-1");
DeviceCommandServiceImpl service = new DeviceCommandServiceImpl(deviceService, wateringLogService);
ReflectionTestUtils.setField(service, "commandPublisher", commandPublisher);
service.sendBindDeviceCommand("D01");
ArgumentCaptor<DeviceCommand> commandCaptor = ArgumentCaptor.forClass(DeviceCommand.class);
verify(commandPublisher).send(commandCaptor.capture());
assertThat(commandCaptor.getValue().getDeviceNo()).isEqualTo("D01");
assertThat(commandCaptor.getValue().getCommandType()).isEqualTo("bindDevice");
assertThat(commandCaptor.getValue().getPayload()).containsEntry("deviceNo", "D01");
}
@Test
void sendBindDeviceCommand_keepsMacAsPayloadOnlyForFirstRegistrationFlow() {
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo("D01");
device.setUserId(99L);
device.setMacAddress("AABBCC");
when(deviceService.queryById("D01")).thenReturn(device);
when(commandPublisher.send(any(DeviceCommand.class))).thenReturn("cmd-1");
DeviceCommandServiceImpl service = new DeviceCommandServiceImpl(deviceService, wateringLogService);
ReflectionTestUtils.setField(service, "commandPublisher", commandPublisher);
service.sendBindDeviceCommand("D01");
ArgumentCaptor<DeviceCommand> commandCaptor = ArgumentCaptor.forClass(DeviceCommand.class);
verify(commandPublisher).send(commandCaptor.capture());
DeviceCommand command = commandCaptor.getValue();
assertThat(command.getDeviceNo()).isEqualTo("D01");
assertThat(command.getDeviceMac()).isEqualTo("AABBCC");
assertThat(command.getCommandType()).isEqualTo("bindDevice");
assertThat(command.getPayload()).containsEntry("deviceNo", "D01");
}
@Test
void sendSwitchCommand_addsSecondsWhenStartTimeOnlyHasHourAndMinute() {
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo("D01");
device.setUserId(99L);
device.setMacAddress("AABBCC");
when(deviceService.queryById("D01")).thenReturn(device);
when(commandPublisher.send(any(DeviceCommand.class))).thenReturn("cmd-1");
DeviceCommandServiceImpl service = new DeviceCommandServiceImpl(deviceService, wateringLogService);
ReflectionTestUtils.setField(service, "commandPublisher", commandPublisher);
try (MockedStatic<LoginHelper> loginHelper = mockStatic(LoginHelper.class)) {
loginHelper.when(LoginHelper::getUserId).thenReturn(99L);
service.sendSwitchCommand("D01", "1", "08:05", 10);
}
ArgumentCaptor<DeviceCommand> commandCaptor = ArgumentCaptor.forClass(DeviceCommand.class);
verify(commandPublisher).send(commandCaptor.capture());
assertThat(commandCaptor.getValue().getPayload()).containsEntry("startTime", "08:05:00");
ArgumentCaptor<AppWateringLogBo> logCaptor = ArgumentCaptor.forClass(AppWateringLogBo.class);
verify(wateringLogService).insertByBo(logCaptor.capture());
AppWateringLogBo logBo = logCaptor.getValue();
assertThat(new SimpleDateFormat("HH:mm:ss").format(logBo.getStartTime())).isEqualTo("08:05:00");
assertThat(new SimpleDateFormat("HH:mm:ss").format(logBo.getEndTime())).isEqualTo("08:15:00");
}
@Test
void sendSwitchCommand_stopFinishesCurrentRunningLogForDevice() {
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo("D01");
device.setUserId(99L);
device.setMacAddress("AABBCC");
when(deviceService.queryById("D01")).thenReturn(device);
when(commandPublisher.send(any(DeviceCommand.class))).thenReturn("cmd-1");
when(wateringLogService.finishRunningLogsByDevice(any(), any(), any())).thenReturn(1);
DeviceCommandServiceImpl service = new DeviceCommandServiceImpl(deviceService, wateringLogService);
ReflectionTestUtils.setField(service, "commandPublisher", commandPublisher);
try (MockedStatic<LoginHelper> loginHelper = mockStatic(LoginHelper.class)) {
loginHelper.when(LoginHelper::getUserId).thenReturn(99L);
service.sendSwitchCommand("D01", "0", null, null);
}
verify(wateringLogService).finishRunningLogsByDevice(eq("D01"), any(), eq("手动停止浇水"));
verify(wateringLogService, never()).finishManualLog(any(), any(), any(), any());
}
}

View File

@@ -0,0 +1,83 @@
package org.dromara.app.task;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;
import org.dromara.app.domain.AppDevice;
import org.dromara.app.handler.MqttDeviceStatusService;
import org.dromara.app.mapper.AppDeviceMapper;
import org.dromara.common.redis.utils.RedisUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.redisson.api.RedissonClient;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.Duration;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@Tag("dev")
class DeviceOfflineCheckTaskTest {
private static GenericApplicationContext applicationContext;
@Mock
private AppDeviceMapper appDeviceMapper;
@Mock
private MqttDeviceStatusService deviceStatusService;
@BeforeAll
static void initializeInfrastructure() {
if (TableInfoHelper.getTableInfo(AppDevice.class) == null) {
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new Configuration(), ""), AppDevice.class);
}
applicationContext = new GenericApplicationContext();
applicationContext.registerBean(RedissonClient.class, () -> mock(RedissonClient.class));
applicationContext.refresh();
new SpringUtil().setApplicationContext(applicationContext);
}
@AfterAll
static void closeApplicationContext() {
applicationContext.close();
}
@Test
void checkOfflineDevicesAddsTtlToLegacyPermanentOnlineKey() {
DeviceOfflineCheckTask task = newTask();
AppDevice device = new AppDevice();
device.setDeviceNo("D01");
when(appDeviceMapper.selectList(any(Wrapper.class))).thenReturn(List.of(device));
try (MockedStatic<RedisUtils> redis = mockStatic(RedisUtils.class)) {
redis.when(() -> RedisUtils.hasKey("mqtt:device:status:D01")).thenReturn(true);
redis.when(() -> RedisUtils.getTimeToLive("mqtt:device:status:D01")).thenReturn(-1L);
task.checkOfflineDevices();
redis.verify(() -> RedisUtils.expire("mqtt:device:status:D01", Duration.ofSeconds(900)));
verify(deviceStatusService, never()).markOfflineIfCacheMissing(any(), any());
}
}
private DeviceOfflineCheckTask newTask() {
DeviceOfflineCheckTask task = new DeviceOfflineCheckTask(appDeviceMapper, deviceStatusService);
ReflectionTestUtils.setField(task, "deviceStatusCachePrefix", "mqtt:device:status:");
ReflectionTestUtils.setField(task, "deviceStatusCacheTtlSeconds", 900L);
ReflectionTestUtils.setField(task, "enabled", true);
ReflectionTestUtils.setField(task, "ttlCompatEnabled", true);
return task;
}
}