浇水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,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 或命令下发异常时,接口返回失败