diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/README.md b/docs/9.9.1/safety-command-mock-2026-10-30/README.md new file mode 100644 index 0000000..f3fe02e --- /dev/null +++ b/docs/9.9.1/safety-command-mock-2026-10-30/README.md @@ -0,0 +1,61 @@ +# 拍摄任务底部安全控制:本地模拟调试 + +日期:2026-10-30。全部请求与回执来自纯内存 Mock,**未访问后端、未向无人机发送指令**,不代表后端受理或设备执行成功。 + +## 接口合同 + +朱工提供 `POST /api/app/airport/command`,只发送同一订单飞行任务的 `id` 和指令码: + +| 按钮 | command | +| --- | --- | +| 紧急暂停 | `flighttask_pause` | +| 继续拍摄 | `flighttask_recovery` | +| 立即返航 | `return_home` | +| 取消返航 | `return_home_cancel` | + +不传 `plane_id`、`airport_sn`,也不编造 `dry_run` 参数。响应解析 `order_flight_task_id`、`command`、`airport_sn`、任意 JSON 类型的 `dji_status` 和非实时 `metrics`;回显任务及指令必须与请求一致。 + +成功后只查询同一任务 `shooting` 一次,不轮询;受理回执不直接代替设备状态。底部两列分别展示暂停/继续、返航/取消返航,位置固定。 + +## 模拟入口与场景 + +- Debug 启动参数 `--dock-command-mock`:直接进入合成任务 `901` 的模拟拍摄中。 +- `--dock-command-result=success`(默认)、`business-failure`、`timeout` 分别验证成功、明确拒绝与结果未知。 +- 原有准备页“本地模拟”及 `--dock-preparation-mock`、`--dock-start-shoot-mock` 也接入同一内存指令服务;不携带真实订单或设备身份。 +- 右上角文档图标展示当前模拟会话的完整请求、响应及错误,含 `source=local_mock`、`network_sent=false`。 + +真实入口仍未注入指令服务,按钮禁用。Debug 统一网络层的禁飞拦截未改动;普通传输即使实例化指令 API,也会在发送前被拦截。模拟传输仅接受 `https://mock.invalid` 的已知请求,未知请求本地失败,无网络回退能力。 + +## 交互与状态边界 + +- 必须存在有效任务、锁定飞机及明确的 `ui.commands` 白名单指令;缺失或未知指令不开放按钮。不用开拍门禁推导暂停/返航权限。 +- 连点只提交一次;开拍、指令和刷新互斥,等待时保留旧阶段与六项读数。 +- 明确业务拒绝可由用户再次点击重试;超时、错误回执或发送后取消会锁定控制操作,只允许读取状态,不自动重试。 +- 回查仍为旧数据时,所有已受理且仍出现在旧列表的指令分别保持防重锁,不能通过暂停/返航交替点击绕过。 +- 立即返航先弹确认。本地状态按文档模拟任务中断;取消返航后任务仍中断,不恢复任务、自动开拍或新建任务。该模拟状态是测试场景,不是后端当前行为的实测证据。 +- 离页、后台和身份变化会使迟到响应失效。 + +## 验证 + +首轮模拟器相关测试 99 项全部通过,覆盖 API、ViewModel、UI、既有开拍/准备流程和禁飞保护。防重复边界修正后,18 项指令 ViewModel 测试与 1 项暂停/恢复 UI 测试再次全部通过;累计 100 项不同测试通过。构建通过,`git diff --check` 通过。 + +- 首轮结果包:`test_sim_2026-10-30T02-17-48-735Z_pid48214_75e97ac8.xcresult`。 +- 最终结果包:`test_sim_2026-10-30T02-20-02-298Z_pid48214_c1e1a9c1.xcresult`。 +- 手动操作:在 iPhone 18 Pro / iOS 27 模拟器依次点击暂停、继续、返航并确认、取消返航;共 9 次本地交换(首次 GET + 4 组 POST/GET),全程任务 `901`。 +- [完整成功流程请求与回执](success-flow.mock.json):从本次实际模拟器操作日志提取,四个指令均有模拟 `code=100000` 回执。 +- [明确拒绝及再次点击记录](business-failure.mock.json)、[超时及只读刷新记录](timeout.mock.json):来自隔离 UI 测试附件。 +- 暂停后按钮变为继续;返航后只开放取消返航;取消后保持任务中断且控制按钮禁用。 + +## 模拟器截图 + +暂停后: + +![暂停成功(纯本地模拟)](paused-mock.png) + +返航中断任务后: + +![取消返航入口(纯本地模拟)](returning-mock.png) + +[取消返航后的中断状态](return-cancelled-mock.png) · [返航确认弹窗](return-confirmation-mock.png) · [超时结果待核对](timeout-mock.png) + +后续真实联调仍需在用户解除禁飞限制后进行,并核对后端不同阶段的 `ui.commands`、返航中断与取消返航的实际响应。本次不验证真实网络、设备飞行或素材产生。 diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/business-failure.mock.json b/docs/9.9.1/safety-command-mock-2026-10-30/business-failure.mock.json new file mode 100644 index 0000000..c3691fd --- /dev/null +++ b/docs/9.9.1/safety-command-mock-2026-10-30/business-failure.mock.json @@ -0,0 +1,154 @@ +{ + "command_scenario" : "business-failure", + "description" : "纯内存模拟,未调用后端或设备", + "network_sent" : false, + "records" : [ + { + "http_status" : 200, + "method" : "GET", + "path" : "/api/app/airport/shooting", + "query" : "id=901&live_battery=1", + "response_body" : { + "code" : 100000, + "data" : { + "air_line" : { + "id" : 401, + "name" : "模拟航线", + "scenic_spot_id" : 301 + }, + "current_plane" : { + "id" : 201, + "online_status" : 1, + "sn_number" : "LOCAL-MOCK-PLANE-201", + "status_text" : "本地模拟 · 拍摄中 · 电量95%", + "work_status" : 2, + "work_status_label" : "拍摄中" + }, + "execute_gate" : { + "can_execute" : false, + "code" : "already_started", + "message" : "本地模拟:开拍已受理", + "primary_action" : "shooting", + "primary_action_label" : "拍摄中" + }, + "header" : { + "order_number" : "LOCAL-MOCK-ORDER-901", + "package_name" : "模拟套餐 · 含5次拍摄", + "title" : "模拟点位 · 模拟航线", + "tourist_label" : "本地模拟,无设备指令" + }, + "metrics" : [ + { + "key" : "battery", + "value" : "95%" + }, + { + "key" : "env_temp", + "value" : "20.3℃" + }, + { + "key" : "wind_speed", + "value" : "0m/s" + }, + { + "key" : "rainfall", + "value" : "无雨" + }, + { + "key" : "signal", + "value" : "良好" + }, + { + "key" : "satellite", + "value" : "36颗" + } + ], + "order_flight_task" : { + "id" : 901, + "order_number" : "LOCAL-MOCK-ORDER-901", + "scenic_id" : 128, + "status" : 20, + "status_label" : "执行中(模拟)", + "wayline_status" : 20, + "wayline_status_label" : "执行中(模拟)" + }, + "order_number" : "LOCAL-MOCK-ORDER-901", + "plane_status" : { + "connected" : true, + "poll_hint_ms" : 5000, + "scenic_id" : 128 + }, + "scenic" : { + "id" : 128, + "name" : "本地模拟景区" + }, + "scenic_spot" : { + "id" : 301, + "name" : "模拟点位" + }, + "task" : { + "id" : 901, + "order_number" : "LOCAL-MOCK-ORDER-901", + "scenic_id" : 128, + "status" : 20, + "status_label" : "执行中(模拟)", + "wayline_status" : 20, + "wayline_status_label" : "执行中(模拟)" + }, + "ui" : { + "commands" : [ + { + "command" : "flighttask_pause", + "label" : "紧急暂停", + "sub" : "悬停待命" + }, + { + "command" : "return_home", + "label" : "立即返航", + "sub" : "中断任务" + } + ], + "message" : "本地模拟状态回查,未向设备发送指令。", + "phase" : "shooting", + "title" : "无人机正在拍摄中(模拟)" + } + }, + "msg" : "local mock success" + } + }, + { + "http_status" : 200, + "method" : "POST", + "path" : "/api/app/airport/command", + "request_body" : { + "command" : "flighttask_pause", + "id" : 901 + }, + "response_body" : { + "code" : 100099, + "data" : { + + }, + "msg" : "本地模拟:指令被拒绝,未改变任务状态" + } + }, + { + "http_status" : 200, + "method" : "POST", + "path" : "/api/app/airport/command", + "request_body" : { + "command" : "flighttask_pause", + "id" : 901 + }, + "response_body" : { + "code" : 100099, + "data" : { + + }, + "msg" : "本地模拟:指令被拒绝,未改变任务状态" + } + } + ], + "scenario" : "success", + "source" : "local_mock" +} \ No newline at end of file diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/paused-mock.png b/docs/9.9.1/safety-command-mock-2026-10-30/paused-mock.png new file mode 100644 index 0000000..cb2dea3 Binary files /dev/null and b/docs/9.9.1/safety-command-mock-2026-10-30/paused-mock.png differ diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/return-cancelled-mock.png b/docs/9.9.1/safety-command-mock-2026-10-30/return-cancelled-mock.png new file mode 100644 index 0000000..584a6e5 Binary files /dev/null and b/docs/9.9.1/safety-command-mock-2026-10-30/return-cancelled-mock.png differ diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/return-confirmation-mock.png b/docs/9.9.1/safety-command-mock-2026-10-30/return-confirmation-mock.png new file mode 100644 index 0000000..e92a2d6 Binary files /dev/null and b/docs/9.9.1/safety-command-mock-2026-10-30/return-confirmation-mock.png differ diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/returning-mock.png b/docs/9.9.1/safety-command-mock-2026-10-30/returning-mock.png new file mode 100644 index 0000000..990f753 Binary files /dev/null and b/docs/9.9.1/safety-command-mock-2026-10-30/returning-mock.png differ diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/success-flow.mock.json b/docs/9.9.1/safety-command-mock-2026-10-30/success-flow.mock.json new file mode 100644 index 0000000..b2ef43f --- /dev/null +++ b/docs/9.9.1/safety-command-mock-2026-10-30/success-flow.mock.json @@ -0,0 +1,745 @@ +{ + "source": "local_mock", + "description": "模拟器实际点击,纯内存处理,未调用后端或设备", + "network_sent": false, + "task_id": 901, + "records": [ + { + "method": "GET", + "path": "/api/app/airport/shooting", + "query": "id=901&live_battery=1", + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "air_line": { + "id": 401, + "name": "模拟航线", + "scenic_spot_id": 301 + }, + "current_plane": { + "id": 201, + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "本地模拟 · 拍摄中 · 电量95%", + "work_status": 2, + "work_status_label": "拍摄中" + }, + "execute_gate": { + "can_execute": false, + "code": "already_started", + "message": "本地模拟:开拍已受理", + "primary_action": "shooting", + "primary_action_label": "拍摄中" + }, + "header": { + "order_number": "LOCAL-MOCK-ORDER-901", + "package_name": "模拟套餐 · 含5次拍摄", + "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令" + }, + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_number": "LOCAL-MOCK-ORDER-901", + "plane_status": { + "connected": true, + "poll_hint_ms": 5000, + "scenic_id": 128 + }, + "scenic": { + "id": 128, + "name": "本地模拟景区" + }, + "scenic_spot": { + "id": 301, + "name": "模拟点位" + }, + "task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "ui": { + "commands": [ + { + "command": "flighttask_pause", + "label": "紧急暂停", + "sub": "悬停待命" + }, + { + "command": "return_home", + "label": "立即返航", + "sub": "中断任务" + } + ], + "message": "本地模拟状态回查,未向设备发送指令。", + "phase": "shooting", + "title": "无人机正在拍摄中(模拟)" + } + }, + "msg": "local mock success" + } + }, + { + "method": "POST", + "path": "/api/app/airport/command", + "request_body": { + "id": 901, + "command": "flighttask_pause" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "airport_sn": "LOCAL-MOCK-DOCK-201", + "command": "flighttask_pause", + "dji_status": "paused", + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task_id": 901 + }, + "msg": "local mock success" + } + }, + { + "method": "GET", + "path": "/api/app/airport/shooting", + "query": "id=901&live_battery=1", + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "air_line": { + "id": 401, + "name": "模拟航线", + "scenic_spot_id": 301 + }, + "current_plane": { + "id": 201, + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "本地模拟 · 悬停中 · 电量95%", + "work_status": 2, + "work_status_label": "悬停中" + }, + "execute_gate": { + "can_execute": false, + "code": "already_started", + "message": "本地模拟:开拍已受理", + "primary_action": "paused", + "primary_action_label": "拍摄中" + }, + "header": { + "order_number": "LOCAL-MOCK-ORDER-901", + "package_name": "模拟套餐 · 含5次拍摄", + "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令" + }, + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_number": "LOCAL-MOCK-ORDER-901", + "plane_status": { + "connected": true, + "poll_hint_ms": 5000, + "scenic_id": 128 + }, + "scenic": { + "id": 128, + "name": "本地模拟景区" + }, + "scenic_spot": { + "id": 301, + "name": "模拟点位" + }, + "task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "ui": { + "commands": [ + { + "command": "flighttask_recovery", + "label": "继续拍摄", + "sub": "恢复航线" + }, + { + "command": "return_home", + "label": "立即返航", + "sub": "中断任务" + } + ], + "message": "本地模拟状态回查,未向设备发送指令。", + "phase": "paused", + "title": "拍摄已暂停(模拟)" + } + }, + "msg": "local mock success" + } + }, + { + "method": "POST", + "path": "/api/app/airport/command", + "request_body": { + "id": 901, + "command": "flighttask_recovery" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "airport_sn": "LOCAL-MOCK-DOCK-201", + "command": "flighttask_recovery", + "dji_status": "shooting", + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task_id": 901 + }, + "msg": "local mock success" + } + }, + { + "method": "GET", + "path": "/api/app/airport/shooting", + "query": "id=901&live_battery=1", + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "air_line": { + "id": 401, + "name": "模拟航线", + "scenic_spot_id": 301 + }, + "current_plane": { + "id": 201, + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "本地模拟 · 拍摄中 · 电量95%", + "work_status": 2, + "work_status_label": "拍摄中" + }, + "execute_gate": { + "can_execute": false, + "code": "already_started", + "message": "本地模拟:开拍已受理", + "primary_action": "shooting", + "primary_action_label": "拍摄中" + }, + "header": { + "order_number": "LOCAL-MOCK-ORDER-901", + "package_name": "模拟套餐 · 含5次拍摄", + "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令" + }, + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "order_number": "LOCAL-MOCK-ORDER-901", + "plane_status": { + "connected": true, + "poll_hint_ms": 5000, + "scenic_id": 128 + }, + "scenic": { + "id": 128, + "name": "本地模拟景区" + }, + "scenic_spot": { + "id": 301, + "name": "模拟点位" + }, + "task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "scenic_id": 128, + "status": 20, + "status_label": "执行中(模拟)", + "wayline_status": 20, + "wayline_status_label": "执行中(模拟)" + }, + "ui": { + "commands": [ + { + "command": "flighttask_pause", + "label": "紧急暂停", + "sub": "悬停待命" + }, + { + "command": "return_home", + "label": "立即返航", + "sub": "中断任务" + } + ], + "message": "本地模拟状态回查,未向设备发送指令。", + "phase": "shooting", + "title": "无人机正在拍摄中(模拟)" + } + }, + "msg": "local mock success" + } + }, + { + "method": "POST", + "path": "/api/app/airport/command", + "request_body": { + "id": 901, + "command": "return_home" + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "airport_sn": "LOCAL-MOCK-DOCK-201", + "command": "return_home", + "dji_status": "returning", + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task_id": 901 + }, + "msg": "local mock success" + } + }, + { + "method": "GET", + "path": "/api/app/airport/shooting", + "query": "id=901&live_battery=1", + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "air_line": { + "id": 401, + "name": "模拟航线", + "scenic_spot_id": 301 + }, + "current_plane": { + "id": 201, + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "本地模拟 · 返航中 · 电量95%", + "work_status": 2, + "work_status_label": "返航中" + }, + "execute_gate": { + "can_execute": false, + "code": "return_home", + "message": "本地模拟:开拍已受理", + "primary_action": "returning", + "primary_action_label": "拍摄中" + }, + "header": { + "order_number": "LOCAL-MOCK-ORDER-901", + "package_name": "模拟套餐 · 含5次拍摄", + "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令" + }, + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "result_code": "return_home", + "result_message": "本地模拟:立即返航中断任务;无人机返航中。", + "scenic_id": 128, + "status": 40, + "status_label": "任务已中断(模拟)", + "wayline_status": 40, + "wayline_status_label": "已中断(模拟)" + }, + "order_number": "LOCAL-MOCK-ORDER-901", + "plane_status": { + "connected": true, + "poll_hint_ms": 5000, + "scenic_id": 128 + }, + "scenic": { + "id": 128, + "name": "本地模拟景区" + }, + "scenic_spot": { + "id": 301, + "name": "模拟点位" + }, + "task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "result_code": "return_home", + "result_message": "本地模拟:立即返航中断任务;无人机返航中。", + "scenic_id": 128, + "status": 40, + "status_label": "任务已中断(模拟)", + "wayline_status": 40, + "wayline_status_label": "已中断(模拟)" + }, + "ui": { + "commands": [ + { + "command": "return_home_cancel", + "label": "取消返航", + "sub": "不恢复已中断任务" + } + ], + "message": "本地模拟:立即返航中断任务;无人机返航中", + "phase": "returning", + "title": "本地模拟:立即返航中断任务;无人机返航中" + } + }, + "msg": "local mock success" + } + }, + { + "method": "POST", + "path": "/api/app/airport/command", + "request_body": { + "command": "return_home_cancel", + "id": 901 + }, + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "airport_sn": "LOCAL-MOCK-DOCK-201", + "command": "return_home_cancel", + "dji_status": "failed", + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task_id": 901 + }, + "msg": "local mock success" + } + }, + { + "method": "GET", + "path": "/api/app/airport/shooting", + "query": "id=901&live_battery=1", + "http_status": 200, + "response_body": { + "code": 100000, + "data": { + "air_line": { + "id": 401, + "name": "模拟航线", + "scenic_spot_id": 301 + }, + "current_plane": { + "id": 201, + "online_status": 1, + "sn_number": "LOCAL-MOCK-PLANE-201", + "status_text": "本地模拟 · 悬停中 · 电量95%", + "work_status": 2, + "work_status_label": "悬停中" + }, + "execute_gate": { + "can_execute": false, + "code": "return_home", + "message": "本地模拟:开拍已受理", + "primary_action": "failed", + "primary_action_label": "拍摄中" + }, + "header": { + "order_number": "LOCAL-MOCK-ORDER-901", + "package_name": "模拟套餐 · 含5次拍摄", + "title": "模拟点位 · 模拟航线", + "tourist_label": "本地模拟,无设备指令" + }, + "metrics": [ + { + "key": "battery", + "value": "95%" + }, + { + "key": "env_temp", + "value": "20.3℃" + }, + { + "key": "wind_speed", + "value": "0m/s" + }, + { + "key": "rainfall", + "value": "无雨" + }, + { + "key": "signal", + "value": "良好" + }, + { + "key": "satellite", + "value": "36颗" + } + ], + "order_flight_task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "result_code": "return_home", + "result_message": "本地模拟:返航已取消,任务仍已中断,不能继续拍摄。", + "scenic_id": 128, + "status": 40, + "status_label": "任务已中断(模拟)", + "wayline_status": 40, + "wayline_status_label": "已中断(模拟)" + }, + "order_number": "LOCAL-MOCK-ORDER-901", + "plane_status": { + "connected": true, + "poll_hint_ms": 5000, + "scenic_id": 128 + }, + "scenic": { + "id": 128, + "name": "本地模拟景区" + }, + "scenic_spot": { + "id": 301, + "name": "模拟点位" + }, + "task": { + "id": 901, + "order_number": "LOCAL-MOCK-ORDER-901", + "result_code": "return_home", + "result_message": "本地模拟:返航已取消,任务仍已中断,不能继续拍摄。", + "scenic_id": 128, + "status": 40, + "status_label": "任务已中断(模拟)", + "wayline_status": 40, + "wayline_status_label": "已中断(模拟)" + }, + "ui": { + "commands": [], + "message": "本地模拟:返航已取消,任务仍已中断", + "phase": "failed", + "title": "本地模拟:返航已取消,任务仍已中断" + } + }, + "msg": "local mock success" + } + } + ] +} diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/timeout-mock.png b/docs/9.9.1/safety-command-mock-2026-10-30/timeout-mock.png new file mode 100644 index 0000000..c10ead2 Binary files /dev/null and b/docs/9.9.1/safety-command-mock-2026-10-30/timeout-mock.png differ diff --git a/docs/9.9.1/safety-command-mock-2026-10-30/timeout.mock.json b/docs/9.9.1/safety-command-mock-2026-10-30/timeout.mock.json new file mode 100644 index 0000000..7001e2e --- /dev/null +++ b/docs/9.9.1/safety-command-mock-2026-10-30/timeout.mock.json @@ -0,0 +1,244 @@ +{ + "command_scenario" : "timeout", + "description" : "纯内存模拟,未调用后端或设备", + "network_sent" : false, + "records" : [ + { + "http_status" : 200, + "method" : "GET", + "path" : "/api/app/airport/shooting", + "query" : "id=901&live_battery=1", + "response_body" : { + "code" : 100000, + "data" : { + "air_line" : { + "id" : 401, + "name" : "模拟航线", + "scenic_spot_id" : 301 + }, + "current_plane" : { + "id" : 201, + "online_status" : 1, + "sn_number" : "LOCAL-MOCK-PLANE-201", + "status_text" : "本地模拟 · 拍摄中 · 电量95%", + "work_status" : 2, + "work_status_label" : "拍摄中" + }, + "execute_gate" : { + "can_execute" : false, + "code" : "already_started", + "message" : "本地模拟:开拍已受理", + "primary_action" : "shooting", + "primary_action_label" : "拍摄中" + }, + "header" : { + "order_number" : "LOCAL-MOCK-ORDER-901", + "package_name" : "模拟套餐 · 含5次拍摄", + "title" : "模拟点位 · 模拟航线", + "tourist_label" : "本地模拟,无设备指令" + }, + "metrics" : [ + { + "key" : "battery", + "value" : "95%" + }, + { + "key" : "env_temp", + "value" : "20.3℃" + }, + { + "key" : "wind_speed", + "value" : "0m/s" + }, + { + "key" : "rainfall", + "value" : "无雨" + }, + { + "key" : "signal", + "value" : "良好" + }, + { + "key" : "satellite", + "value" : "36颗" + } + ], + "order_flight_task" : { + "id" : 901, + "order_number" : "LOCAL-MOCK-ORDER-901", + "scenic_id" : 128, + "status" : 20, + "status_label" : "执行中(模拟)", + "wayline_status" : 20, + "wayline_status_label" : "执行中(模拟)" + }, + "order_number" : "LOCAL-MOCK-ORDER-901", + "plane_status" : { + "connected" : true, + "poll_hint_ms" : 5000, + "scenic_id" : 128 + }, + "scenic" : { + "id" : 128, + "name" : "本地模拟景区" + }, + "scenic_spot" : { + "id" : 301, + "name" : "模拟点位" + }, + "task" : { + "id" : 901, + "order_number" : "LOCAL-MOCK-ORDER-901", + "scenic_id" : 128, + "status" : 20, + "status_label" : "执行中(模拟)", + "wayline_status" : 20, + "wayline_status_label" : "执行中(模拟)" + }, + "ui" : { + "commands" : [ + { + "command" : "flighttask_pause", + "label" : "紧急暂停", + "sub" : "悬停待命" + }, + { + "command" : "return_home", + "label" : "立即返航", + "sub" : "中断任务" + } + ], + "message" : "本地模拟状态回查,未向设备发送指令。", + "phase" : "shooting", + "title" : "无人机正在拍摄中(模拟)" + } + }, + "msg" : "local mock success" + } + }, + { + "error" : "未能完成操作。(NSURLErrorDomain错误-1001。)", + "method" : "POST", + "path" : "/api/app/airport/command", + "request_body" : { + "command" : "flighttask_pause", + "id" : 901 + } + }, + { + "http_status" : 200, + "method" : "GET", + "path" : "/api/app/airport/shooting", + "query" : "id=901&live_battery=1", + "response_body" : { + "code" : 100000, + "data" : { + "air_line" : { + "id" : 401, + "name" : "模拟航线", + "scenic_spot_id" : 301 + }, + "current_plane" : { + "id" : 201, + "online_status" : 1, + "sn_number" : "LOCAL-MOCK-PLANE-201", + "status_text" : "本地模拟 · 拍摄中 · 电量95%", + "work_status" : 2, + "work_status_label" : "拍摄中" + }, + "execute_gate" : { + "can_execute" : false, + "code" : "already_started", + "message" : "本地模拟:开拍已受理", + "primary_action" : "shooting", + "primary_action_label" : "拍摄中" + }, + "header" : { + "order_number" : "LOCAL-MOCK-ORDER-901", + "package_name" : "模拟套餐 · 含5次拍摄", + "title" : "模拟点位 · 模拟航线", + "tourist_label" : "本地模拟,无设备指令" + }, + "metrics" : [ + { + "key" : "battery", + "value" : "95%" + }, + { + "key" : "env_temp", + "value" : "20.3℃" + }, + { + "key" : "wind_speed", + "value" : "0m/s" + }, + { + "key" : "rainfall", + "value" : "无雨" + }, + { + "key" : "signal", + "value" : "良好" + }, + { + "key" : "satellite", + "value" : "36颗" + } + ], + "order_flight_task" : { + "id" : 901, + "order_number" : "LOCAL-MOCK-ORDER-901", + "scenic_id" : 128, + "status" : 20, + "status_label" : "执行中(模拟)", + "wayline_status" : 20, + "wayline_status_label" : "执行中(模拟)" + }, + "order_number" : "LOCAL-MOCK-ORDER-901", + "plane_status" : { + "connected" : true, + "poll_hint_ms" : 5000, + "scenic_id" : 128 + }, + "scenic" : { + "id" : 128, + "name" : "本地模拟景区" + }, + "scenic_spot" : { + "id" : 301, + "name" : "模拟点位" + }, + "task" : { + "id" : 901, + "order_number" : "LOCAL-MOCK-ORDER-901", + "scenic_id" : 128, + "status" : 20, + "status_label" : "执行中(模拟)", + "wayline_status" : 20, + "wayline_status_label" : "执行中(模拟)" + }, + "ui" : { + "commands" : [ + { + "command" : "flighttask_pause", + "label" : "紧急暂停", + "sub" : "悬停待命" + }, + { + "command" : "return_home", + "label" : "立即返航", + "sub" : "中断任务" + } + ], + "message" : "本地模拟状态回查,未向设备发送指令。", + "phase" : "shooting", + "title" : "无人机正在拍摄中(模拟)" + } + }, + "msg" : "local mock success" + } + } + ], + "scenario" : "success", + "source" : "local_mock" +} \ No newline at end of file diff --git a/docs/9.9.1/start-shoot-mock-2026-10-29/README.md b/docs/9.9.1/start-shoot-mock-2026-10-29/README.md index ef0f5cc..bff4b8e 100644 --- a/docs/9.9.1/start-shoot-mock-2026-10-29/README.md +++ b/docs/9.9.1/start-shoot-mock-2026-10-29/README.md @@ -37,4 +37,4 @@ Debug 启动参数 `--dock-start-shoot-mock`,可加 `--dock-start-shoot-result 此入口使用独立客户端 `https://mock.invalid` 和纯内存传输;未知请求直接本地失败,不回退网络。`live_battery=1` 仅用于验证 Mock 的查询合同,不触发实时采集;真实 Debug 查询强制改为 0。合成订单、飞机 ID、任务 UUID 和机巢序列号均不可作为真实业务参数。 -正式任务页未注入开拍服务,按钮仍禁用;统一网络层继续阻断真实 `tasks/create/shoot/start-shoot/command/live`。底部暂停和返航也未启用。后端目前没有约定不会下发设备指令的模拟协议,因此本次只验证客户端行为,不验证后端接收及实际执行。 +正式任务页未注入开拍服务,按钮仍禁用;统一网络层继续阻断真实 `tasks/create/shoot/start-shoot/command/live`。2026-10-30 已为同一纯内存流程增加底部安全指令,见[安全控制模拟记录](../safety-command-mock-2026-10-30/README.md),真实暂停和返航仍未启用。后端目前没有约定不会下发设备指令的模拟协议,因此本次只验证客户端行为,不验证后端接收及实际执行。 diff --git a/suixinkan/Features/DroneDock/API/DroneDockCommandAPI.swift b/suixinkan/Features/DroneDock/API/DroneDockCommandAPI.swift new file mode 100644 index 0000000..f7a9d87 --- /dev/null +++ b/suixinkan/Features/DroneDock/API/DroneDockCommandAPI.swift @@ -0,0 +1,40 @@ +import Foundation + +/// 基于既有订单飞行任务发送单次安全指令;禁飞期间仅向本地模拟页面注入。 +protocol DroneDockCommandSending: Sendable { + /// 提交任务 ID 和白名单指令,不创建任务、不选机,也不自动重试。 + @MainActor + func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse +} + +/// 朱工 command 合同适配,真实传输仍受统一 Debug 禁飞策略阻断。 +@MainActor +final class DroneDockCommandAPI: DroneDockCommandSending { + private let client: APIClient + + /// 注入统一客户端;模拟调试使用完全不转发网络的响应替身。 + init(client: APIClient) { self.client = client } + + /// 每次仅发送 id 和 command,回执必须对应同一任务及同一指令。 + func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { + try Task.checkCancellation() + guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请返回任务页确认") } + let response: DroneDockCommandResponse = try await client.send(APIRequest( + method: .post, path: "/api/app/airport/command", + body: CommandBody(taskID: taskID, command: command.rawValue) + )) + guard response.orderFlightTaskID == taskID, response.command == command.rawValue else { + throw APIError.decodeFailed("安全指令回执的任务或指令不一致,请核对原任务状态") + } + return response + } + + /// 指令请求只携带任务身份及已确认的指令码。 + private struct CommandBody: Encodable { + let taskID: Int + let command: String + + /// 朱工请求字段映射,不附加飞机或模拟标志。 + private enum CodingKeys: String, CodingKey { case taskID = "id", command } + } +} diff --git a/suixinkan/Features/DroneDock/Models/DroneDockCommandModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockCommandModels.swift new file mode 100644 index 0000000..cb16582 --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneDockCommandModels.swift @@ -0,0 +1,67 @@ +import Foundation + +/// 朱工 command 接口明确允许的四类安全指令,不接受服务端未知动作直接透传。 +enum DroneDockSafetyCommand: String, CaseIterable, Sendable { + /// 暂停航线并悬停待命。 + case pause = "flighttask_pause" + /// 恢复已暂停的航线。 + case resume = "flighttask_recovery" + /// 立即返航;服务端会中断当前任务并释放飞行锁。 + case returnHome = "return_home" + /// 取消返航,不代表已恢复或重新创建原拍摄任务。 + case cancelReturn = "return_home_cancel" +} + +/// 指令受理回执;仅保留后端返回的身份、读数与状态,不推断设备已完成动作。 +struct DroneDockCommandResponse: Decodable, Equatable, Sendable { + /// 文档要求回显的订单飞行任务 ID。 + let orderFlightTaskID: Int? + /// 本次回显的指令码,API 核验其与请求一致。 + let command: String? + /// 任务实际锁定的机场标识,客户端不提交或覆盖它。 + let airportSN: String? + /// 司空状态允许任意 JSON 类型;null 与缺失都不构成执行成功证据。 + let djiStatus: DroneDockHomeJSONValue? + /// 非实时采集的六项读数,不替代 shooting 完整快照。 + let metrics: [DroneDockHomeMetric] + /// 完整 data 格式化 JSON,供本地模拟联调查看未知字段与原始类型。 + let dataJSON: String + + /// 朱工指令回执字段映射。 + private enum CodingKeys: String, CodingKey { + case orderFlightTaskID = "order_flight_task_id", command, airportSN = "airport_sn" + case djiStatus = "dji_status", metrics + } + + /// 不补造身份、状态或读数,完整 JSON 仍保留实际出现的 null 字段。 + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID) + command = try container.decodeIfPresent(String.self, forKey: .command) + airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN) + djiStatus = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .djiStatus) + metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? [] + let raw = try DroneDockHomeJSONValue(from: decoder) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + dataJSON = String(decoding: try encoder.encode(DroneDockCommandJSONSnapshot(value: raw)), as: UTF8.self) + } +} + +/// 将现有 JSON 值完整格式化,不更改指令回执的原始值与结构。 +private struct DroneDockCommandJSONSnapshot: Encodable { + let value: DroneDockHomeJSONValue + + /// 保留字符串、数字、布尔、null 和嵌套对象,不添加业务成功推断。 + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch value { + case .object(let object): try container.encode(object.mapValues { DroneDockCommandJSONSnapshot(value: $0) }) + case .array(let array): try container.encode(array.map { DroneDockCommandJSONSnapshot(value: $0) }) + case .string(let text): try container.encode(text) + case .number(let number): try container.encode(number) + case .bool(let flag): try container.encode(flag) + case .null: try container.encodeNil() + } + } +} diff --git a/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift index b1ee324..a02ae86 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift @@ -189,6 +189,26 @@ struct DroneDockShootingUI: Decodable, Equatable, Sendable { let title: String? /// 服务端阶段说明,不由 GET 请求成功拼造飞行进度。 let message: String? + /// 服务端实际提供的安全指令;缺失时保持未知,不据阶段文案自行补齐。 + let commands: [DroneDockShootingCommand]? + + /// 保留既有展示构造方式,新增动作列表默认为未知。 + init(phase: String?, title: String?, message: String?, commands: [DroneDockShootingCommand]? = nil) { + self.phase = phase + self.title = title + self.message = message + self.commands = commands + } +} + +/// shooting 或 start-shoot 的指令展示项;原始字符串保留,执行时另作白名单校验。 +struct DroneDockShootingCommand: Decodable, Equatable, Sendable { + /// 服务端指令码,未知值不应开放动作。 + let command: String? + /// 服务端按钮标题。 + let label: String? + /// 服务端按钮副标题。 + let sub: String? } /// 将现有 JSON 值解码结果重新格式化,完整保留 shooting 的未建模字段。 diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift index b4038a2..c26a7f9 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift @@ -1,6 +1,6 @@ import Foundation -/// 拍摄任务状态及可选开拍流程,始终复用同一任务;禁飞调试仅为本地模拟注入开拍服务。 +/// 拍摄任务状态及可选控制流程,始终复用同一任务;禁飞调试仅为本地模拟注入操作服务。 final class DroneDockShootingTaskViewModel { /// 页面绑定的账号、景区和门店身份。 let context: DroneDockHomeContext @@ -24,25 +24,42 @@ final class DroneDockShootingTaskViewModel { private(set) var hasSubmittedStart = false /// 同任务开拍回执;受理成功不直接替代 shooting 的完整状态快照。 private(set) var startResponse: DroneDockStartShootResponse? + /// 指令提交及其后单次回查期间锁定控制动作,旧状态继续展示。 + private(set) var isSendingCommand = false + /// 当前正在提交或核对的指令;结束后清空。 + private(set) var activeCommand: DroneDockSafetyCommand? + /// 最近一次明确受理且身份一致的指令回执,不作为设备已执行的证据。 + private(set) var commandResponse: DroneDockCommandResponse? + /// 指令业务拒绝、本地拦截或结果待核对提示。 + private(set) var commandErrorMessage: String? + /// 已发但结果不明确时保持锁定,普通读取不能自动解除或重发。 + private(set) var commandOutcomeUnknown = false private let service: any DroneDockShootingServing private let startService: (any DroneDockStartShooting)? + private let commandService: (any DroneDockCommandSending)? private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext private var generation = 0 private var identityInvalidated = false private var startGeneration = 0 private var didSendStart = false + private var commandGeneration = 0 + private var didSendCommand = false + // 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。 + private var pendingAcceptedCommands: Set = [] - /// 默认只读;只有显式注入开拍服务才提供开拍动作,当前正式入口不注入该服务。 + /// 默认只读;仅显式注入模拟操作服务时开放对应动作,当前正式入口不注入。 init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder, service: any DroneDockShootingServing, startService: (any DroneDockStartShooting)? = nil, + commandService: (any DroneDockCommandSending)? = nil, currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { self.context = context self.taskID = taskID self.order = order self.service = service self.startService = startService + self.commandService = commandService self.currentContext = currentContext } @@ -53,8 +70,9 @@ final class DroneDockShootingTaskViewModel { } @MainActor - private func refreshSnapshot(allowWhileStarting: Bool) async { - guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting else { return } + private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false) async { + guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting, + !isSendingCommand || allowWhileCommand else { return } generation &+= 1 let requestGeneration = generation isLoading = true @@ -79,6 +97,7 @@ final class DroneDockShootingTaskViewModel { throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取") } response = value + pendingAcceptedCommands.formIntersection(availableSafetyCommands) } catch { guard accepts(requestGeneration) else { return } errorMessage = error is CancellationError ? nil : error.localizedDescription @@ -89,6 +108,7 @@ final class DroneDockShootingTaskViewModel { @MainActor func invalidate(preservingSnapshot: Bool = false) { invalidateStartShooting() + invalidateCommand() generation &+= 1 isLoading = false if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true } @@ -96,6 +116,9 @@ final class DroneDockShootingTaskViewModel { response = nil startResponse = nil startErrorMessage = nil + commandResponse = nil + commandErrorMessage = nil + pendingAcceptedCommands.removeAll() errorMessage = "账号或景区已变化,请返回工作台重新进入" } else { if !preservingSnapshot { response = nil } @@ -106,8 +129,9 @@ final class DroneDockShootingTaskViewModel { /// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。 var canStartShooting: Bool { startService != nil && context.canLoad && taskID > 0 && !identityInvalidated - && !isLoading && !isStartingShooting && errorMessage == nil + && !isLoading && !isStartingShooting && !isSendingCommand && errorMessage == nil && !hasSubmittedStart && !startOutcomeUnknown + && !commandOutcomeUnknown && pendingAcceptedCommands.isEmpty && resolvedDisplayPhase().0 == .ready && response?.executeGate?.canExecute == true && response?.executeGate?.primaryAction == "start_shoot" @@ -180,6 +204,93 @@ final class DroneDockShootingTaskViewModel { didSendStart = false } + /// 只识别当前快照明确提供的四种指令,未知值忽略,同一指令只展示一次。 + var availableSafetyCommands: [DroneDockSafetyCommand] { + var commands: [DroneDockSafetyCommand] = [] + for item in response?.ui?.commands ?? [] { + guard let raw = item.command, let command = DroneDockSafetyCommand(rawValue: raw), + !commands.contains(command) else { continue } + commands.append(command) + } + return commands + } + + /// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。 + func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool { + commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated + && !isLoading && !isStartingShooting && !isSendingCommand && errorMessage == nil + && !startOutcomeUnknown && !commandOutcomeUnknown && !pendingAcceptedCommands.contains(command) + && (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID) + && (response?.currentPlane?.id ?? 0) > 0 + && availableSafetyCommands.contains(command) + } + + /// 只提交当前任务的一次指令,受理后单次回查;不轮询、不改派飞机、不自动重试。 + @MainActor + func sendCommand(_ command: DroneDockSafetyCommand, + onStateChange: @escaping @MainActor () -> Void = {}) async { + guard canSendCommand(command), let commandService else { return } + guard context.hasSameIdentity(as: currentContext()) else { + identityInvalidated = true + invalidate() + onStateChange() + return + } + guard !Task.isCancelled else { return } + commandGeneration &+= 1 + let requestGeneration = commandGeneration + isSendingCommand = true + activeCommand = command + didSendCommand = false + commandResponse = nil + commandErrorMessage = nil + onStateChange() + defer { + if commandGeneration == requestGeneration { + if Task.isCancelled && didSendCommand && commandResponse == nil { markCommandUnknown() } + isSendingCommand = false + activeCommand = nil + didSendCommand = false + onStateChange() + } + } + guard acceptsCommand(requestGeneration) else { return } + do { + didSendCommand = true + let value = try await commandService.sendCommand(taskID: taskID, command: command) + guard acceptsCommand(requestGeneration) else { return } + guard value.orderFlightTaskID == taskID, value.command == command.rawValue else { + throw APIError.decodeFailed("安全指令回执与当前任务或指令不一致,请先核对任务状态") + } + commandResponse = value + pendingAcceptedCommands.insert(command) + commandOutcomeUnknown = false + onStateChange() + guard acceptsCommand(requestGeneration) else { return } + await refreshSnapshot(allowWhileStarting: false, allowWhileCommand: true) + } catch { + if error is DeviceCommandDebugBlockedError, commandGeneration == requestGeneration { didSendCommand = false } + guard acceptsCommand(requestGeneration) else { return } + if error is DeviceCommandDebugBlockedError { + commandErrorMessage = DeviceCommandDebugPolicy.blockedMessage + } else if case APIError.serverCode = error { + commandErrorMessage = error.localizedDescription + } else { + markCommandUnknown(reason: error.localizedDescription) + } + } + } + + /// 离页或后台取消控制流程;已发而未受理时保留未知结果锁,忽略迟到回执。 + @MainActor + func invalidateCommand() { + if isSendingCommand && didSendCommand && commandResponse == nil { markCommandUnknown() } + commandGeneration &+= 1 + isSendingCommand = false + activeCommand = nil + didSendCommand = false + } + /// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。 var title: String { if let title = usable(response?.header?.title) { return title } @@ -211,12 +322,13 @@ final class DroneDockShootingTaskViewModel { ?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认" } - /// 保留服务端阶段说明;未确认的开拍结果明确提示核对,不伪装为正在拍摄。 + /// 保留服务端阶段说明;操作结果未知时优先提示核对,不伪装为设备已执行。 var statusMessage: String { if response == nil { if let errorMessage { return errorMessage } if isLoading { return "正在读取当前拍摄任务" } } + if let commandErrorMessage { return commandErrorMessage } if resolvedDisplayPhase().0 == .failed { return failureMessage } if startOutcomeUnknown, let startErrorMessage { return startErrorMessage } if resolvedDisplayPhase().0 == .ready { @@ -243,7 +355,7 @@ final class DroneDockShootingTaskViewModel { let actionTitle: String? let enabled: Bool switch phase { - case .ready where hasSubmittedStart || startOutcomeUnknown: + case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown: action = .refresh actionTitle = "刷新状态" enabled = !identityInvalidated @@ -271,7 +383,7 @@ final class DroneDockShootingTaskViewModel { } return DroneDockTaskPresentation(phase: phase, title: title, message: message, deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle, - isActionEnabled: enabled && !isLoading && !isStartingShooting && !identityInvalidated && (errorMessage == nil || action == .refresh), + isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !identityInvalidated && (errorMessage == nil || action == .refresh), actionNote: phase == .failed ? retryUnavailableNote : nil) } @@ -310,6 +422,22 @@ final class DroneDockShootingTaskViewModel { return !Task.isCancelled } + @MainActor + private func acceptsCommand(_ requestGeneration: Int) -> Bool { + guard commandGeneration == requestGeneration else { return false } + guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else { + identityInvalidated = true + invalidate() + return false + } + return !Task.isCancelled + } + + private func markCommandUnknown(reason: String? = nil) { + commandOutcomeUnknown = true + commandErrorMessage = (reason.map { "\($0)。" } ?? "") + "安全指令结果待核对,请刷新任务状态,勿重复提交" + } + private func markStartUnknown(reason: String? = nil) { startOutcomeUnknown = true startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交" diff --git a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift index f66e176..dc06568 100644 --- a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift @@ -1,7 +1,7 @@ import SnapKit import UIKit -/// 拍摄任务页:真实入口只读,本地模拟入口可注入开始拍摄服务验证接口流程。 +/// 拍摄任务页:真实入口只读,本地模拟入口可验证开拍与底部安全指令合同。 @MainActor final class DroneDockShootingTaskViewController: BaseViewController { /// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。 @@ -23,11 +23,13 @@ final class DroneDockShootingTaskViewController: BaseViewController { private let simulationRecordsProvider: (@MainActor () -> String)? private var refreshTask: Task? private var startTask: Task? + private var commandTask: Task? private var requestGeneration = 0 private var isPageVisible = false private var isApplicationActive = false private var isRequesting = false private var isStartingAction = false + private var isSendingSafetyAction = false /// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。 init(viewModel: DroneDockShootingTaskViewModel, @@ -51,6 +53,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { deinit { refreshTask?.cancel() startTask?.cancel() + commandTask?.cancel() NotificationCenter.default.removeObserver(self) } @@ -156,6 +159,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { override func bindActions() { statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() } statusView.onDetails = { [weak self] in self?.showStatusDetails() } + safetyView.onCommand = { [weak self] command in self?.safetyCommandTriggered(command) } NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), @@ -180,6 +184,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func applySnapshot() { guard isViewLoaded else { return } let loading = isRequesting || viewModel.isLoading || isStartingAction || viewModel.isStartingShooting + || isSendingSafetyAction || viewModel.isSendingCommand taskTitleLabel.text = viewModel.title subtitleLabel.text = viewModel.subtitle let telemetry = viewModel.telemetry @@ -190,6 +195,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务", deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation statusView.apply(value, isRefreshing: loading) + safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil, + isInteractive: isPageVisible && isApplicationActive && !loading) statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading } navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil @@ -197,7 +204,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func primaryActionTriggered() { guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading, - !isStartingAction, !viewModel.isStartingShooting else { return } + !isStartingAction, !viewModel.isStartingShooting, + !isSendingSafetyAction, !viewModel.isSendingCommand else { return } let state = viewModel.presentation guard state.isActionEnabled else { return } switch state.action { @@ -221,6 +229,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { texts.append("刷新失败,当前显示上次数据:\(error)") } if let error = viewModel.startErrorMessage { texts.append(error) } + if let error = viewModel.commandErrorMessage { texts.append(error) } var distinct: [String] = [] for text in texts where !distinct.contains(text) { distinct.append(text) } let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert) @@ -231,7 +240,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { /// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。 private func refreshTaskIfVisible() { guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading, - !isStartingAction, !viewModel.isStartingShooting else { return } + !isStartingAction, !viewModel.isStartingShooting, + !isSendingSafetyAction, !viewModel.isSendingCommand else { return } requestGeneration &+= 1 let generation = requestGeneration isRequesting = true @@ -256,6 +266,9 @@ final class DroneDockShootingTaskViewController: BaseViewController { refreshTask = nil startTask?.cancel() startTask = nil + commandTask?.cancel() + commandTask = nil + isSendingSafetyAction = false isStartingAction = false isRequesting = false viewModel.invalidate(preservingSnapshot: true) @@ -264,7 +277,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { /// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。 private func startShootingIfAllowed() { - guard !isStartingAction, viewModel.canStartShooting else { return } + guard !isStartingAction, !isSendingSafetyAction, viewModel.canStartShooting else { return } requestGeneration &+= 1 let generation = requestGeneration isStartingAction = true @@ -285,6 +298,51 @@ final class DroneDockShootingTaskViewController: BaseViewController { } } + /// 仅模拟入口响应安全按钮;返航会中断任务,先明确展示其含义再提交一次。 + private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) { + guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive, + presentedViewController == nil, !isSendingSafetyAction, !isStartingAction, + !isRequesting, viewModel.canSendCommand(command) else { return } + if command == .returnHome { + let alert = UIAlertController(title: "立即返航(本地模拟)", + message: "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。", preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "取消", style: .cancel)) + alert.addAction(UIAlertAction(title: "模拟返航", style: .destructive) { [weak self] _ in + self?.sendSafetyCommand(command) + }) + present(alert, animated: true) + } else { + sendSafetyCommand(command) + } + } + + /// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。 + private func sendSafetyCommand(_ command: DroneDockSafetyCommand) { + guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive, + !isSendingSafetyAction, !isStartingAction, !isRequesting, + viewModel.canSendCommand(command) else { return } + requestGeneration &+= 1 + let generation = requestGeneration + isSendingSafetyAction = true + applySnapshot() + commandTask = Task { @MainActor [weak self] in + guard let self else { return } + await self.viewModel.sendCommand(command) { [weak self] in self?.applySnapshot() } + guard self.isPageVisible, self.isApplicationActive, + self.requestGeneration == generation, !Task.isCancelled else { return } + self.commandTask = nil + self.isSendingSafetyAction = false + self.applySnapshot() + if let error = self.viewModel.commandErrorMessage { + self.showToast(error) + } else if let error = self.viewModel.errorMessage { + self.showToast("模拟指令已受理,状态刷新失败:\(error)") + } else { + self.showToast("本地模拟指令已受理,未发送设备指令") + } + } + } + /// 模拟入口专用记录页,内容由内存传输提供,不请求后端日志或设备。 @objc private func showSimulationRecords() { guard let simulationRecordsProvider, presentedViewController == nil else { return } @@ -349,9 +407,13 @@ final class DroneDockSimulationRecordsViewController: BaseViewController { @objc private func close() { dismiss(animated: true) } } -/// 固定底部的安全控制占位,尚未接入控制接口时不提供可执行的飞控动作。 +/// 固定底部的安全控制,只在隔离模拟入口按当前接口提供的指令展示可用操作。 @MainActor private final class DroneDockTaskSafetyView: UIView { + /// 将用户选择的白名单指令交给页面,不直接调用任何服务。 + var onCommand: ((DroneDockSafetyCommand) -> Void)? + private var pauseCommand = DroneDockSafetyCommand.pause + private var returnCommand = DroneDockSafetyCommand.returnHome private let header = DroneDockStyle.label("安全控制", size: 11, color: DroneDockStyle.secondary) private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true) private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false) @@ -361,7 +423,7 @@ private final class DroneDockTaskSafetyView: UIView { private var buttonGap: Constraint? private var buttonHeight: Constraint? - /// 复用安全按钮样式,按钮始终保留占位与明确的不可用状态。 + /// 复用安全按钮样式,初始没有状态数据时保持禁用。 override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white @@ -384,6 +446,8 @@ private final class DroneDockTaskSafetyView: UIView { returnButton.accessibilityIdentifier = "drone.task.remote.return" pauseButton.apply(title: "紧急暂停", subtitle: "暂不可用", enabled: false) returnButton.apply(title: "立即返航", subtitle: "暂不可用", enabled: false) + pauseButton.addTarget(self, action: #selector(pauseTapped), for: .touchUpInside) + returnButton.addTarget(self, action: #selector(returnTapped), for: .touchUpInside) header.snp.makeConstraints { make in headerTop = make.top.equalToSuperview().offset(10).constraint make.leading.trailing.equalToSuperview().inset(16) @@ -399,6 +463,36 @@ private final class DroneDockTaskSafetyView: UIView { @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + /// 保持两列固定布局,暂停/继续与返航/取消由快照中的指令白名单决定。 + func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool) { + let commands = model.availableSafetyCommands + pauseCommand = commands.contains(.resume) ? .resume : .pause + returnCommand = commands.contains(.cancelReturn) ? .cancelReturn : .returnHome + header.text = model.commandOutcomeUnknown ? "安全控制 · 结果待核对" + : model.isSendingCommand ? "安全控制 · 本地模拟发送中" + : isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制" + for (button, command) in [(pauseButton, pauseCommand), (returnButton, returnCommand)] { + let title: String + let subtitle: String + switch command { + case .pause: title = "紧急暂停"; subtitle = "悬停待命" + case .resume: title = "继续拍摄"; subtitle = "恢复航线" + case .returnHome: title = "立即返航"; subtitle = "中断任务" + case .cancelReturn: title = "取消返航"; subtitle = "不恢复已中断任务" + } + let enabled = isSimulation && isInteractive && model.canSendCommand(command) + let detail = model.activeCommand == command ? "本地模拟发送中…" + : model.commandOutcomeUnknown ? "结果待核对" + : !isSimulation || !commands.contains(command) ? "暂不可用" : subtitle + button.apply(title: title, subtitle: detail, enabled: enabled) + button.setControlSymbol(command == .resume ? "play.circle" : command == .pause ? "pause.circle" + : command == .cancelReturn ? "xmark.circle" : "arrow.uturn.backward") + } + } + + @objc private func pauseTapped() { guard pauseButton.isEnabled else { return }; onCommand?(pauseCommand) } + @objc private func returnTapped() { guard returnButton.isEnabled else { return }; onCommand?(returnCommand) } + /// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。 func configure(compact: Bool) { headerTop?.update(offset: compact ? 8 : 10) diff --git a/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift b/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift index 9d9de9d..0535d42 100644 --- a/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift +++ b/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift @@ -2,18 +2,24 @@ import Foundation import UIKit #if DEBUG -/// 独立的准备、召唤与开拍模拟入口;所有请求在内存中处理,不复用账号或真实网络服务。 +/// 独立的准备、召唤、开拍及安全控制模拟入口;所有请求在内存中处理,不复用真实网络。 @MainActor enum DroneDockStartShootSimulation { /// 显式启动参数选择准备页或任务页,两个入口始终使用隔离的模拟会话。 static func makeController(arguments: [String]) -> UIViewController? { let startsAtPreparation = arguments.contains("--dock-preparation-mock") - guard startsAtPreparation || arguments.contains("--dock-start-shoot-mock") else { return nil } + let startsAtCommands = arguments.contains("--dock-command-mock") + guard startsAtPreparation || startsAtCommands || arguments.contains("--dock-start-shoot-mock") else { return nil } let resultArgument = arguments.first { $0.hasPrefix("--dock-start-shoot-result=") } let result = resultArgument.flatMap { DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-start-shoot-result=".count))) } ?? .success - return makeFlow(result: result, startsAtPreparation: startsAtPreparation) + let commandResultArgument = arguments.first { $0.hasPrefix("--dock-command-result=") } + let commandResult = commandResultArgument.flatMap { + DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-command-result=".count))) + } ?? .success + return makeFlow(result: result, startsAtPreparation: startsAtPreparation, + commandResult: commandResult, startsAtCommands: startsAtCommands) } /// 从正式准备页进入全新的纯内存模拟,不携带真实订单、账号或设备身份。 @@ -22,8 +28,11 @@ enum DroneDockStartShootSimulation { } private static func makeFlow(result: DroneDockStartShootMockResult, - startsAtPreparation: Bool) -> UIViewController? { - let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation) + startsAtPreparation: Bool, + commandResult: DroneDockStartShootMockResult = .success, + startsAtCommands: Bool = false) -> UIViewController? { + let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation, + commandResult: commandResult, hasStarted: startsAtCommands && !startsAtPreparation) let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!, webSocketURL: URL(string: "wss://mock.invalid/unused")!) let client = APIClient(environment: environment, session: session) @@ -35,7 +44,8 @@ enum DroneDockStartShootSimulation { let taskFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController = { taskID, taskOrder, taskContext in let model = DroneDockShootingTaskViewModel(context: taskContext, taskID: taskID, order: taskOrder, service: DroneDockShootingAPI(client: client), - startService: DroneDockStartShootAPI(client: client), currentContext: { context }) + startService: DroneDockStartShootAPI(client: client), + commandService: DroneDockCommandAPI(client: client), currentContext: { context }) return DroneDockShootingTaskViewController(viewModel: model, materialsControllerFactory: { _, _ in let unavailable = UIViewController() @@ -65,18 +75,25 @@ private enum DroneDockStartShootMockResult: String { case timeout } -/// 无任何网络转发能力的响应替身;仅接受 mock.invalid 上约定的准备、模拟召唤和开拍请求。 +/// 无任何网络转发能力的响应替身;仅接受 mock.invalid 上约定的准备、召唤、开拍和安全指令。 private final class DroneDockStartShootMockSession: LocalSimulationURLSession { private let result: DroneDockStartShootMockResult + private let commandResult: DroneDockStartShootMockResult private let lock = NSLock() private var hasCreated: Bool private var hasSummoned: Bool - private var hasStarted = false + private var hasStarted: Bool + private var isPaused = false + private var isReturning = false + private var wasInterrupted = false private var exchanges: [Exchange] = [] /// 固定当前实例结果,不能用参数切换到真实传输。 - init(result: DroneDockStartShootMockResult, requiresPreparation: Bool) { + init(result: DroneDockStartShootMockResult, requiresPreparation: Bool, + commandResult: DroneDockStartShootMockResult, hasStarted: Bool) { self.result = result + self.commandResult = commandResult + self.hasStarted = hasStarted hasCreated = !requiresPreparation hasSummoned = !requiresPreparation } @@ -99,7 +116,8 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { return item } let object: [String: Any] = ["source": "local_mock", "description": "纯内存模拟,未调用后端或设备", - "network_sent": false, "scenario": result.rawValue, "records": items] + "network_sent": false, "scenario": result.rawValue, + "command_scenario": commandResult.rawValue, "records": items] guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) else { return "本地模拟记录暂不可显示;没有网络请求。" } @@ -189,6 +207,34 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") } return try envelope(shootingData()) } + if request.httpMethod == "POST", url.path == "/api/app/airport/command" { + guard url.query == nil, let body = request.httpBody, + let object = try JSONSerialization.jsonObject(with: body) as? [String: Any], + Set(object.keys) == ["id", "command"], + let values = try? JSONDecoder().decode(CommandBody.self, from: body), + values.id == 901, let command = DroneDockSafetyCommand(rawValue: values.command) else { + throw URLError(.badURL) + } + guard availableCommands.contains(command) else { + return try envelope([:], code: 100099, message: "本地模拟:当前任务不允许这项指令") + } + switch commandResult { + case .businessFailure: + return try envelope([:], code: 100099, message: "本地模拟:指令被拒绝,未改变任务状态") + case .timeout: + throw URLError(.timedOut) + case .success: + switch command { + case .pause: isPaused = true + case .resume: isPaused = false + case .returnHome: isReturning = true; wasInterrupted = true; isPaused = false + case .cancelReturn: isReturning = false; isPaused = true + } + return try envelope(["command": command.rawValue, "order_flight_task_id": 901, + "airport_sn": "LOCAL-MOCK-DOCK-201", "dji_status": simulatedPhase, + "metrics": simulatedMetrics]) + } + } guard request.httpMethod == "POST", url.path == "/api/app/airport/start-shoot", url.query == nil, let body = request.httpBody, let object = try JSONSerialization.jsonObject(with: body) as? [String: Any], @@ -197,6 +243,9 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { throw URLError(.unsupportedURL) } guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") } + guard !isPaused, !wasInterrupted else { + return try envelope([:], code: 100099, message: "本地模拟:任务暂停或已中断,不可开始拍摄") + } guard !hasStarted else { return try envelope([:], code: 100099, message: "本地模拟:该任务已开始,请读取任务状态") } @@ -233,31 +282,76 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { } private func shootingData() -> [String: Any] { - ["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(), + let canStart = !hasStarted && !isPaused && !wasInterrupted + let phaseTitle: String + if wasInterrupted { + phaseTitle = isReturning ? "本地模拟:立即返航中断任务;无人机返航中" : "本地模拟:返航已取消,任务仍已中断" + } else if isPaused { + phaseTitle = "拍摄已暂停(模拟)" + } else { + phaseTitle = hasStarted ? "无人机正在拍摄中(模拟)" : "无人机已到达(模拟)" + } + let commands: [[String: String]] = availableCommands.map { command in + switch command { + case .pause: return ["command": command.rawValue, "label": "紧急暂停", "sub": "悬停待命"] + case .resume: return ["command": command.rawValue, "label": "继续拍摄", "sub": "恢复航线"] + case .returnHome: return ["command": command.rawValue, "label": "立即返航", "sub": "中断任务"] + case .cancelReturn: return ["command": command.rawValue, "label": "取消返航", "sub": "不恢复已中断任务"] + } + } + let deviceLabel = isReturning ? "返航中" : isPaused ? "悬停中" : hasStarted ? "拍摄中" : "空闲" + return ["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(), "scenic": ["id": 128, "name": "本地模拟景区"], "scenic_spot": ["id": 301, "name": "模拟点位"], "air_line": ["id": 401, "name": "模拟航线", "scenic_spot_id": 301], "header": ["order_number": "LOCAL-MOCK-ORDER-901", "title": "模拟点位 · 模拟航线", "tourist_label": "本地模拟,无设备指令", "package_name": "模拟套餐 · 含5次拍摄"], "current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-PLANE-201", "online_status": 1, - "work_status": hasStarted ? 2 : 1, "work_status_label": hasStarted ? "拍摄中" : "空闲", - "status_text": hasStarted ? "模拟拍摄中 · 电量95%" : "模拟就绪 · 电量95%"], - "metrics": [["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"], - ["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"], - ["key": "signal", "value": "良好"], ["key": "satellite", "value": "36颗"]], + "work_status": hasStarted ? 2 : 1, "work_status_label": deviceLabel, + "status_text": "本地模拟 · \(deviceLabel) · 电量95%"], + "metrics": simulatedMetrics, "plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000], - "execute_gate": ["can_execute": !hasStarted, "code": hasStarted ? "already_started" : "ok", + "execute_gate": ["can_execute": canStart, "code": wasInterrupted ? "return_home" : hasStarted ? "already_started" : "ok", "message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求", - "primary_action": hasStarted ? "shooting" : "start_shoot", + "primary_action": canStart ? "start_shoot" : simulatedPhase, "primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"], - "ui": ["phase": hasStarted ? "shooting" : "arrived_pending_start", - "title": hasStarted ? "无人机正在拍摄中(模拟)" : "无人机已到达(模拟)", - "message": hasStarted ? "本地模拟状态回查:拍摄中,未向设备发送指令。" : "点击开始拍摄,仅验证本地接口流程。"]] + "ui": ["phase": simulatedPhase, "title": phaseTitle, "commands": commands, + "message": wasInterrupted ? phaseTitle : "本地模拟状态回查,未向设备发送指令。"]] } private func taskData() -> [String: Any] { - ["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128, + var task: [String: Any] = ["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128, "status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"] + if wasInterrupted { + task["status"] = 40 + task["status_label"] = "任务已中断(模拟)" + task["wayline_status"] = 40 + task["wayline_status_label"] = "已中断(模拟)" + task["result_code"] = "return_home" + task["result_message"] = isReturning ? "本地模拟:立即返航中断任务;无人机返航中。" + : "本地模拟:返航已取消,任务仍已中断,不能继续拍摄。" + } + return task + } + + private var availableCommands: [DroneDockSafetyCommand] { + guard hasSummoned else { return [] } + if isReturning { return [.cancelReturn] } + if wasInterrupted { return [] } + return [isPaused ? .resume : .pause, .returnHome] + } + + private var simulatedPhase: String { + if isReturning { return "returning" } + if wasInterrupted { return "failed" } + if isPaused { return "paused" } + return hasStarted ? "shooting" : "arrived_pending_start" + } + + private var simulatedMetrics: [[String: String]] { + [["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"], + ["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"], + ["key": "signal", "value": "良好"], ["key": "satellite", "value": "36颗"]] } private func envelope(_ data: [String: Any], code: Int = 100000, message: String = "local mock success") throws -> Data { @@ -296,5 +390,11 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { private struct StartBody: Decodable { let id: Int } + + /// 模拟指令仍严格匹配正式接口的整数任务 ID 与白名单指令码。 + private struct CommandBody: Decodable { + let id: Int + let command: String + } } #endif diff --git a/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift b/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift index f7ef024..6f86733 100644 --- a/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift +++ b/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift @@ -326,6 +326,11 @@ final class DroneShootingTaskSafetyButton: UIButton { accessibilityLabel = title accessibilityValue = subtitle } + + /// 切换同一位置的暂停/继续或返航/取消图标,不改变按钮布局。 + func setControlSymbol(_ symbol: String) { + controlIconView.image = UIImage(systemName: symbol) + } } /// 任务本地静帧的全屏放大页,明确标记画面来源。 diff --git a/suixinkanTests/DroneDockCommandAPITests.swift b/suixinkanTests/DroneDockCommandAPITests.swift new file mode 100644 index 0000000..dbfb3a6 --- /dev/null +++ b/suixinkanTests/DroneDockCommandAPITests.swift @@ -0,0 +1,208 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 使用纯内存响应核验四类安全指令合同,不访问后端或真实设备。 +@MainActor +final class DroneDockCommandAPITests: XCTestCase { + /// 四种操作都只发一次带鉴权 POST,任务身份使用 id,不传飞机或机场标识。 + func testEachCommandSendsOnlyTaskIDAndCommand() async throws { + for command in DroneDockSafetyCommand.allCases { + let session = MockURLSession(responses: [try envelope(data: payload(command: command))]) + let client = APIClient(environment: .testing, session: session) + client.bindAuthTokenProvider { "command-test-token" } + let response = try await DroneDockCommandAPI(client: client).sendCommand(taskID: 501, command: command) + + XCTAssertEqual(session.requests.count, 1) + let request = try XCTUnwrap(session.requests.first) + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(request.url?.path, "/api/app/airport/command") + XCTAssertNil(request.url?.query) + XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "command-test-token") + let body = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.httpBody)) as? [String: Any]) + XCTAssertEqual(Set(body.keys), ["id", "command"]) + XCTAssertEqual(body["id"] as? Int, 501) + XCTAssertEqual(body["command"] as? String, command.rawValue) + XCTAssertEqual(response.orderFlightTaskID, 501) + XCTAssertEqual(response.command, command.rawValue) + XCTAssertEqual(response.airportSN, "LOCAL-MOCK-AIRPORT-501") + XCTAssertEqual(response.metrics.map(\.key), ["battery", "satellite"]) + } + } + + /// 无效任务 ID 与已经取消的操作在进入传输前终止。 + func testInvalidOrCancelledRequestNeverReachesTransport() async throws { + let session = MockURLSession(responses: []) + let api = DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) + for taskID in [0, -1] { + do { + _ = try await api.sendCommand(taskID: taskID, command: .pause) + XCTFail("无效任务 ID 不应提交") + } catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) } + } + let pending = Task { @MainActor in try await api.sendCommand(taskID: 501, command: .returnHome) } + pending.cancel() + do { + _ = try await pending.value + XCTFail("已取消的指令不应提交") + } catch is CancellationError {} + XCTAssertTrue(session.requests.isEmpty) + } + + /// 业务拒绝不受 data 形状影响,不伪造成成功或自动重试。 + func testBusinessFailurePreservesBackendReasonWithoutRetry() async throws { + for data: Any in [NSNull(), [:] as [String: Any], [] as [Any], payload()] { + let session = MockURLSession(responses: [try envelope(data: data, code: 100099, + message: "模拟:任务未锁定飞机,请先召唤无人机")]) + do { + _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) + .sendCommand(taskID: 501, command: .pause) + XCTFail("拒绝不能转换为成功") + } catch let APIError.serverCode(code, message) { + XCTAssertEqual(code, 100099) + XCTAssertEqual(message, "模拟:任务未锁定飞机,请先召唤无人机") + } + XCTAssertEqual(session.requests.count, 1) + } + } + + /// 网络超时只回报一次失败,不自动重复具有设备副作用的指令。 + func testTimeoutDoesNotAutomaticallyRetry() async throws { + let session = MockURLSession(results: [.failure(URLError(.timedOut))]) + do { + _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) + .sendCommand(taskID: 501, command: .returnHome) + XCTFail("超时不能伪造成功") + } catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) } + XCTAssertEqual(session.requests.count, 1) + } + + /// HTTP 失败不能因业务包裹恰为成功而转成受理回执。 + func testHTTPFailureDoesNotBecomeSuccess() async throws { + let session = MockURLSession(responses: [try envelope(data: payload())], statusCode: 503) + do { + _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) + .sendCommand(taskID: 501, command: .pause) + XCTFail("HTTP 失败不能算成功") + } catch let APIError.httpStatus(code, _) { XCTAssertEqual(code, 503) } + XCTAssertEqual(session.requests.count, 1) + } + + /// 错任务、无效身份和错误回显指令都拒绝,不将别的操作结果交给当前按钮。 + func testMismatchedIdentityAndEchoAreRejected() async throws { + let changes: [[String: Any]] = [ + ["order_flight_task_id": 502], ["order_flight_task_id": 0], + ["order_flight_task_id": -1], ["order_flight_task_id": "501"], + ["order_flight_task_id": true], ["order_flight_task_id": NSNull()], + ["command": "return_home"], ["command": "unknown"], ["command": NSNull()] + ] + for change in changes { + let session = MockURLSession(responses: [try envelope(data: payload().merging(change) { _, new in new })]) + do { + _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) + .sendCommand(taskID: 501, command: .pause) + XCTFail("错误任务或指令回显应拒绝") + } catch let APIError.decodeFailed(message) { XCTAssertFalse(message.isEmpty) } + XCTAssertEqual(session.requests.count, 1) + } + } + + /// 空响应或缺少必需回显不能生成成功回执。 + func testMissingDataAndEchoAreRejected() async throws { + let data: [Any] = [NSNull(), [:] as [String: Any], [] as [Any], + ["order_flight_task_id": 501], ["command": "flighttask_pause"]] + for value in data { + let session = MockURLSession(responses: [try envelope(data: value)]) + do { + _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) + .sendCommand(taskID: 501, command: .pause) + XCTFail("缺失回显不能算成功") + } catch let error as APIError { + switch error { + case .emptyData, .decodeFailed: break + default: XCTFail("应保留数据缺失或解析错误:\(error)") + } + } + XCTAssertEqual(session.requests.count, 1) + } + } + + /// dji_status 的字符串、数字、对象、数组和 null 均保留原始 JSON,不强行映射为飞行阶段。 + func testMixedDJIStatusAndUnknownFieldsArePreserved() async throws { + let statuses: [Any] = ["paused", 3, false, ["phase": "running", "code": 20], + [NSNull(), "pending"], NSNull()] + for status in statuses { + var data = payload() + data["dji_status"] = status + data["future"] = ["text": "001", "count": 0, "empty": NSNull()] as [String: Any] + let session = MockURLSession(responses: [try envelope(data: data)]) + let response = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) + .sendCommand(taskID: 501, command: .pause) + let original = try JSONDecoder().decode(DroneDockHomeJSONValue.self, + from: JSONSerialization.data(withJSONObject: data)) + let displayed = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: Data(response.dataJSON.utf8)) + XCTAssertEqual(displayed, original) + if status is NSNull { XCTAssertNil(response.djiStatus) } + else { XCTAssertNotNil(response.djiStatus) } + } + } + + /// 缺少非身份展示字段仍保留未知值,不阻断已经核对身份的回执。 + func testOptionalDisplayFieldsRemainUnknownWhenMissing() async throws { + let session = MockURLSession(responses: [try envelope(data: ["order_flight_task_id": 501, + "command": "flighttask_pause"])]) + let response = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) + .sendCommand(taskID: 501, command: .pause) + XCTAssertNil(response.airportSN) + XCTAssertNil(response.djiStatus) + XCTAssertTrue(response.metrics.isEmpty) + } + + /// 未标记本地模拟的传输在测试和生产环境都接收不到四类指令。 + func testDebugPolicyBlocksEveryCommandBeforeOrdinaryTransport() async throws { + for environment in [APIEnvironment.testing, .production] { + let session = SafetyCommandTransportProbe() + let api = DroneDockCommandAPI(client: APIClient(environment: environment, session: session)) + for command in DroneDockSafetyCommand.allCases { + do { + _ = try await api.sendCommand(taskID: 501, command: command) + XCTFail("新增 API 不得绕过禁飞保护") + } catch is DeviceCommandDebugBlockedError {} + } + XCTAssertEqual(session.requestCount, 0) + } + } + + /// 服务端动作列表缺失保持未知;未知动作可展示原文但不成为本地指令枚举。 + func testShootingCommandsDecodeKnownAndUnknownEntries() throws { + let ui = try JSONDecoder().decode(DroneDockShootingUI.self, from: Data(#"{"phase":"paused","commands":[{"command":"flighttask_recovery","label":"继续拍摄","sub":"恢复航线"},{"command":"future_control","label":"未来操作"}]}"#.utf8)) + XCTAssertEqual(ui.commands?.count, 2) + XCTAssertEqual(ui.commands?.first?.command, DroneDockSafetyCommand.resume.rawValue) + XCTAssertEqual(ui.commands?.first?.label, "继续拍摄") + XCTAssertEqual(ui.commands?.first?.sub, "恢复航线") + XCTAssertNil(DroneDockSafetyCommand(rawValue: try XCTUnwrap(ui.commands?.last?.command))) + let missing = try JSONDecoder().decode(DroneDockShootingUI.self, from: Data(#"{"phase":"shooting"}"#.utf8)) + XCTAssertNil(missing.commands) + XCTAssertNil(DroneDockShootingUI(phase: "shooting", title: nil, message: nil).commands) + } + + private func payload(command: DroneDockSafetyCommand = .pause) -> [String: Any] { + ["order_flight_task_id": 501, "command": command.rawValue, "airport_sn": "LOCAL-MOCK-AIRPORT-501", + "dji_status": "paused", "metrics": [["key": "battery", "value": "95%"], + ["key": "satellite", "value": "36颗"]]] + } + + private func envelope(data: Any, code: Int = 100000, message: String = "local mock success") throws -> Data { + try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data]) + } +} + +/// 不具备模拟豁免且自身绝不联网的探针,用于证明请求在真实传输边界前终止。 +private final class SafetyCommandTransportProbe: URLSessionProtocol { + private(set) var requestCount = 0 + + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + requestCount += 1 + throw URLError(.unsupportedURL) + } +} diff --git a/suixinkanTests/DroneDockCommandViewModelTests.swift b/suixinkanTests/DroneDockCommandViewModelTests.swift new file mode 100644 index 0000000..a10f18e --- /dev/null +++ b/suixinkanTests/DroneDockCommandViewModelTests.swift @@ -0,0 +1,451 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 安全控制仅通过隔离服务验证请求、单次回查及重复操作保护,不连接后端或设备。 +@MainActor +final class DroneDockCommandViewModelTests: XCTestCase { + /// 正式页默认不注入控制服务,即使快照提供指令也不可发送。 + func testDefaultReadonlyModelCannotSendCommands() async throws { + let fixture = try CommandTaskFixture(allowCommands: false) + await fixture.model.refresh() + for command in DroneDockSafetyCommand.allCases { + XCTAssertFalse(fixture.model.canSendCommand(command)) + await fixture.model.sendCommand(command) + } + XCTAssertTrue(fixture.write.requests.isEmpty) + } + + /// 仅使用当前快照的已知指令,去重后保留顺序,开拍门禁为 false 不影响安全动作。 + func testExplicitCommandWhitelistDoesNotUseStartGate() async throws { + let fixture = try CommandTaskFixture() + fixture.read.result = .success(try CommandTaskData.snapshot(commands: ["unknown_command", "return_home", "flighttask_pause", "flighttask_pause"])) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.availableSafetyCommands, [.returnHome, .pause]) + XCTAssertEqual(fixture.model.response?.executeGate?.canExecute, false) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertFalse(fixture.model.canSendCommand(.resume)) + await fixture.model.sendCommand(.resume) + XCTAssertTrue(fixture.write.requests.isEmpty) + } + + /// 缺少明确任务身份、锁定飞机或当前指令时,不将其它状态字段推导为许可。 + func testIncompleteSnapshotCannotSendCommands() async throws { + for snapshot in [ + try CommandTaskData.snapshot(commands: []), + try CommandTaskData.snapshot(lockedPlane: false), + try CommandTaskData.snapshot(includeTaskIdentity: false) + ] { + let fixture = try CommandTaskFixture() + fixture.read.result = .success(snapshot) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.write.requests.isEmpty) + } + } + + /// 接受回执时仍保留旧画面,只按随后同任务读取结果切换阶段,不轮询。 + func testSuccessRetainsSnapshotUntilSingleSameTaskRead() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + let previous = fixture.model.response + let paused = try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"]) + fixture.write.onRequest = { fixture.read.result = .success(paused) } + var observedReceiptBeforeRefresh = false + await fixture.model.sendCommand(.pause) { + if fixture.model.commandResponse != nil && fixture.model.response == previous { + observedReceiptBeforeRefresh = true + XCTAssertTrue(fixture.model.isSendingCommand) + XCTAssertEqual(fixture.model.activeCommand, .pause) + XCTAssertFalse(fixture.model.presentation.isActionEnabled) + } + } + XCTAssertTrue(observedReceiptBeforeRefresh) + XCTAssertEqual(fixture.write.requests.map(\.taskID), [501]) + XCTAssertEqual(fixture.write.requests.map(\.command), [.pause]) + XCTAssertEqual(fixture.read.requests, [501, 501]) + XCTAssertEqual(fixture.model.response, paused) + XCTAssertEqual(fixture.model.presentation.phase, .paused) + XCTAssertNotNil(fixture.model.commandResponse?.dataJSON) + XCTAssertFalse(fixture.model.isSendingCommand) + XCTAssertNil(fixture.model.activeCommand) + XCTAssertTrue(fixture.model.canSendCommand(.resume)) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + } + + /// 回查仍返回旧指令时,不重复提交已受理的同一指令。 + func testAcceptedCommandCannotRepeatFromStaleSnapshot() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + await fixture.model.sendCommand(.pause) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + fixture.model.invalidate(preservingSnapshot: true) + await fixture.model.refresh() + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.write.requests.count, 1) + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + } + + /// 多条指令均已受理而状态尚未追上时,后一条受理不能解除前一条的防重锁。 + func testStaleSnapshotRetainsEveryAcceptedCommandLock() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + await fixture.model.sendCommand(.returnHome) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) + await fixture.model.sendCommand(.pause) + await fixture.model.sendCommand(.returnHome) + fixture.model.invalidate(preservingSnapshot: true) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) + XCTAssertEqual(fixture.write.requests.map(\.command), [.pause, .returnHome]) + XCTAssertEqual(fixture.read.requests, [501, 501, 501, 501]) + } + + /// 暂停、恢复再暂停使用新的权限快照,可按用户操作继续调试同一任务。 + func testPauseResumeCycleAcceptsFreshCommandAvailability() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"])) + await fixture.model.sendCommand(.pause) + fixture.read.result = .success(try CommandTaskData.snapshot()) + await fixture.model.sendCommand(.resume) + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"])) + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.write.requests.map(\.command), [.pause, .resume, .pause]) + XCTAssertEqual(fixture.read.requests, [501, 501, 501, 501]) + XCTAssertEqual(fixture.model.presentation.phase, .paused) + } + + /// 明确业务拒绝保留旧状态,只在再次点击时重试。 + func testBusinessRejectionAllowsExplicitRetryWithoutRead() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + let previous = fixture.model.response + fixture.write.result = .failure(APIError.serverCode(100099, "模拟设备拒绝暂停")) + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.write.requests.count, 1) + XCTAssertEqual(fixture.read.requests.count, 1) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertEqual(fixture.model.commandErrorMessage, "模拟设备拒绝暂停") + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + fixture.write.result = nil + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.write.requests.count, 2) + XCTAssertNil(fixture.model.commandErrorMessage) + XCTAssertNotNil(fixture.model.commandResponse) + } + + /// 网络或解析失败不能确定是否已执行,刷新、重进均不能自动解锁重发。 + func testUnknownOutcomeLocksCommandsAndStartAcrossRefresh() async throws { + for error in [APIError.networkFailed("模拟超时"), APIError.httpStatus(500, "模拟异常"), APIError.decodeFailed("模拟回执无法解析")] { + let fixture = try CommandTaskFixture() + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "arrived_pending_start")) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.canStartShooting) + let previous = fixture.model.response + fixture.write.result = .failure(error) + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.model.commandOutcomeUnknown) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertTrue(fixture.model.presentation.message.contains("安全指令结果待核对")) + XCTAssertEqual(fixture.model.presentation.action, .refresh) + XCTAssertTrue(fixture.model.presentation.isActionEnabled) + fixture.model.invalidate(preservingSnapshot: true) + await fixture.model.refresh() + for command in DroneDockSafetyCommand.allCases { await fixture.model.sendCommand(command) } + await fixture.model.startShooting() + XCTAssertEqual(fixture.write.requests.count, 1) + XCTAssertTrue(fixture.start.requests.isEmpty) + } + } + + /// 本地拦截明确没有发送,不将其误判为结果未知。 + func testLocalBlockIsNotAnUnknownRemoteOutcome() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + fixture.write.result = .failure(DeviceCommandDebugBlockedError()) + await fixture.model.sendCommand(.pause) + fixture.model.invalidate(preservingSnapshot: true) + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + XCTAssertEqual(fixture.model.commandErrorMessage, DeviceCommandDebugPolicy.blockedMessage) + XCTAssertNil(fixture.model.commandResponse) + XCTAssertEqual(fixture.read.requests.count, 1) + } + + /// 指令在途时,连点、开拍和手动读取均不能插入并发请求。 + func testPendingCommandRejectsDoubleTapStartAndRefresh() async throws { + let fixture = try CommandTaskFixture() + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "arrived_pending_start")) + await fixture.model.refresh() + let previous = fixture.model.response + fixture.write.suspend = true + let sent = expectation(description: "指令进入隔离服务") + fixture.write.onRequest = { sent.fulfill() } + let pending = Task { await fixture.model.sendCommand(.pause) } + await fulfillment(of: [sent], timeout: 2) + XCTAssertTrue(fixture.model.isSendingCommand) + XCTAssertEqual(fixture.model.response, previous) + await fixture.model.sendCommand(.pause) + await fixture.model.sendCommand(.returnHome) + await fixture.model.startShooting() + await fixture.model.refresh() + XCTAssertEqual(fixture.write.requests.count, 1) + XCTAssertTrue(fixture.start.requests.isEmpty) + XCTAssertEqual(fixture.read.requests.count, 1) + fixture.write.finish() + await pending.value + XCTAssertEqual(fixture.read.requests.count, 2) + } + + /// 开拍在途时底部指令也保持互斥,不产生第二条控制请求。 + func testPendingStartRejectsCommands() async throws { + let fixture = try CommandTaskFixture() + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "arrived_pending_start")) + await fixture.model.refresh() + fixture.start.suspend = true + let sent = expectation(description: "开拍进入隔离服务") + fixture.start.onRequest = { sent.fulfill() } + let pending = Task { await fixture.model.startShooting() } + await fulfillment(of: [sent], timeout: 2) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.write.requests.isEmpty) + fixture.start.finish() + await pending.value + } + + /// 取消、离页后的迟到成功不能回填,也不能触发新的 shooting 读取。 + func testCancelledOrInvalidatedRequestIgnoresLateReceipt() async throws { + for leavePage in [false, true] { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + let previous = fixture.model.response + fixture.write.suspend = true + let sent = expectation(description: "指令等待取消") + fixture.write.onRequest = { sent.fulfill() } + let pending = Task { await fixture.model.sendCommand(.pause) } + await fulfillment(of: [sent], timeout: 2) + if leavePage { fixture.model.invalidate(preservingSnapshot: true) } else { pending.cancel() } + fixture.write.finish() + await pending.value + XCTAssertTrue(fixture.model.commandOutcomeUnknown) + XCTAssertNil(fixture.model.commandResponse) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertEqual(fixture.read.requests.count, 1) + XCTAssertFalse(fixture.model.isSendingCommand) + XCTAssertNil(fixture.model.activeCommand) + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.write.requests.count, 1) + } + } + + /// 点击前身份变化不发送;在途身份变化则撤下旧任务及回执。 + func testIdentityChangeBeforeOrDuringCommandClearsSnapshot() async throws { + let before = try CommandTaskFixture() + await before.model.refresh() + before.scope.scenicID = 999 + await before.model.sendCommand(.pause) + XCTAssertTrue(before.write.requests.isEmpty) + XCTAssertNil(before.model.response) + + let during = try CommandTaskFixture() + await during.model.refresh() + during.write.suspend = true + let sent = expectation(description: "指令等待身份变化") + during.write.onRequest = { sent.fulfill() } + let pending = Task { await during.model.sendCommand(.pause) } + await fulfillment(of: [sent], timeout: 2) + during.scope.scenicID = 999 + during.write.finish() + await pending.value + XCTAssertNil(during.model.response) + XCTAssertNil(during.model.commandResponse) + XCTAssertNil(during.model.commandErrorMessage) + XCTAssertFalse(during.model.canSendCommand(.pause)) + XCTAssertEqual(during.read.requests.count, 1) + } + + /// 即使替身绕过 API 校验,任务或回显指令错误也不能接受为成功。 + func testMismatchedReceiptLocksOutcomeWithoutFollowupRead() async throws { + for receipt in [try CommandTaskData.receipt(command: .pause, taskID: 999), + try CommandTaskData.receipt(command: .returnHome)] { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + fixture.write.result = .success(receipt) + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.model.commandOutcomeUnknown) + XCTAssertNil(fixture.model.commandResponse) + XCTAssertEqual(fixture.read.requests.count, 1) + } + } + + /// 返航可终结任务但仍提供取消返航;取消后不自动恢复任务或开始拍摄。 + func testFailedTaskCanCancelReturnOnlyWhenExplicitlyOffered() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "returning", commands: ["return_home_cancel"], taskStatus: 40)) + await fixture.model.sendCommand(.returnHome) + XCTAssertEqual(fixture.model.presentation.phase, .failed) + XCTAssertTrue(fixture.model.canSendCommand(.cancelReturn)) + XCTAssertFalse(fixture.model.canSendCommand(.resume)) + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "failed", commands: [], taskStatus: 40)) + await fixture.model.sendCommand(.cancelReturn) + XCTAssertEqual(fixture.write.requests.map(\.command), [.returnHome, .cancelReturn]) + XCTAssertEqual(fixture.model.presentation.phase, .failed) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertTrue(fixture.model.availableSafetyCommands.isEmpty) + } + + /// 已接受后读取失败保留旧快照,需新权限快照才能继续控制。 + func testAcceptedCommandWithFailedReadKeepsSnapshotAndReceipt() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + let previous = fixture.model.response + fixture.read.result = .failure(APIError.networkFailed("模拟回查失败")) + await fixture.model.sendCommand(.pause) + XCTAssertNotNil(fixture.model.commandResponse) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"])) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.canSendCommand(.resume)) + } + + /// 调用前已经取消的任务不能进入指令服务。 + func testCancellationBeforeSubmissionSendsNothing() async throws { + let fixture = try CommandTaskFixture() + await fixture.model.refresh() + let pending = Task { await fixture.model.sendCommand(.pause) } + pending.cancel() + await pending.value + XCTAssertTrue(fixture.write.requests.isEmpty) + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + } +} + +/// 隔离账号、读取、开拍及安全控制依赖,共用匿名任务身份。 +@MainActor +private struct CommandTaskFixture { + let scope: CommandTaskScope + let read: CommandTaskReadService + let write: CommandTaskWriteService + let start: CommandTaskStartService + let model: DroneDockShootingTaskViewModel + + init(allowCommands: Bool = true) throws { + scope = CommandTaskScope() + read = CommandTaskReadService(result: .success(try CommandTaskData.snapshot())) + write = CommandTaskWriteService() + start = CommandTaskStartService() + let boundScope = scope + model = DroneDockShootingTaskViewModel(context: boundScope.value, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: read, startService: start, + commandService: allowCommands ? write : nil, currentContext: { boundScope.value }) + } +} + +/// 显式切换景区,不改动共享登录状态。 +@MainActor +private final class CommandTaskScope { + var scenicID = 128 + var value: DroneDockHomeContext { DroneDockShootingTaskTestData.context(scenicID: scenicID) } +} + +/// 只返回配置的内存快照,记录回查次数。 +@MainActor +private final class CommandTaskReadService: DroneDockShootingServing { + var result: Result + private(set) var requests: [Int] = [] + + init(result: Result) { self.result = result } + + func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse { + requests.append(taskID) + return try result.get() + } +} + +/// 支持挂起和错误注入的安全控制替身,不具有联网能力。 +@MainActor +private final class CommandTaskWriteService: DroneDockCommandSending { + var result: Result? + var onRequest: (() -> Void)? + var suspend = false + private(set) var requests: [(taskID: Int, command: DroneDockSafetyCommand)] = [] + private var continuation: CheckedContinuation? + + func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { + requests.append((taskID, command)) + onRequest?() + if suspend { return try await withCheckedThrowingContinuation { continuation = $0 } } + return try result?.get() ?? CommandTaskData.receipt(command: command) + } + + func finish() { + let receipt = result ?? Result { try CommandTaskData.receipt(command: requests.last?.command ?? .pause) } + continuation?.resume(with: receipt) + continuation = nil + } +} + +/// 仅用于确认开拍与安全控制互斥的内存替身。 +@MainActor +private final class CommandTaskStartService: DroneDockStartShooting { + var onRequest: (() -> Void)? + var suspend = false + private(set) var requests: [Int] = [] + private var continuation: CheckedContinuation? + + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + requests.append(taskID) + onRequest?() + if suspend { return try await withCheckedThrowingContinuation { continuation = $0 } } + return try CommandTaskData.startReceipt() + } + + func finish() { + continuation?.resume(with: Result { try CommandTaskData.startReceipt() }) + continuation = nil + } +} + +/// 按接口合同构造的合成数据,不表示真实设备状态或受理回执。 +private enum CommandTaskData { + static func snapshot(phase: String = "shooting", commands: [String] = ["flighttask_pause", "return_home"], + taskStatus: Int = 20, lockedPlane: Bool = true, + includeTaskIdentity: Bool = true) throws -> DroneDockShootingResponse { + var task: [String: Any] = ["status": taskStatus] + if includeTaskIdentity { task["id"] = 501 } + return try DroneDockShootingTaskTestData.response(changes: [ + "order_flight_task": task, "task": task, + "current_plane": ["id": lockedPlane ? 58 : 0, "sn_number": "LOCAL-COMMAND-PLANE-058"], + "execute_gate": ["can_execute": phase == "arrived_pending_start", + "primary_action": phase == "arrived_pending_start" ? "start_shoot" : phase], + "ui": ["phase": phase, "title": "模拟安全指令阶段", "message": "本地模拟,未发送设备指令", + "commands": commands.map { ["command": $0] }] + ]) + } + + static func receipt(command: DroneDockSafetyCommand, taskID: Int = 501) throws -> DroneDockCommandResponse { + let payload: [String: Any] = ["order_flight_task_id": taskID, "command": command.rawValue, + "airport_sn": "LOCAL-COMMAND-DOCK-058", "dji_status": NSNull(), "metrics": []] + return try JSONDecoder().decode(DroneDockCommandResponse.self, + from: JSONSerialization.data(withJSONObject: payload)) + } + + static func startReceipt() throws -> DroneDockStartShootResponse { + try JSONDecoder().decode(DroneDockStartShootResponse.self, + from: Data(#"{"order_flight_task_id":501,"plane_id":58}"#.utf8)) + } +} diff --git a/suixinkanTests/DroneDockCommandViewTests.swift b/suixinkanTests/DroneDockCommandViewTests.swift new file mode 100644 index 0000000..a7ed757 --- /dev/null +++ b/suixinkanTests/DroneDockCommandViewTests.swift @@ -0,0 +1,264 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 使用隔离的内存模拟入口检查任务页安全按钮,不连接后端或真实无人机。 +@MainActor +final class DroneDockCommandViewTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 暂停和继续均使用同一任务,连点仅提交一次,刷新期间保留旧数据与固定区域。 + func testPauseAndResumeUseSameTaskWithoutDuplicateRequestsOrLayoutChanges() async throws { + let controller = try makeController(result: "success") + let window = makeWindow(controller) + defer { close(window) } + let model = controller.viewModel + try await settle(window) { model.canSendCommand(.pause) } + XCTAssertEqual(controller.title, "拍摄任务 · 本地模拟") + let pause = try button(controller, suffix: "pause") + let returnHome = try button(controller, suffix: "return") + let fixedIDs = ["top", "stateContainer", "safety"] + let frames = try fixedIDs.map { try XCTUnwrap(find(controller.view, suffix: $0)).frame } + let oldTitle = model.presentation.title + let oldBattery = find(controller.view, suffix: "metric.battery")?.accessibilityValue + + pause.sendActions(for: .touchUpInside) + pause.sendActions(for: .touchUpInside) + XCTAssertFalse(pause.isEnabled) + XCTAssertFalse(returnHome.isEnabled) + XCTAssertEqual(model.presentation.title, oldTitle) + XCTAssertEqual(find(controller.view, suffix: "metric.battery")?.accessibilityValue, oldBattery) + + try await settle(window) { + model.canSendCommand(.resume) && !model.isSendingCommand + && (pause.accessibilityLabel?.contains("继续") == true) + } + XCTAssertEqual(model.presentation.phase, .paused) + XCTAssertEqual(model.commandResponse?.command, "flighttask_pause") + assertFrames(controller, suffixes: fixedIDs, frames: frames) + capture(window, name: "安全控制-暂停成功-本地模拟") + + pause.sendActions(for: .touchUpInside) + pause.sendActions(for: .touchUpInside) + try await settle(window) { + model.canSendCommand(.pause) && !model.isSendingCommand + && (pause.accessibilityLabel?.contains("暂停") == true) + } + XCTAssertEqual(model.presentation.phase, .shooting) + XCTAssertEqual(model.commandResponse?.command, "flighttask_recovery") + assertFrames(controller, suffixes: fixedIDs, frames: frames) + capture(window, name: "安全控制-继续拍摄-本地模拟") + + let transcript = try await records(controller, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + XCTAssertEqual(entries.compactMap { $0["method"] as? String }, ["GET", "POST", "GET", "POST", "GET"]) + let posts = entries.filter { $0["method"] as? String == "POST" } + XCTAssertEqual(posts.compactMap { $0["path"] as? String }, Array(repeating: "/api/app/airport/command", count: 2)) + let bodies = posts.compactMap { $0["request_body"] as? [String: Any] } + XCTAssertEqual(bodies.compactMap { $0["id"] as? Int }, [901, 901]) + XCTAssertEqual(bodies.compactMap { $0["command"] as? String }, ["flighttask_pause", "flighttask_recovery"]) + for body in bodies { XCTAssertEqual(Set(body.keys), ["id", "command"]) } + } + + /// 返航必须先显示模拟确认,关闭确认不会产生任何指令请求。 + func testReturnConfirmationCanBeCancelledWithoutSendingCommand() async throws { + let controller = try makeController(result: "success") + let window = makeWindow(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.canSendCommand(.returnHome) } + let returnHome = try button(controller, suffix: "return") + returnHome.sendActions(for: .touchUpInside) + returnHome.sendActions(for: .touchUpInside) + try await settle(window) { + controller.presentedViewController is UIAlertController + && controller.presentedViewController?.transitionCoordinator == nil + } + let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController) + XCTAssertEqual(alert.title, "立即返航(本地模拟)") + XCTAssertEqual(alert.actions.compactMap(\.title), ["取消", "模拟返航"]) + XCTAssertFalse(controller.viewModel.isSendingCommand) + XCTAssertNil(controller.viewModel.commandResponse) + capture(window, name: "安全控制-返航确认-本地模拟") + + alert.dismiss(animated: false) + try await settle(window) { controller.presentedViewController == nil } + let transcript = try await records(controller, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + XCTAssertFalse(entries.contains { $0["method"] as? String == "POST" }) + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + } + + /// 明确拒绝保留原任务状态,只在用户再次点击后重发,不创建或召唤新任务。 + func testBusinessFailurePreservesSnapshotAndAllowsExplicitRetry() async throws { + let controller = try makeController(result: "business-failure") + let window = makeWindow(controller) + defer { close(window) } + let model = controller.viewModel + try await settle(window) { model.canSendCommand(.pause) } + let original = model.response + let pause = try button(controller, suffix: "pause") + pause.sendActions(for: .touchUpInside) + try await settle(window) { model.commandErrorMessage != nil && model.canSendCommand(.pause) && pause.isEnabled } + XCTAssertEqual(model.response, original) + XCTAssertFalse(model.commandOutcomeUnknown) + XCTAssertNil(model.commandResponse) + pause.sendActions(for: .touchUpInside) + try await settle(window) { model.commandErrorMessage != nil && model.canSendCommand(.pause) && pause.isEnabled } + let transcript = try await records(controller, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + XCTAssertEqual(entries.compactMap { $0["method"] as? String }, ["GET", "POST", "POST"]) + XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.compactMap { $0["path"] as? String }, + Array(repeating: "/api/app/airport/command", count: 2)) + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + } + + /// 超时保留旧数据并锁定所有安全动作,手动读取及回执查看仍可使用,不能自动重发。 + func testTimeoutLocksSafetyButtonsWhileReadRefreshAndReceiptsRemainAvailable() async throws { + let controller = try makeController(result: "timeout") + let window = makeWindow(controller) + defer { close(window) } + let model = controller.viewModel + try await settle(window) { model.canSendCommand(.pause) } + let original = model.response + let pause = try button(controller, suffix: "pause") + let returnHome = try button(controller, suffix: "return") + pause.sendActions(for: .touchUpInside) + try await settle(window) { model.commandOutcomeUnknown && !model.isSendingCommand } + XCTAssertEqual(model.response, original) + XCTAssertFalse(pause.isEnabled) + XCTAssertFalse(returnHome.isEnabled) + XCTAssertFalse(model.canStartShooting) + XCTAssertFalse(model.canSendCommand(.pause)) + let refresh = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { + $0.accessibilityIdentifier == "drone.task.remote.navigationRefresh" + }) + XCTAssertTrue(refresh.isEnabled) + send(refresh) + try await settle(window) { !model.isLoading && refresh.isEnabled } + XCTAssertTrue(model.commandOutcomeUnknown) + XCTAssertFalse(pause.isEnabled) + XCTAssertFalse(returnHome.isEnabled) + capture(window, name: "安全控制-结果待核对-本地模拟") + let transcript = try await records(controller, window: window) + let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) + XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.count, 1) + XCTAssertEqual(entries.filter { $0["method"] as? String == "GET" }.count, 2) + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + } + + /// 普通入口即使读到可用指令,也因未注入模拟指令服务而保持安全按钮禁用。 + func testReadOnlyEntryKeepsSafetyButtonsDisabledWhenSnapshotOffersCommands() async throws { + let context = DroneDockShootingTaskTestData.context() + let response = try DroneDockShootingTaskTestData.response(changes: [ + "ui": ["phase": "shooting", "title": "拍摄中", "commands": [ + ["command": "flighttask_pause", "label": "紧急暂停"], + ["command": "return_home", "label": "立即返航"] + ]] + ]) + let service = DroneDockShootingTaskTestService(result: .success(response)) + let model = DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: service, currentContext: { context }) + let controller = DroneDockShootingTaskViewController(viewModel: model) + let window = makeWindow(controller) + defer { close(window) } + try await settle(window) { model.response != nil && !model.isLoading } + let pause = try button(controller, suffix: "pause") + let returnHome = try button(controller, suffix: "return") + XCTAssertFalse(pause.isEnabled) + XCTAssertFalse(returnHome.isEnabled) + pause.sendActions(for: .touchUpInside) + returnHome.sendActions(for: .touchUpInside) + XCTAssertNil(controller.presentedViewController) + XCTAssertFalse(model.isSendingCommand) + XCTAssertNil(model.commandResponse) + XCTAssertEqual(service.requests.count, 1) + } + + private func makeController(result: String) throws -> DroneDockShootingTaskViewController { + try XCTUnwrap(DroneDockStartShootSimulation.makeController(arguments: [ + "--dock-command-mock", "--dock-command-result=\(result)" + ]) as? DroneDockShootingTaskViewController) + } + + private func button(_ controller: UIViewController, suffix: String) throws -> UIButton { + try XCTUnwrap(find(controller.view, suffix: suffix) as? UIButton) + } + + private func records(_ controller: UIViewController, window: UIWindow) async throws -> [String: Any] { + let item = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { + $0.accessibilityIdentifier == "drone.task.mock.recordsButton" + }) + XCTAssertTrue(item.isEnabled) + send(item) + try await settle(window) { controller.presentedViewController != nil } + let sheet = try XCTUnwrap(controller.presentedViewController) + let text = try XCTUnwrap(allViews(sheet.view).first { + $0.accessibilityIdentifier == "drone.task.mock.records" + } as? UITextView) + let attachment = XCTAttachment(data: Data(text.text.utf8), uniformTypeIdentifier: "public.json") + attachment.name = "安全控制模拟回执" + attachment.lifetime = .keepAlways + add(attachment) + return try XCTUnwrap(JSONSerialization.jsonObject(with: Data(text.text.utf8)) as? [String: Any]) + } + + private func assertFrames(_ controller: UIViewController, suffixes: [String], frames: [CGRect]) { + for (suffix, frame) in zip(suffixes, frames) { XCTAssertEqual(find(controller.view, suffix: suffix)?.frame, frame) } + } + + private func capture(_ window: UIWindow, name: String) { + window.layoutIfNeeded() + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let attachment = XCTAttachment(image: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } + + private func send(_ item: UIBarButtonItem) { + guard let action = item.action else { return XCTFail("缺少导航操作") } + _ = UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil) + } + + private func makeWindow(_ controller: UIViewController) -> UIWindow { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first + previousKeyWindow = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds + window.overrideUserInterfaceStyle = .light + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + return window + } + + private func close(_ window: UIWindow) { + window.rootViewController?.dismiss(animated: false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + private func settle(_ window: UIWindow, until condition: () -> Bool) async throws { + for _ in 0..<250 { + window.layoutIfNeeded() + if condition() { + try await Task.sleep(nanoseconds: 100_000_000) + window.layoutIfNeeded() + if condition() { return } + } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTFail("本地安全指令页面未在预期时间内完成状态更新") + throw NSError(domain: "DroneDockCommandViewTests", code: 1) + } + + private func find(_ root: UIView, suffix: String) -> UIView? { + allViews(root).first { $0.accessibilityIdentifier == "drone.task.remote.\(suffix)" } + } + + private func allViews(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews($0) } } +} diff --git a/机巢工作台页面接口对接记录.md b/机巢工作台页面接口对接记录.md index 388b5ad..45371b7 100644 --- a/机巢工作台页面接口对接记录.md +++ b/机巢工作台页面接口对接记录.md @@ -1,12 +1,13 @@ # 机巢工作台页面接口对接记录 -> 更新日期:2026-10-29 +> 更新日期:2026-10-30 > **当前禁飞限制(优先于下文历史联调记录):**按用户最新要求,调试不得向真实无人机下发指令。Debug 准备页禁止真实创建和召唤;统一网络层在传输前阻断 `tasks/create`、机场操作请求(包括 `shoot/start-shoot/command/live` 及未确认的新接口)。状态 GET 仅允许已确认的 `home/plane-status/shooting/status`,其中实时采集参数强制为 `live_battery=0` 或 `live_metrics=0`。只有完全不联网的 Mock 传输可以验证原始请求合同。下文任务 6、11 的真实召唤均发生于此限制之前,不作为继续真实联调的授权。 -> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;按用户最新要求,`shooting` 已取消定时轮询,仅在进入页面、页面可见时返回前台或手动刷新时各读取一次同一任务。准备页 `plane-status` 保持轮询。最新 2026-10-29 17:18–17:19 模拟器实操新建任务 11,再以 `{id:11,restart:false}` 召唤;两个接口均成功,绑定飞机 61、航线任务 1931。17:19:04 首次查询允许开始,17:19:59 手动回查已为航线执行失败、禁止拍摄,当前待朱工定位 1931 失败原因与自动派机条件(见 7.7.3)。任务 6 / 航线 1926 的先前失败记录保留。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;`start-shoot` 已实现纯本地模拟(见 7.6.2),真实开拍入口保持禁用;图传、`command` 尚未接入,真实成片上传仍待联调。 +> 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;按用户最新要求,`shooting` 已取消定时轮询,仅在进入页面、页面可见时返回前台或手动刷新时各读取一次同一任务。准备页 `plane-status` 保持轮询。最新 2026-10-29 17:18–17:19 模拟器实操新建任务 11,再以 `{id:11,restart:false}` 召唤;两个接口均成功,绑定飞机 61、航线任务 1931。17:19:04 首次查询允许开始,17:19:59 手动回查已为航线执行失败、禁止拍摄,当前待朱工定位 1931 失败原因与自动派机条件(见 7.7.3)。任务 6 / 航线 1926 的先前失败记录保留。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;`start-shoot` 已实现纯本地模拟(见 7.6.2),真实开拍入口保持禁用;`command` 已实现纯本地模拟(见 7.6.3),真实控制保持禁用;图传尚未接入,真实成片上传仍待联调。 > 用途:记录每个页面实际调用的接口、提供人、调用时机、请求参数和返回 JSON,供 iOS 与后端持续联调。 ## 1. 阅读说明 +- **底部安全控制模拟入口**:`--dock-command-mock` 直接进入模拟拍摄中;支持暂停、继续、返航及取消返航,右上角查看完整请求与回执。只在内存处理,详见 7.6.3。 - **开始拍摄模拟入口**:`--dock-start-shoot-mock`;只使用内存响应,不联网。成功/业务拒绝/超时三种场景与完整回执见第 7.6.2 节。 - **准备到任务的模拟入口**:Debug 真实准备页右上角“本地模拟”,或启动参数 `--dock-preparation-mock`。进入独立模拟准备页后点击“确认并召唤(模拟)”,在内存中完成创建、召唤并带同一任务 ID 跳到模拟任务页;真实提交保护不变。 - **当前模拟调试方式**:`--dock-ui-preparation-preview`、`--dock-ui-task-preview` 使用纯内存演示状态;接口合同用 Mock 响应验证参数、解析、成功/失败和页面切换。模拟结果不能记成真实接口成功。`--dock-*-live` 仍连接真实服务,受 Debug 禁飞保护,不能用于执行飞控。 @@ -24,7 +25,7 @@ ## 2. 页面与接口总览 -当前机巢模块共 **8 个正式页面,已实现 15 个业务接口及 1 个通用 STS 接口**(其中 `start-shoot` 仅启用纯本地模拟)。新增拍摄任务页复用已实现的 `shooting` API,接口总数不增加;它由任务页读取,准备页不直接调用。`shooting` 已取得类型 25 的真实响应;`tasks/create → shoot` 对任务 6 业务成功,但随后回查显示航线执行失败、禁止拍摄。任务页成功导航仍有网络替身测试覆盖;成片保存与 STS 上传流程仍待真实联调。独立订单页复用首页已使用的 `orders`。 +当前机巢模块共 **8 个正式页面,已实现 16 个业务接口及 1 个通用 STS 接口**(其中 `start-shoot`、`command` 仅启用纯本地模拟)。新增拍摄任务页复用已实现的 `shooting` API,接口总数不增加;它由任务页读取,准备页不直接调用。`shooting` 已取得类型 25 的真实响应;`tasks/create → shoot` 对任务 6 业务成功,但随后回查显示航线执行失败、禁止拍摄。任务页成功导航仍有网络替身测试覆盖;成片保存与 STS 上传流程仍待真实联调。独立订单页复用首页已使用的 `orders`。 | 页面/区域 | 提供人 | 方法与完整路径 | 当前状态 | | --- | --- | --- | --- | @@ -41,6 +42,7 @@ | 拍摄准备页:对已创建任务确认并召唤 | 朱工 | `POST /api/app/airport/shoot` | 16:03:31 真实成功,id=6 且省略 plane_id;回执绑定飞机 61、航线任务 1926,业务成功后进入同任务页 | | 拍摄任务页:任务摘要、六项读数与阶段状态 | 朱工 | `GET /api/app/airport/shooting` | 已接入,取消定时轮询;进入、可见时返回前台或手动刷新各读一次;16:04:52 任务 6 的航线执行失败、门禁阻止拍摄 | | 拍摄任务页:开始拍摄 | 朱工 | `POST /api/app/airport/start-shoot` | 已实现纯内存 Mock;真实入口禁用,84 项相关测试通过,见 7.6.2 | +| 拍摄任务页:底部安全控制 | 朱工 | `POST /api/app/airport/command` | 已实现纯内存 Mock;真实入口禁用,暂停/继续/返航/取消返航共用,见 7.6.3 | | 订单素材库:整单摘要与点位标签 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/orders/detail` | 已接入 | | 订单素材库:任务、原素材、成片与点位筛选 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/tasks` | 已接入,不分页 | | 交付成片:订单权限与购买点位 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/orders/detail` | 复用已接入接口 | @@ -48,7 +50,7 @@ | 交付成片:上传凭证 | 既有通用接口,张工文档指定复用 | `GET /api/app/config/get-sts-token` | 已实现,待本页真实上传联调 | | 交付成片:保存或替换成片 | 张工 | `POST /api/yf-handset-app/photog/multi-plane/tasks/film` | 已实现,待真实联调 | -准备页已停用朱工 `workbench`,历史响应保留在第 7.3 节;召唤 `shoot` 见第 7.7 节。订单素材库见第 8 节;交付成片见第 9 节。到达后开始拍摄已通过纯本地模拟,真实入口禁用,见第 7.6.2 节;暂停、返航、批量下载和游客交付确认尚未接入,见第 10 节。 +准备页已停用朱工 `workbench`,历史响应保留在第 7.3 节;召唤 `shoot` 见第 7.7 节。订单素材库见第 8 节;交付成片见第 9 节。到达后开始拍摄已通过纯本地模拟,真实入口禁用,见第 7.6.2 节;暂停/继续/返航/取消返航已支持纯本地模拟,见 7.6.3;批量下载和游客交付确认尚未接入,见第 10 节。 ## 3. 公共约定 @@ -1203,12 +1205,54 @@ HTTP 200,完整业务响应: 客户端仅在已注入开拍服务、最近一次读取成功、就绪状态无冲突、`execute_gate.can_execute=true`、`ui.primary_action=start_shoot`、已绑定正数飞机 ID,且没有进行中/已成功/结果未知的开拍请求时启用按钮。POST 成功并核对任务、订单、景区与飞机身份后,单次 GET 同一任务 `shooting`,不恢复轮询。刷新期间保留旧快照,直到回查成功再更新页面,不把 POST 成功直接当成设备开始拍摄。 -连续点击只发送一次;明确业务拒绝可手动重试,超时、响应无法确认、发送后取消等锁定重复提交,只允许状态回查。页面离开或身份变化后丢弃迟到回执。底部暂停/返航始终不发送请求。 +连续点击只发送一次;明确业务拒绝可手动重试,超时、响应无法确认、发送后取消等锁定重复提交,只允许状态回查。页面离开或身份变化后丢弃迟到回执。底部安全控制的真实请求仍被禁用;2026-10-30 新增纯本地模拟指令流程,见 7.6.3。 2026-10-29 模拟器手动走通 `GET shooting → POST start-shoot → GET shooting`,本地状态由就绪变为拍摄中;全部请求交给 `https://mock.invalid` 对应的内存传输,不会回退真实网络。右上角可查看带 `source=local_mock`、`network_sent=false` 的完整模拟接口记录。 验证:**84 项相关测试全部通过**,涵盖开拍 API 10、开拍 ViewModel 12、模拟页面 3、原任务 ViewModel 16、原任务页面 15、阶段展示 14、固定布局 8、禁飞保护 6。成功、业务拒绝、超时、重复点击、身份核对、离页取消及真实传输前阻断均有覆盖。调试参数、[完整三次请求回执与截图](docs/9.9.1/start-shoot-mock-2026-10-29/README.md) 已保存;后端接收和真实设备执行尚未验证。 +### 7.6.3 底部安全控制:朱工 command(仅本地模拟) + +`POST /api/app/airport/command`,请求只有原订单飞行任务 `id` 与 `command`,不传飞机 ID、机场 SN 或自行定义的 `dry_run`。 + +| 按钮 | command | +| --- | --- | +| 紧急暂停 | `flighttask_pause` | +| 继续拍摄 | `flighttask_recovery` | +| 立即返航 | `return_home` | +| 取消返航 | `return_home_cancel` | + +模拟暂停请求: + +```json +{"id":901,"command":"flighttask_pause"} +``` + +模拟响应的 data 结构(非后端真实返回): + +```json +{ + "order_flight_task_id": 901, + "command": "flighttask_pause", + "airport_sn": "LOCAL-MOCK-DOCK-201", + "dji_status": "paused", + "metrics": [ + {"key":"battery","value":"95%"}, + {"key":"env_temp","value":"20.3℃"}, + {"key":"wind_speed","value":"0m/s"}, + {"key":"rainfall","value":"无雨"}, + {"key":"signal","value":"良好"}, + {"key":"satellite","value":"36颗"} + ] +} +``` + +当前正式入口不注入指令服务;Debug 网络层继续拦截所有真实 command。模拟页仅在快照 `ui.commands` 明确给出白名单指令、任务及锁定飞机有效时启用;不将开拍 `execute_gate.can_execute` 当成暂停/返航许可。回执必须回显同一任务和指令,成功后只 GET 同一任务一次;无轮询,不用受理回执直接替代状态快照。 + +提交期间按钮互斥并保留旧 UI。明确拒绝可手动重试;超时、异常回执、发出后取消等结果未知时锁定控制操作,仍可手动只读刷新。迟滞快照下已受理的同项指令不会重发;账号/景区变化时拒绝旧响应。返航前确认;模拟返航按文档标记任务中断,取消返航也不会恢复任务、重新创建或自动开拍。 + +详细场景、模拟器截图与完整回执见 [安全控制模拟记录](docs/9.9.1/safety-command-mock-2026-10-30/README.md)。当前仅验证客户端请求合同与交互;尚无后端真实指令受理或设备执行证据。 + ### 7.7 “确认并召唤”:朱工 shoot,复用已创建任务 API:[DroneDockShootAPI.swift](suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift) @@ -1563,7 +1607,7 @@ GET /api/yf-handset-app/photog/multi-plane/tasks?scenic_id=271&order_number=TEST | 页面/功能 | 当前实现状态 | 文档中的后续候选接口与提供人 | 返回 JSON 记录 | | --- | --- | --- | --- | | 历史演示订单页 `DroneShootingOrdersViewController` | 仅演示流程继续使用本地数据;正式首页“查看全部”已进入真实 `DroneDockOrdersViewController` | 正式页张工 `GET /orders` 已接入,见 4.4 | 演示数据不能作为接口实测证据 | -| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台或导航栏/中间刷新各只读一次,无下拉刷新或定时轮询;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;`/airport/start-shoot` 已实现纯本地模拟、真实入口禁用;图传 `/airport/live`、控制 `/airport/command` 尚未接入,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;开始拍摄模拟回执见 7.6.2;尚无真实开始拍摄或控制成功记录 | +| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台或导航栏/中间刷新各只读一次,无下拉刷新或定时轮询;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;`/airport/start-shoot` 已实现纯本地模拟、真实入口禁用;`/airport/command` 已实现纯本地模拟、真实入口禁用;图传 `/airport/live` 尚未接入,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;开始拍摄模拟回执见 7.6.2;尚无真实开始拍摄或控制成功记录 | | 历史素材演示/下载 `DroneMaterialsViewController`、`DroneMaterialPreviewViewController` | 仅演示流程保留;正式入口已切换真实素材库,尚未接入批量下载或保存相册 | 下载可使用张工返回的有效文件 URL;当前正式页面只支持查看与预览 | 正式页面响应见第 8 节 | | 历史交付演示 `DroneDeliveryUploadViewController`、`DroneDeliveryReviewViewController` | 仅演示流程保留;正式上传使用第 9 节新共用页,游客确认尚未接入 | 后续张工 `POST /orders/confirm-code`、`GET /orders/detail` | 正式上传记录见第 9 节;暂无游客确认实测响应 | | 收款页“线下收款” | 跳转既有 `OfflineCollectionRegistrationViewController` | 复用原通用线下收款模块,不属于本次机巢类型 25 专用接口接入 | 本文未审计该旧模块 JSON,不将它记为新接口已打通 |