浇水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

547
docs/mqtt-spec.md Normal file
View File

@@ -0,0 +1,547 @@
# Water MQTT 通信协议说明文档
## 1. 系统架构概览
```
┌─────────────┐ MQTT Broker ┌─────────────────┐
│ 物理设备 │ ◄══════════════════► │ Water 后端服务 │
│ (ESP32等) │ (SSL/TCP连接) │ (Spring Boot) │
└─────────────┘ └─────────────────┘
│ │
│ 上行 (publish) │ 下行 (subscriber)
│ /{identity}/publish/xxx │ /{deviceNo}/subscriber/xxx
│ │
▼ ▼
设备注册、数据上报、 命令下发、排程同步、
浇水完成、异常告警、ACK 设备绑定/解绑/初始化
```
### 核心组件
| 组件 | 包路径 | 职责 |
|------|--------|------|
| `MqttClientManager` | `org.dromara.mqtt` | MQTT 客户端连接管理、消息收发 |
| `MqttMessageDispatcher` | `org.dromara.app.mqtt` | 上行消息路由分发(策略模式) |
| `MqttTopicHandler` | `org.dromara.app.mqtt` | 上行消息处理器接口 |
| `DeviceMqttCommandPublisher` | `org.dromara.mqtt` | 下行命令发布器 |
| `DeviceCommandServiceImpl` | `org.dromara.app.service.impl` | 命令构造与业务编排 |
| `MqttCommandAckService` | `org.dromara.mqtt` | 命令 ACK 确认与重试 |
| `DeviceIdentityResolver` | `org.dromara.app.handler` | 设备标识解析MAC/设备编号 → deviceNo |
---
## 2. Topic 约定
### 2.1 上行 Topic设备 → 服务端)
服务端通过通配符订阅(如 `+/publish/#`),由 `MqttMessageDispatcher` 按正则分发到对应 Handler。
| Topic 模式 | 正则 | 处理器 | 说明 |
|------------|------|--------|------|
| `/{identity}/publish/register` | `^/([^/]+)/publish/register$` | `DeviceRegisterHandler` | 设备注册/上线 |
| `/{identity}/publish/power` | `^/([^/]+)/publish/power$` | `DeviceDataHandler` | 电量数据上报 |
| `/{identity}/publish/finish/key` | `^/([^/]+)/publish/finish/key$` | `KeyFinishHandler` | 按键/手动浇水完成 |
| `/{identity}/publish/finish/schedule` | `^/([^/]+)/publish/finish/schedule$` | `ScheduleFinishHandler` | 排程浇水完成 |
| `/{identity}/publish/error` | `^/([^/]+)/publish/error$` | `ErromesHandler` | 设备异常告警 |
| `/{identity}/publish/ack` | `^/([^/]+)/publish/ack$` | `DeviceCommandAckHandler` | 命令执行确认 |
> `{identity}` 可以是设备编号deviceNo或 MAC 地址,由 `DeviceIdentityResolver` 统一解析为 deviceNo。
### 2.2 下行 Topic服务端 → 设备)
| Topic 模式 | 用途 | 构造方式 |
|------------|------|---------|
| `/{deviceNo}/subscriber/cmd` | 通用命令下发 | `DeviceMqttCommandPublisher.buildCommandTopic()` |
| `/{deviceNo}/subscriber/schedule` | 排程专用下发 | `DeviceCommandServiceImpl.buildScheduleTopic()` |
> 可通过 `mqtt.topics.publish-prefix` 配置前缀,如配置为 `/water`,则实际 Topic 为 `/water/{deviceNo}/subscriber/cmd`。
> `deviceNo` 统一为小写格式。
---
## 3. 消息格式
### 3.1 下行命令通用结构DeviceCommand
所有下行命令通过 `DeviceCommand` 对象构造,最终以 `payload` 字段的 JSON 发送到 MQTT。
```java
// DeviceCommand 字段
String commandId; // 命令唯一标识UUID自动生成
String deviceNo; // 设备编号
String deviceMac; // 设备 MAC 地址
String commandType; // 命令类型
String topic; // 发送目标 Topic可自定义默认自动构建
Map<String, Object> payload; // 命令负载(最终序列化为 JSON 发送)
int retryCount; // 当前重试次数
long createdAt; // 创建时间戳
long lastSentAt; // 最后发送时间戳
long nextRetryAt; // 下次重试时间戳
```
发送时自动注入到 payload 的字段:
```json
{
"commandId": "自动生成的UUID",
"commandType": "命令类型",
// ... 其他业务字段
}
```
### 3.2 上行 ACK 结构DeviceCommandAck
```json
{
"commandId": "对应下发命令的commandId",
"status": "1",
"message": "可选的文本消息"
}
```
> 也支持非 JSON 格式的纯文本 ACK当设备只有一条待确认命令时可自动匹配
---
## 4. 下行命令类型详解
### 4.1 设备开关命令 — `switchDevice`
**触发**: 用户手动开启/关闭设备浇水
**接口**: `PUT /app/v1/switchDevice`
**Topic**: `/{deviceNo}/subscriber/cmd`
```json
{
"commandId": "xxx",
"commandType": "switchDevice",
"deviceNo": "01",
"cmd": "1",
"startTime": "2026-06-25 14:35:00",
"durationMin": 20
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `cmd` | String | `"1"` = 开启浇水,`"0"` = 停止浇水 |
| `startTime` | String | 开始时间(`yyyy-MM-dd HH:mm:ss``HH:mm` |
| `durationMin` | Integer | 持续时间(分钟),开启时必填且 > 0 |
**附加行为**:
- 开启时自动创建手动浇水日志记录
- 停止时自动结束进行中的手动浇水日志
---
### 4.2 设备绑定命令 — `bindDevice`
**触发**: 用户在 APP 绑定设备
**接口**: `POST /app/v1/addDevice`
**Topic**: `/{deviceNo}/subscriber/cmd`
```json
{
"commandId": "xxx",
"commandType": "bindDevice",
"bindStatus": true,
"deviceNo": "01",
"cmd": -1
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `bindStatus` | Boolean | `true` = 已绑定 |
| `deviceNo` | String | 分配给设备的编号 |
| `cmd` | Integer | `-1` = 非浇水指令 |
---
### 4.3 设备初始化/解绑命令 — `initDevice`
**触发**: 用户删除/解绑设备
**接口**: `DELETE /app/v1/deleteDevice/{deviceNos}`
**Topic**: `/{deviceNo}/subscriber/cmd`
```json
{
"commandId": "xxx",
"commandType": "initDevice",
"deviceNo": "01",
"initStatus": true,
"cmd": "init"
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `initStatus` | Boolean | `true` = 需要恢复出厂设置 |
| `cmd` | String | `"init"` = 初始化指令 |
**附加行为**: 服务端同时清除用户绑定、排程关联、浇水日志。
---
### 4.4 设备编号下发 — `registerDeviceNo`
**触发**: 设备通过 MQTT 注册上线后,服务端自动回复
**接口**: 无(`DeviceRegisterHandler` 自动触发)
**Topic**: `/{deviceMac}/subscriber/cmd`
> 这是唯一保留 MAC 作为 Topic 第一段的下行命令;其余下行命令统一使用 `deviceNo`。
```json
{
"commandId": "xxx",
"commandType": "registerDeviceNo",
"deviceNo": "01",
"deviceMac": "aa:bb:cc:dd:ee:ff"
}
```
---
### 4.5 排程绑定命令 — `bindSchedule`
**触发**: 用户绑定排程到设备 / 修改排程内容 / 修改排程状态
**接口**: `POST /app/v1/addScheduleDevice` · `PUT /app/v1/updataschedule` · `PUT /app/v1/editScheduleStatus`
**Topic**: `/{deviceNo}/subscriber/schedule`(排程专用 Topic
```json
{
"commandId": "xxx",
"commandType": "bindSchedule",
"cmd": -1,
"deviceNo": "01",
"schedule": {
"id": 1,
"name": "每日浇水",
"status": "1"
},
"details": [
{
"id": 10,
"weekday": "1",
"timeData": [
{ "startTime": "08:00", "durationMin": 15 },
{ "startTime": "18:00", "durationMin": 10 }
],
"triggerType": "0",
"status": "1"
}
]
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `schedule.id` | Long | 排程 ID |
| `schedule.name` | String | 排程名称 |
| `schedule.status` | String | `"1"` = 启用,`"0"` = 停用 |
| `details[].weekday` | String | 星期几(`1`-`7` |
| `details[].timeData` | Array | 时间段列表 |
| `details[].triggerType` | String | 触发类型 |
| `details[].status` | String | 明细状态 |
---
### 4.6 排程解绑命令 — `unbindSchedule`
**触发**: 用户删除排程与设备的绑定关系 / 删除排程
**接口**: `DELETE /app/v1/deleteScheduleDevice` · `DELETE /app/v1/deleteschedule/{ids}`
**Topic**: `/{deviceNo}/subscriber/schedule`
```json
{
"commandId": "xxx",
"commandType": "unbindSchedule",
"cmd": -1,
"deviceNo": "01",
"scheduleId": 1,
"unbind": true
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `scheduleId` | Long | 要解绑的排程 ID |
| `unbind` | Boolean | `true` = 解绑 |
---
### 4.7 自定义命令 — 任意 `commandType`
**触发**: 通过 `sendCustomCommand` 接口下发
**Topic**: `/{deviceNo}/subscriber/cmd`
```json
{
"commandId": "xxx",
"commandType": "自定义类型",
// ... 自定义扩展字段
}
```
---
## 5. 上行消息类型详解
### 5.1 设备注册 — `/{identity}/publish/register`
设备上电或重连后发送注册消息。
```json
{
"deviceName": "花园浇水器",
"deviceMac": "aa:bb:cc:dd:ee:ff",
"powerLevel": "85",
"deviceEm": "型号",
"deviceSn": "序列号",
"version": "1.0.0"
}
```
**服务端处理**:
1. 通过 MAC 或设备编号解析入库设备
2. 更新设备注册信息(名称、电量、固件版本等)
3. 刷新设备在线状态到 Redis
4. 自动回复设备编号(`registerDeviceNo` 命令)
---
### 5.2 电量上报 — `/{identity}/publish/power`
```json
{
"powerLevel": "78"
}
```
**服务端处理**: 更新设备电量 + 刷新在线状态。
---
### 5.3 按键浇水完成 — `/{identity}/publish/finish/key`
```json
{
"deviceNo": "01",
"commandId": "对应的命令ID",
"startTime": "2026-06-25 08:00:00",
"endTime": "2026-06-25 08:15:00",
"durationMin": 15,
"triggerON": "schedule 或其他"
}
```
**服务端处理**:
- `triggerON = "schedule"` → 排程触发,调用 `confirmScheduleLog`
- 其他 → 手动触发,调用 `insertByBo` 创建新记录
---
### 5.4 排程浇水完成 — `/{identity}/publish/finish/schedule`
```json
{
"deviceNo": "01",
"commandId": "对应的命令ID",
"startTime": "2026-06-25 08:00:00",
"endTime": "2026-06-25 08:15:00",
"durationMin": 15,
"triggerON": "mqtt on 或其他"
}
```
**服务端处理**: 调用 `confirmScheduleLog` 记录排程浇水日志。
`triggerON = "mqtt on"` 时标记为手动触发类型。
---
### 5.5 设备异常告警 — `/{identity}/publish/error`
```json
{
"errorCode": "E001",
"message": "水泵故障"
}
```
**服务端处理**: 当前仅日志记录,未做告警推送。
---
### 5.6 命令 ACK — `/{identity}/publish/ack`
```json
{
"commandId": "对应的命令ID",
"status": "1",
"message": "执行成功"
}
```
**服务端处理**:
1. 从 Redis 移除 pending 命令
2. 缓存 ACK 结果
3. 刷新设备在线状态
---
## 6. 命令可靠性机制
### 6.1 命令生命周期
```
构造命令 → 存入 Redis(pending) → 发布到 MQTT → 等待 ACK
↓ ↓
定时扫描 收到 ACK
↓ ↓
超时未确认? 从 pending 移除
↓ 存入 Redis(ack)
重试(最多 3 次)
达到上限? → 放弃并记录日志
```
### 6.2 重试策略
| 配置项 | 默认值 | 说明 |
|--------|--------|------|
| `maxRetryCount` | 3 | 最大重试次数 |
| `retryIntervalMs` | 5000 | 重试间隔ms |
| `scanIntervalMs` | 5000 | 定时扫描间隔ms |
| `pendingTtlSeconds` | 86400 | pending 命令 TTL |
| `ackTtlSeconds` | 86400 | ACK 结果缓存 TTL |
### 6.3 离线处理
- 重试前检查设备在线状态Redis 缓存)
- 设备离线时不执行 MQTT 发布,仅递增重试计数
- 达到最大重试次数后自动放弃
### 6.4 Redis 键规则
| Key 模式 | 说明 |
|---------|------|
| `mqtt:command:pending:{commandId}` | 待确认命令 |
| `mqtt:command:ack:{commandId}` | ACK 确认结果 |
| `mqtt:command:pending:ids` | 待确认命令 ID 集合Set |
| `lock:mqtt:command:retry:{commandId}` | 命令操作分布式锁 |
| `mqtt:device:status:{deviceNo}` | 设备在线状态缓存 |
| `lock:mqtt:device:status:{deviceNo}` | 设备状态写入锁 |
---
## 7. 接口 → MQTT 命令映射表
| 接口 | 路由 | MQTT 命令类型 | 备注 |
|------|------|--------------|------|
| 绑定设备 | `POST /addDevice` | `bindDevice` | Service 层下发 |
| 解绑设备 | `DELETE /deleteDevice/{deviceNos}` | `initDevice` | Service 层下发(每台设备) |
| 开关设备 | `PUT /switchDevice` | `switchDevice` | Service 层下发 + 浇水日志 |
| 绑定排程设备 | `POST /addScheduleDevice` | `bindSchedule` | Controller 层下发 |
| 解绑排程设备 | `DELETE /deleteScheduleDevice` | `unbindSchedule` | Controller 层下发 |
| 修改排程状态 | `PUT /editScheduleStatus` | `bindSchedule` | 向所有绑定设备重新下发 |
| 修改排程内容 | `PUT /updataschedule` | `bindSchedule` | 向所有绑定设备重新下发 |
| 删除排程 | `DELETE /deleteschedule/{ids}` | `unbindSchedule` | 删除前通知所有绑定设备 |
| 设备注册(自动) | — | `registerDeviceNo` | 设备上线后自动回复 |
---
## 8. 配置参考
```yaml
mqtt:
enabled: true
broker-url: ssl://your-broker:8883
client-id: water-server-01
username: server
password: xxxxxx
qos: 1
keep-alive: 60
connection-timeout: 30
max-inflight: 1000
clean-session: false
automatic-reconnect: true
tls:
enabled: true
skip-verify: false
topics:
subscribe:
- "+/publish/#"
publish-prefix: "" # 为空时 Topic = /{deviceNo}/subscriber/cmd
async:
core-pool-size: 8
max-pool-size: 32
consumer-count: 16
queue-capacity: 5000
batch-size: 100
offer-timeout-ms: 50
poll-timeout-ms: 100
command-ack:
enabled: true
max-retry-count: 3
retry-interval-ms: 5000
scan-interval-ms: 5000
pending-ttl-seconds: 86400
ack-ttl-seconds: 86400
pending-key-prefix: "mqtt:command:pending:"
ack-key-prefix: "mqtt:command:ack:"
pending-set-key: "mqtt:command:pending:ids"
retry-lock-key-prefix: "lock:mqtt:command:retry:"
retry-lock-ttl-ms: 30000
device-status-cache-prefix: "mqtt:device:status:"
device-status-cache-ttl-seconds: 300
```
---
## 9. 扩展指南
### 新增上行消息处理器
1. 实现 `MqttTopicHandler` 接口
2. 添加 `@Component` 注解
3. 定义 `topicPattern()` 返回匹配正则(必须包含一个捕获组提取设备标识)
4. 实现 `handle(deviceIdentity, payload)` 方法
```java
@Component
public class MyNewHandler implements MqttTopicHandler {
private static final Pattern PATTERN = Pattern.compile("^/([^/]+)/publish/mytype$");
@Override
public Pattern topicPattern() { return PATTERN; }
@Override
public void handle(String deviceIdentity, String payload) {
// 处理逻辑
}
}
```
> 无需修改 `MqttMessageDispatcher`,新 Handler 注册为 Bean 后自动发现。
### 新增下行命令类型
1.`IDeviceCommandService` 接口添加方法签名
2.`DeviceCommandServiceImpl` 实现命令构造与下发
3. 在 Controller 调用新方法
---
## 10. 设备在线状态检测
设备在线状态通过 Redis 缓存管理:
- **写入时机**: 设备注册、电量上报、ACK 确认时刷新
- **缓存格式**: `{ "deviceNo": "01", "status": "1", "lastReportTime": "2026-06-25T14:30:00Z" }`
- **TTL**: 默认 300 秒5 分钟)
- **离线判定**: 缓存过期 = 设备离线
- **并发保护**: 使用分布式锁(`lock:mqtt:device:status:{deviceNo}`)防止并发写入

View File

@@ -0,0 +1,267 @@
# Bind Schedule Device Dispatch Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** When the app binds a schedule to one or more devices, immediately publish that schedule's detail payload to each bound device.
**Architecture:** Keep the change inside the existing app module flow. `AppController.addScheduleDevice` remains the entry point, persists the relation as it does today, then reuses the existing `IDeviceCommandService.sendScheduleBindCommand(...)` path to publish a `bindSchedule` command with a small payload assembled from current schedule-detail data. Shared payload shaping should stay private to `AppController` unless implementation pressure proves otherwise.
**Tech Stack:** Java 17, Spring Boot 3, existing app controller/service layer, MQTT command publishing through `IDeviceCommandService`, Maven
## Global Constraints
- Only touch the schedule-device binding flow in `water-modules/water-app`
- Reuse existing `IDeviceCommandService.sendScheduleBindCommand(...)`
- Do not modify MQTT publisher, ACK handling, or topic routing
- Published payload must contain `deviceNo` and `details`
- `details` must follow the current device-facing schedule detail structure used by `buildScheduleBindPayload`
- Binding uses synchronous failure semantics: command publish failure must fail the API call
- Keep changes ASCII unless the target file already uses non-ASCII
---
### Task 1: Add a focused regression test for schedule-device bind dispatch
**Files:**
- Create: `water-modules/water-app/src/test/java/org/dromara/app/controller/AppControllerTest.java`
- Modify: `water-modules/water-app/pom.xml`
**Interfaces:**
- Consumes: `AppController.addScheduleDevice(String body)`
- Produces: a regression test proving that binding a device triggers `deviceCommandService.sendScheduleBindCommand(deviceNo, payload)`
- [ ] **Step 1: Add the test dependency baseline for the app module**
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
```
- [ ] **Step 2: Write the failing controller regression test**
```java
package org.dromara.app.controller;
import org.dromara.app.domain.bo.AppSchedulingDeviceBo;
import org.dromara.app.domain.vo.AppDeviceVo;
import org.dromara.app.domain.vo.AppScheduleDetailVo;
import org.dromara.app.domain.vo.AppScheduleVo;
import org.dromara.app.service.IAppDeviceService;
import org.dromara.app.service.IAppScheduleDetailService;
import org.dromara.app.service.IAppScheduleService;
import org.dromara.app.service.IAppSchedulingDeviceService;
import org.dromara.app.service.IAppWateringLogService;
import org.dromara.app.service.IDeviceCommandService;
import org.dromara.common.core.domain.R;
import org.dromara.system.service.ISysUserService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
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.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
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;
@InjectMocks
private AppController controller;
@Test
void addScheduleDevice_dispatchesSchedulePayloadAfterBinding() {
AppScheduleVo schedule = new AppScheduleVo();
schedule.setId(10L);
schedule.setUserId(99L);
schedule.setName("Morning");
schedule.setStatus("1");
AppDeviceVo device = new AppDeviceVo();
device.setDeviceNo("D01");
device.setUserId(99L);
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);
when(appScheduleDetailService.queryByScheduleIdByStatus(10L)).thenReturn(List.of(detail));
when(appSchedulingDeviceService.insertByBo(any(AppSchedulingDeviceBo.class))).thenReturn(true);
when(deviceCommandService.sendScheduleBindCommand(eq("D01"), anyMap())).thenReturn("cmd-1");
R<Void> result = controller.addScheduleDevice("{\"scheduleId\":10,\"deviceNos\":[\"D01\"]}");
assertThat(result.getCode()).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");
}
}
```
- [ ] **Step 3: Run the test to verify it fails for the expected reason**
Run: `mvn -pl water-modules/water-app -DskipTests=false -Dtest=AppControllerTest test`
Expected: FAIL because `sendScheduleBindCommand(...)` is never invoked and payload assertions cannot be satisfied yet
- [ ] **Step 4: Commit the failing test baseline**
```bash
git add water-modules/water-app/pom.xml water-modules/water-app/src/test/java/org/dromara/app/controller/AppControllerTest.java
git commit -m "test: cover schedule bind device dispatch"
```
### Task 2: Implement schedule payload assembly and dispatch in AppController
**Files:**
- Modify: `water-modules/water-app/src/main/java/org/dromara/app/controller/AppController.java`
- Test: `water-modules/water-app/src/test/java/org/dromara/app/controller/AppControllerTest.java`
**Interfaces:**
- Consumes: `IAppScheduleService.queryById(Long)`, `IAppScheduleDetailService.queryByScheduleIdByStatus(Long)`, `IDeviceCommandService.sendScheduleBindCommand(String, Map<String, Object>)`
- Produces: `addScheduleDevice(...)` publishes a `bindSchedule` command after each successful relation insert
- [ ] **Step 1: Implement the minimum controller change to make the test pass**
```java
for (String deviceNo : deviceNos) {
if (StringUtils.isBlank(deviceNo)) {
continue;
}
assertDeviceOwned(deviceNo);
AppSchedulingDeviceBo schedulingDeviceBo = new AppSchedulingDeviceBo();
schedulingDeviceBo.setDeviceNo(deviceNo);
schedulingDeviceBo.setScheduleId(scheduleId);
appSchedulingDeviceService.insertByBo(schedulingDeviceBo);
deviceCommandService.sendScheduleBindCommand(deviceNo, buildScheduleBindPayload(scheduleId, deviceNo));
}
```
```java
private Map<String, Object> buildScheduleBindPayload(Long scheduleId, String deviceNo) {
List<AppScheduleDetailVo> details = appScheduleDetailService.queryByScheduleIdByStatus(scheduleId);
List<Map<String, Object>> detailPayload = new ArrayList<>();
for (AppScheduleDetailVo detail : details) {
List<Object> timeSlots = new ArrayList<>();
JSONArray timeArray = JSONUtil.parseArray(detail.getTimeData());
for (Object timeSlot : timeArray) {
timeSlots.add(timeSlot);
}
Map<String, Object> item = new HashMap<>();
item.put("weekday", detail.getWeekday());
item.put("timeData", timeSlots);
item.put("triggerType", detail.getTriggerType());
item.put("status", detail.getStatus());
detailPayload.add(item);
}
Map<String, Object> payload = new HashMap<>();
payload.put("deviceNo", deviceNo);
payload.put("details", detailPayload);
return payload;
}
```
- [ ] **Step 2: Run the focused regression test to verify it passes**
Run: `mvn -pl water-modules/water-app -DskipTests=false -Dtest=AppControllerTest test`
Expected: PASS with `AppControllerTest` green
- [ ] **Step 3: Refactor only if needed to remove duplication inside schedule bind payload shaping**
```java
private List<Map<String, Object>> toScheduleDetailPayload(List<AppScheduleDetailVo> details) {
List<Map<String, Object>> detailPayload = new ArrayList<>();
for (AppScheduleDetailVo detail : details) {
List<Object> timeSlots = new ArrayList<>();
JSONArray timeArray = JSONUtil.parseArray(detail.getTimeData());
for (Object timeSlot : timeArray) {
timeSlots.add(timeSlot);
}
Map<String, Object> item = new HashMap<>();
item.put("weekday", detail.getWeekday());
item.put("timeData", timeSlots);
item.put("triggerType", detail.getTriggerType());
item.put("status", detail.getStatus());
detailPayload.add(item);
}
return detailPayload;
}
```
- [ ] **Step 4: Re-run the focused regression test after refactor**
Run: `mvn -pl water-modules/water-app -DskipTests=false -Dtest=AppControllerTest test`
Expected: PASS
- [ ] **Step 5: Commit the implementation**
```bash
git add water-modules/water-app/src/main/java/org/dromara/app/controller/AppController.java water-modules/water-app/src/test/java/org/dromara/app/controller/AppControllerTest.java
git commit -m "feat: dispatch schedule payload when binding device"
```
### Task 3: Run module-level verification and review edge behavior
**Files:**
- Modify: none required unless verification reveals defects
**Interfaces:**
- Consumes: completed controller change and regression test
- Produces: fresh verification evidence for the implementation claim
- [ ] **Step 1: Run the focused controller regression test**
Run: `mvn -pl water-modules/water-app -DskipTests=false -Dtest=AppControllerTest test`
Expected: PASS
- [ ] **Step 2: Run a compile pass for the app module with tests skipped**
Run: `mvn -pl water-modules/water-app -DskipTests compile`
Expected: BUILD SUCCESS
- [ ] **Step 3: Inspect the diff to confirm scope stayed local**
Run: `git diff --stat`
Expected: only the app controller, app module test baseline, the new controller test, and planning/spec docs changed for this task
- [ ] **Step 4: Commit any verification-driven follow-up if needed**
```bash
git add -A
git commit -m "chore: verify schedule bind dispatch change"
```

View File

@@ -0,0 +1,73 @@
# App Version Check Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add an app-facing version check endpoint so the mobile app can compare its current version with the latest enabled app version record and prompt updates when they differ.
**Architecture:** Store version records in the new `app_version` table. `AppController` validates the request, asks `IAppVersionService` for the latest enabled record by platform, and returns whether an update is available.
**Tech Stack:** Spring Boot MVC, existing `R<T>` response wrapper, MyBatis Plus `BaseMapperPlus`, JUnit 5, Mockito, AssertJ.
## Global Constraints
- Keep the endpoint under `/app/v1`.
- Use exact version equality: `currentVersion` differs from configured `latestVersion` means update is available.
- Store version data in `app_version`; do not use `sys_config` for this feature.
- Do not change unrelated schedule, MQTT, auth, or OSS upload behavior.
---
### Task 1: Version Check Contract
**Files:**
- Modify: `water-modules/water-app/src/test/java/org/dromara/app/controller/AppControllerTest.java`
- Create: `water-modules/water-app/src/main/java/org/dromara/app/domain/AppVersion.java`
- Create: `water-modules/water-app/src/main/java/org/dromara/app/domain/vo/AppVersionVo.java`
- Create: `water-modules/water-app/src/main/java/org/dromara/app/mapper/AppVersionMapper.java`
- Create: `water-modules/water-app/src/main/java/org/dromara/app/service/IAppVersionService.java`
- Create: `water-modules/water-app/src/main/java/org/dromara/app/service/impl/AppVersionServiceImpl.java`
- Modify: `water-modules/water-app/src/main/java/org/dromara/app/controller/AppController.java`
- Create: `script/sql/update/add_app_version.sql`
**Interfaces:**
- Consumes: `IAppVersionService.queryLatestByPlatform(String platform)`
- Produces: `AppController.checkVersion(String platform, String currentVersion): R<AppVersionVo>`
- Produces: `AppVersionVo` fields `platform`, `currentVersion`, `latestVersion`, `versionCode`, `updateAvailable`, `forceUpdate`, `downloadUrl`, `releaseNotes`
- [ ] **Step 1: Write failing tests**
Add `IAppVersionService` as a mocked dependency and add tests for update available, no update, unsupported platform, missing current version, and missing version record.
- [ ] **Step 2: Run tests and verify RED**
Run:
```bash
mvn -pl water-modules/water-app -am "-DskipTests=false" "-Dmaven.test.skip=false" "-Dtest=AppControllerTest#checkVersion*" "-Dsurefire.failIfNoSpecifiedTests=false" test
```
Expected: compilation or test failure because `IAppVersionService` and table-backed implementation do not exist yet.
- [ ] **Step 3: Implement minimal production code**
Create `AppVersion`, `AppVersionVo`, `AppVersionMapper`, `IAppVersionService`, `AppVersionServiceImpl`, inject `IAppVersionService` into `AppController`, and keep `GET /checkVersion`.
- [ ] **Step 4: Run targeted tests and verify GREEN**
Run:
```bash
mvn -pl water-modules/water-app -am "-DskipTests=false" "-Dmaven.test.skip=false" "-Dtest=AppControllerTest#checkVersion*" "-Dsurefire.failIfNoSpecifiedTests=false" test
```
Expected: targeted version check tests pass.
- [ ] **Step 5: Run compile/package verification**
Run:
```bash
mvn -pl water-modules/water-app -am "-DskipTests" package
```
Expected: module and dependencies compile/package successfully.

View File

@@ -0,0 +1,134 @@
# Device Status LWT MAC Resolution Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Verify and document that `/MAC/publish/status` last-will messages resolve the MAC address to `deviceNo` before updating device status.
**Architecture:** Keep `DeviceStatusHandler` focused on status parsing and delegate Topic identity resolution to the existing `DeviceIdentityResolver`. Add a focused integration-style unit test using the real resolver and a mocked mapper so the complete MAC-to-device-number path is covered without duplicating database access in the handler.
**Tech Stack:** Java 17, Spring Boot, JUnit 5, Mockito, AssertJ, MyBatis-Plus
## Global Constraints
- Only `/MAC/publish/status` may use a MAC address for this change.
- Other MQTT communication continues to use `deviceNo`.
- A missing MAC mapping must not update device status.
- Preserve all existing uncommitted workspace changes.
---
### Task 1: Cover MAC Last-Will Resolution
**Files:**
- Modify: `water-modules/water-app/src/test/java/org/dromara/app/handler/DeviceStatusHandlerTest.java`
**Interfaces:**
- Consumes: `DeviceIdentityResolver(AppDeviceMapper)` and `DeviceStatusHandler.handle(String, String, boolean)`
- Produces: Regression coverage proving a Topic MAC is converted to `AppDevice.deviceNo`
- [ ] **Step 1: Add the mapper mock and MAC last-will test**
Add imports and a mapper mock:
```java
import org.dromara.app.domain.AppDevice;
import org.dromara.app.mapper.AppDeviceMapper;
@Mock
private AppDeviceMapper appDeviceMapper;
```
Add this test:
```java
@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 状态离线");
}
```
Add the missing-device guard test:
```java
@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());
}
```
- [ ] **Step 2: Run the focused test**
Run:
```powershell
mvn -pl water-modules/water-app -am "-DskipTests=false" "-Dmaven.test.skip=false" "-Dprofiles.active=dev" "-Dtest=DeviceStatusHandlerTest#handleResolvesLastWillTopicMacToDeviceNo+handleDoesNotUpdateStatusWhenLastWillMacIsUnknown" "-Dsurefire.failIfNoSpecifiedTests=false" test
```
Expected: both tests PASS. The requested production path already exists in `DeviceIdentityResolver`; these characterization tests make that behavior explicit and prevent regression.
### Task 2: Clarify Device Status Topic Identity
**Files:**
- Modify: `water-modules/water-app/src/main/java/org/dromara/app/handler/DeviceStatusHandler.java:15-19`
**Interfaces:**
- Consumes: Existing `DeviceIdentityResolver.resolveDeviceNo(String)` behavior
- Produces: Javadoc that accurately documents device-number and MAC Topic identities
- [ ] **Step 1: Update handler Javadoc**
Replace the class description with:
```java
/**
* 设备在线/离线状态处理器,匹配 /{deviceIdentity}/publish/status。
* <p>
* deviceIdentity 支持设备编号;设备遗嘱消息允许使用 MAC 地址,处理前统一解析为设备编号。
* 设备通过 status=online 标记上线,通过 LWT status=offline 标记异常离线。
*/
```
- [ ] **Step 2: Run all handler tests**
Run:
```powershell
mvn -pl water-modules/water-app -am "-DskipTests=false" "-Dmaven.test.skip=false" "-Dprofiles.active=dev" "-Dtest=DeviceStatusHandlerTest" "-Dsurefire.failIfNoSpecifiedTests=false" test
```
Expected: all `DeviceStatusHandlerTest` tests PASS with zero failures and errors.
- [ ] **Step 3: Check the final diff**
Run:
```powershell
git diff --check -- water-modules/water-app/src/main/java/org/dromara/app/handler/DeviceStatusHandler.java water-modules/water-app/src/test/java/org/dromara/app/handler/DeviceStatusHandlerTest.java
```
Expected: exit code 0 and no whitespace errors.
- [ ] **Step 4: Leave implementation changes uncommitted for review**
Both implementation files already contain user changes. Do not create a commit that would mix those changes with this task.

View File

@@ -0,0 +1,59 @@
# 绑定排程时向设备下发排程信息设计
## 背景
当前 `AppController.addScheduleDevice` 只负责建立排程与设备的关联关系,不会把排程详情同步下发给设备。这样会导致设备绑定成功后仍然缺少最新排程配置。
## 目标
在 APP 端绑定排程与设备成功时,服务端同步向对应设备下发该排程详情信息,确保设备立即拿到当前排程配置。
## 设计
### 入口与改动范围
- 入口保持在 `water-modules/water-app/src/main/java/org/dromara/app/controller/AppController.java``addScheduleDevice`
- 复用现有 `IDeviceCommandService.sendScheduleBindCommand(...)`
- 不修改现有 MQTT 发布器、ACK 处理器和设备主题路由
### 下发时机
对请求中的每个 `deviceNo`
1. 校验设备归属
2. 写入排程设备关联
3. 读取当前排程详情
4. 同步下发排程命令
### 命令协议
- `commandType`: `bindSchedule`
- `payload.deviceNo`: 当前设备编号
- `payload.details`: 当前排程详情列表
`payload.details` 每项沿用当前 APP 查询排程详情时对外返回的结构,包含:
- `weekday`
- `timeData`
- `triggerType`
- `status`
如果排程详情里存在 `zones` 字段且当前查询对象可直接取到,则一并下发;否则不额外改造现有排程详情出参结构。
### 失败策略
绑定接口采用同步失败策略:
- 只要某台设备的排程命令下发失败,接口直接返回失败
- 不吞掉下发异常
- 前端可以明确感知“排程绑定/同步下发”未完全成功
本次不额外引入补偿、重试编排或异步任务。
## 测试与验证
- 优先补最小范围的自动化测试;如果模块当前没有现成测试基线,则至少执行模块编译或定向测试命令做回归验证
- 手工验证重点:
- 绑定排程后关联表仍正常写入
- MQTT 下发 payload 包含 `deviceNo``details`
- 设备未登记 MAC 或命令下发异常时,接口返回失败