diff --git a/AGENTS.md b/AGENTS.md index 15ebf9e..966d7c0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,9 +86,15 @@ Swift · UIKit · SnapKit(代码布局,约束写在 `setupUI()` / `setupCons - 以 Android 工程为功能参考,命令式 UIKit,不用 Observable / Combine - 新增功能必测、类型与公开 API 必注释、保持简洁 +## 景区空境库接口范围(2026-10-30 用户确认) + +- App 只负责获取、查看景区素材,以及下载并保存相册,不负责上传。 +- `/api/app/scenic-media/retry-upload` 和 `/api/app/scenic-media/retry-failed` 不需要对接;后续接口盘点不再列为未接入或待调试项。 +- 页面上的下载失败重试仅重试文件下载与相册保存,不调用上述上传重试接口。此约定只适用于景区空境库。 + ## 当前禁飞调试限制(2026-10-29 用户要求) -- 当前无人机禁止飞行。调试只能模拟,禁止向真实无人机下发任何指令;模拟器、测试账号、测试环境都不代表模拟设备。 +- 当前无人机禁止飞行(用户于 2026-10-30 再次确认)。调试只能模拟,禁止向真实无人机下发任何指令;模拟器、测试账号、测试环境都不代表模拟设备。本次图传和重新召唤接入不解除禁飞限制。 - 不通过 App、curl、脚本、浏览器或其他工具真实调用 `airport/shoot`、`airport/start-shoot`、`airport/command`,也不启动实时图传或尝试未确认的设备操作接口。暂停、恢复、返航同样属于设备指令。 - 创建、召唤、拍摄、失败和返航流程使用纯内存演示或 Mock 响应;必须标明模拟来源,不能把模拟结果记为后端真实成功。不为流程验证创建真实待飞任务。 - 可继续调试已确认只读的订单、项目、素材及状态接口;`plane-status/shooting` 使用 `live_battery=0`,`status` 使用 `live_metrics=0`,不主动请求设备实时采集。 diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/README.md b/docs/9.9.1/live-resummon-mock-2026-10-30/README.md new file mode 100644 index 0000000..82a7eab --- /dev/null +++ b/docs/9.9.1/live-resummon-mock-2026-10-30/README.md @@ -0,0 +1,52 @@ +# 实时图传与重新召唤:本地模拟验证 + +日期:2026-10-30。iPhone 17 Pro / iOS 27 模拟器。 + +**用户再次确认当前禁飞。本目录全部接口回执为纯内存 Mock,`network_sent=false`;没有真实调用 `live/shoot`,没有创建真实待飞任务,也没有连接无人机。视频来自随包 `drone_material_demo.mp4`。** + +## 当前实现 + +- `DroneDockLiveAPI`:`GET /api/app/airport/live?id=901`,解析现有文档字段、校验原订单任务身份。文档缺少播放协议及参数,不能据此建立真实图传。 +- 图传区域支持加载、失败、缺参数与本地样片;注入本地文件后始终显示“本地模拟画面 · 未连接无人机”,离页或后台释放播放器;无定时轮询。正式入口不注入图传服务。 +- `DroneDockShootAPI.resummon`:只发送 `{"id":901,"restart":true}`,不创建新任务、不传 `plane_id` 或覆盖航线。 +- 重召唤成功后仅 `GET shooting` 一次,由同任务的新快照更新页面;在途保持旧读数和固定布局。连点防重、拒绝可手动重试,超时/取消/异常回执只允许核对,旧失败快照不会使同一请求重发。正式入口不注入重召唤服务。 +- 原 `DeviceCommandDebugPolicy` 未改动,所有真实 `live/shoot/start-shoot/command` 仍在网络发送前拦截,无运行时放行开关。 + +## 启动方式 + +| 模拟场景 | 启动参数 | +| --- | --- | +| 失败后重新召唤 | `--dock-resummon-mock` | +| 拒绝/超时 | 加 `--dock-resummon-result=business-failure` 或 `timeout` | +| 图传本地视频 | `--dock-live-mock` | +| 缺参数/拒绝/超时 | 加 `--dock-live-result=missing-parameters`、`business-failure` 或 `timeout` | +| 同页验证两个功能 | `--dock-resummon-mock --dock-live-mock` | + +这些参数只选择完全隔离的本地会话,不能解锁真实请求。 + +## 验证结果 + +累计 **168 个不同相关用例已取得通过结果**,涵盖新增 API、ViewModel、UI、现有开拍/控制、固定布局与禁飞保护。首轮 165/168 通过,3 个新 UI 用例误定位到隐藏的普通主按钮;改用失败页 `failureRetry` 后,相关 UI、固定布局和既有交互 **38 项复跑全部通过,0 失败、0 跳过**。最终模拟器构建通过,`git diff --check` 通过。 + +- 首轮结果包:`test_sim_2026-10-30T10-12-51-905Z_pid29946_b56e8f3b.xcresult`。 +- 复跑结果包:`test_sim_2026-10-30T10-15-15-960Z_pid29946_11613c70.xcresult`。 +- 下表 JSON 和缺参数截图导出自复跑用例附件;每份 JSON 都明确标记 `source=local_mock`、`network_sent=false`。 +- 最终手动验证使用两个模拟启动参数:图传显示本地样片;点击失败页重召唤,原任务回查后展示“无人机已到达(模拟)”。未点击真实入口、未向网络转发。 + +| 场景 | 完整模拟回执 | +| --- | --- | +| 同一任务重召唤成功,单次 POST 后查询 | [resummon-success.mock.json](resummon-success.mock.json) | +| 明确拒绝后手动再试 | [resummon-rejected.mock.json](resummon-rejected.mock.json) | +| 超时后只读回查,不重复 POST | [resummon-timeout.mock.json](resummon-timeout.mock.json) | +| 图传已知字段 + 独立本地视频注入 | [live-success.mock.json](live-success.mock.json) | +| 仅文档现有字段,提示缺少播放参数 | [live-missing-parameters.json](live-missing-parameters.json) | +| 图传明确拒绝 | [live-rejected.mock.json](live-rejected.mock.json) | +| 图传超时 | [live-timeout.mock.json](live-timeout.mock.json) | + +| 失败页与本地画面 | 重召唤后同任务状态 | 缺少真实播放参数 | +| --- | --- | --- | +| ![失败页与本地画面](before-resummon-local.jpg) | ![模拟重召唤回查](after-resummon-local.jpg) | ![缺少图传参数](live-missing-parameters.png) | + +## 后端待确认 + +可直接转发工程根目录 [朱工-实时图传与重新召唤接口确认.md](../../../朱工-实时图传与重新召唤接口确认.md)。真实图传播放协议、凭证生命周期,以及重召唤权限、重启和幂等语义仍待补齐。本地验证不替代后端或真实设备验收,禁飞限制继续生效。 diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/after-resummon-local.jpg b/docs/9.9.1/live-resummon-mock-2026-10-30/after-resummon-local.jpg new file mode 100644 index 0000000..4561980 Binary files /dev/null and b/docs/9.9.1/live-resummon-mock-2026-10-30/after-resummon-local.jpg differ diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/before-resummon-local.jpg b/docs/9.9.1/live-resummon-mock-2026-10-30/before-resummon-local.jpg new file mode 100644 index 0000000..042a648 Binary files /dev/null and b/docs/9.9.1/live-resummon-mock-2026-10-30/before-resummon-local.jpg differ diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/live-missing-parameters.json b/docs/9.9.1/live-resummon-mock-2026-10-30/live-missing-parameters.json new file mode 100644 index 0000000..6be92c2 --- /dev/null +++ b/docs/9.9.1/live-resummon-mock-2026-10-30/live-missing-parameters.json @@ -0,0 +1,177 @@ +{ + "command_scenario" : "success", + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : true, + "code" : "ok", + "message" : "本地模拟:允许验证开拍请求", + "primary_action" : "start_shoot", + "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" : "arrived_pending_start", + "title" : "无人机已到达(模拟)" + } + }, + "msg" : "local mock success" + } + }, + { + "http_status" : 200, + "method" : "GET", + "path" : "/api/app/airport/live", + "query" : "id=901", + "response_body" : { + "code" : 100000, + "data" : { + "airport" : { + + }, + "airport_sn" : "LOCAL-MOCK-DOCK-201", + "drone" : { + + }, + "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, + "task" : { + "id" : 901, + "order_number" : "LOCAL-MOCK-ORDER-901", + "scenic_id" : 128, + "status" : 20, + "status_label" : "执行中(模拟)", + "wayline_status" : 20, + "wayline_status_label" : "执行中(模拟)" + } + }, + "msg" : "local mock success" + } + } + ], + "scenario" : "success", + "source" : "local_mock" +} \ No newline at end of file diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/live-missing-parameters.png b/docs/9.9.1/live-resummon-mock-2026-10-30/live-missing-parameters.png new file mode 100644 index 0000000..5d8a823 Binary files /dev/null and b/docs/9.9.1/live-resummon-mock-2026-10-30/live-missing-parameters.png differ diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/live-rejected.mock.json b/docs/9.9.1/live-resummon-mock-2026-10-30/live-rejected.mock.json new file mode 100644 index 0000000..d59406e --- /dev/null +++ b/docs/9.9.1/live-resummon-mock-2026-10-30/live-rejected.mock.json @@ -0,0 +1,148 @@ +{ + "command_scenario" : "success", + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : true, + "code" : "ok", + "message" : "本地模拟:允许验证开拍请求", + "primary_action" : "start_shoot", + "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" : "arrived_pending_start", + "title" : "无人机已到达(模拟)" + } + }, + "msg" : "local mock success" + } + }, + { + "http_status" : 200, + "method" : "GET", + "path" : "/api/app/airport/live", + "query" : "id=901", + "response_body" : { + "code" : 100099, + "data" : { + + }, + "msg" : "本地模拟:图传连接不可用" + } + }, + { + "http_status" : 200, + "method" : "GET", + "path" : "/api/app/airport/live", + "query" : "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/live-resummon-mock-2026-10-30/live-success.mock.json b/docs/9.9.1/live-resummon-mock-2026-10-30/live-success.mock.json new file mode 100644 index 0000000..6be92c2 --- /dev/null +++ b/docs/9.9.1/live-resummon-mock-2026-10-30/live-success.mock.json @@ -0,0 +1,177 @@ +{ + "command_scenario" : "success", + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : true, + "code" : "ok", + "message" : "本地模拟:允许验证开拍请求", + "primary_action" : "start_shoot", + "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" : "arrived_pending_start", + "title" : "无人机已到达(模拟)" + } + }, + "msg" : "local mock success" + } + }, + { + "http_status" : 200, + "method" : "GET", + "path" : "/api/app/airport/live", + "query" : "id=901", + "response_body" : { + "code" : 100000, + "data" : { + "airport" : { + + }, + "airport_sn" : "LOCAL-MOCK-DOCK-201", + "drone" : { + + }, + "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, + "task" : { + "id" : 901, + "order_number" : "LOCAL-MOCK-ORDER-901", + "scenic_id" : 128, + "status" : 20, + "status_label" : "执行中(模拟)", + "wayline_status" : 20, + "wayline_status_label" : "执行中(模拟)" + } + }, + "msg" : "local mock success" + } + } + ], + "scenario" : "success", + "source" : "local_mock" +} \ No newline at end of file diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/live-timeout.mock.json b/docs/9.9.1/live-resummon-mock-2026-10-30/live-timeout.mock.json new file mode 100644 index 0000000..e26dfde --- /dev/null +++ b/docs/9.9.1/live-resummon-mock-2026-10-30/live-timeout.mock.json @@ -0,0 +1,134 @@ +{ + "command_scenario" : "success", + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : true, + "code" : "ok", + "message" : "本地模拟:允许验证开拍请求", + "primary_action" : "start_shoot", + "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" : "arrived_pending_start", + "title" : "无人机已到达(模拟)" + } + }, + "msg" : "local mock success" + } + }, + { + "error" : "未能完成操作。(NSURLErrorDomain错误-1001。)", + "method" : "GET", + "path" : "/api/app/airport/live", + "query" : "id=901" + }, + { + "error" : "未能完成操作。(NSURLErrorDomain错误-1001。)", + "method" : "GET", + "path" : "/api/app/airport/live", + "query" : "id=901" + } + ], + "scenario" : "success", + "source" : "local_mock" +} \ No newline at end of file diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-rejected.mock.json b/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-rejected.mock.json new file mode 100644 index 0000000..e9cfc1d --- /dev/null +++ b/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-rejected.mock.json @@ -0,0 +1,147 @@ +{ + "command_scenario" : "success", + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : false, + "code" : "ok", + "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_message" : "本地模拟:航线执行失败,无人机空闲待命。", + "scenic_id" : 128, + "status" : 40, + "status_label" : "任务失败(模拟)", + "wayline_status" : 91, + "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_message" : "本地模拟:航线执行失败,无人机空闲待命。", + "scenic_id" : 128, + "status" : 40, + "status_label" : "任务失败(模拟)", + "wayline_status" : 91, + "wayline_status_label" : "执行失败(模拟)" + }, + "ui" : { + "commands" : [ + + ], + "message" : "本地模拟状态回查,未向设备发送指令。", + "phase" : "failed", + "title" : "本地模拟:航线执行失败,可验证重新召唤流程" + } + }, + "msg" : "local mock success" + } + }, + { + "http_status" : 200, + "method" : "POST", + "path" : "/api/app/airport/shoot", + "request_body" : { + "id" : 901, + "restart" : true + }, + "response_body" : { + "code" : 100099, + "data" : { + + }, + "msg" : "本地模拟:设备暂不可用,重新召唤被拒绝" + } + }, + { + "http_status" : 200, + "method" : "POST", + "path" : "/api/app/airport/shoot", + "request_body" : { + "id" : 901, + "restart" : true + }, + "response_body" : { + "code" : 100099, + "data" : { + + }, + "msg" : "本地模拟:设备暂不可用,重新召唤被拒绝" + } + } + ], + "scenario" : "success", + "source" : "local_mock" +} \ No newline at end of file diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-success.mock.json b/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-success.mock.json new file mode 100644 index 0000000..7a5b55e --- /dev/null +++ b/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-success.mock.json @@ -0,0 +1,261 @@ +{ + "command_scenario" : "success", + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : false, + "code" : "ok", + "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_message" : "本地模拟:航线执行失败,无人机空闲待命。", + "scenic_id" : 128, + "status" : 40, + "status_label" : "任务失败(模拟)", + "wayline_status" : 91, + "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_message" : "本地模拟:航线执行失败,无人机空闲待命。", + "scenic_id" : 128, + "status" : 40, + "status_label" : "任务失败(模拟)", + "wayline_status" : 91, + "wayline_status_label" : "执行失败(模拟)" + }, + "ui" : { + "commands" : [ + + ], + "message" : "本地模拟状态回查,未向设备发送指令。", + "phase" : "failed", + "title" : "本地模拟:航线执行失败,可验证重新召唤流程" + } + }, + "msg" : "local mock success" + } + }, + { + "http_status" : 200, + "method" : "POST", + "path" : "/api/app/airport/shoot", + "request_body" : { + "id" : 901, + "restart" : true + }, + "response_body" : { + "code" : 100000, + "data" : { + "airport_sn" : "LOCAL-MOCK-DOCK-201", + "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_flight_task_id" : 901, + "plane_id" : 201, + "task_uuid" : "LOCAL-MOCK-TASK-UUID-901", + "ui" : { + "message" : "本地模拟召唤成功,没有网络或设备指令。", + "phase" : "arrived_pending_start", + "title" : "无人机已到达(模拟)" + } + }, + "msg" : "local mock success" + } + }, + { + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : true, + "code" : "ok", + "message" : "本地模拟:允许验证开拍请求", + "primary_action" : "start_shoot", + "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" : "arrived_pending_start", + "title" : "无人机已到达(模拟)" + } + }, + "msg" : "local mock success" + } + } + ], + "scenario" : "success", + "source" : "local_mock" +} \ No newline at end of file diff --git a/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-timeout.mock.json b/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-timeout.mock.json new file mode 100644 index 0000000..2a829f0 --- /dev/null +++ b/docs/9.9.1/live-resummon-mock-2026-10-30/resummon-timeout.mock.json @@ -0,0 +1,230 @@ +{ + "command_scenario" : "success", + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : false, + "code" : "ok", + "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_message" : "本地模拟:航线执行失败,无人机空闲待命。", + "scenic_id" : 128, + "status" : 40, + "status_label" : "任务失败(模拟)", + "wayline_status" : 91, + "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_message" : "本地模拟:航线执行失败,无人机空闲待命。", + "scenic_id" : 128, + "status" : 40, + "status_label" : "任务失败(模拟)", + "wayline_status" : 91, + "wayline_status_label" : "执行失败(模拟)" + }, + "ui" : { + "commands" : [ + + ], + "message" : "本地模拟状态回查,未向设备发送指令。", + "phase" : "failed", + "title" : "本地模拟:航线执行失败,可验证重新召唤流程" + } + }, + "msg" : "local mock success" + } + }, + { + "error" : "未能完成操作。(NSURLErrorDomain错误-1001。)", + "method" : "POST", + "path" : "/api/app/airport/shoot", + "request_body" : { + "id" : 901, + "restart" : true + } + }, + { + "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" : 1, + "work_status_label" : "空闲" + }, + "execute_gate" : { + "can_execute" : false, + "code" : "ok", + "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_message" : "本地模拟:航线执行失败,无人机空闲待命。", + "scenic_id" : 128, + "status" : 40, + "status_label" : "任务失败(模拟)", + "wayline_status" : 91, + "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_message" : "本地模拟:航线执行失败,无人机空闲待命。", + "scenic_id" : 128, + "status" : 40, + "status_label" : "任务失败(模拟)", + "wayline_status" : 91, + "wayline_status_label" : "执行失败(模拟)" + }, + "ui" : { + "commands" : [ + + ], + "message" : "本地模拟状态回查,未向设备发送指令。", + "phase" : "failed", + "title" : "本地模拟:航线执行失败,可验证重新召唤流程" + } + }, + "msg" : "local mock success" + } + } + ], + "scenario" : "success", + "source" : "local_mock" +} \ No newline at end of file diff --git a/docs/9.9.1/景区空镜库UI实现说明.md b/docs/9.9.1/景区空镜库UI实现说明.md index fc0dd0b..5bf0d3e 100644 --- a/docs/9.9.1/景区空镜库UI实现说明.md +++ b/docs/9.9.1/景区空镜库UI实现说明.md @@ -2,7 +2,21 @@ 实现日期:2026-10-26。分支:`dev_9_9_1`。 -## 2026-10-29 接口接入进度 +## 2026-10-30 当前范围与接入状态 + +按用户确认,景区空境库 App 只负责获取、查看和下载素材并保存相册。素材上传、单条重试上传、整单重试上传均不属于本模块需求,不列为待接入功能。 + +| 用途 | 调用方式 | 状态 | +| --- | --- | --- | +| 素材场次列表、航线/日期筛选、分页 | 朱工 `GET /api/app/scenic-media/sessions` | 已接入;航线筛选项取 `filter_options.air_lines` | +| 场次详情与片段地址 | 朱工 `GET /api/app/scenic-media/session-detail` | 已接入,使用 `scenic_media_id` | +| 下载并保存相册 | 对返回的 `oss_url` 直接 GET,再写入系统相册 | 已接入,保存成功才计为完成;支持暂停、继续及下载失败重试 | + +用户明确确认:`/api/app/scenic-media/retry-upload` 和 `/api/app/scenic-media/retry-failed` 不需要对接,后续接口盘点不再列为未接入或待调试项。当前正式页面没有上传入口,也不调用 `mark-download`。界面的“重试失败”仅重试下载失败的素材。 + +非空场次、详情映射、筛选、分页和预览已完成接入,并已有真实非空响应记录;下文 10 月 29 日“待非空映射”的描述仅保留为历史。景区真实业务视频下载并保存相册的完整实测仍待验证,不将本地演示或替身测试写成真实业务成功。 + +## 2026-10-29 接口接入进度(历史记录) - 正式入口为 `sceniclibrary`,使用当前账号和景区,进入后请求 `GET /api/app/scenic-media/sessions`。列表支持加载、空态、下拉刷新、错误重试及日期参数;正式入口不会生成演示素材。 - 依据朱工《随心瞰9.9.1-App机巢与素材库接口.md》接入列表和 `session-detail?scenic_media_id=...` 只读 API。测试环境实测沿用 `token` 请求头和 `code=100000/msg` 包装,而非文档示意的 `code=0/message`。保留期上限实测为 365 天。 diff --git a/suixinkan/Features/DroneDock/API/DroneDockLiveAPI.swift b/suixinkan/Features/DroneDock/API/DroneDockLiveAPI.swift new file mode 100644 index 0000000..a906adf --- /dev/null +++ b/suixinkan/Features/DroneDock/API/DroneDockLiveAPI.swift @@ -0,0 +1,31 @@ +import Foundation + +/// 朱工任务图传参数服务;请求可能启动设备图传,禁飞期间只允许隔离模拟注入。 +protocol DroneDockLiveServing: Sendable { + /// 读取同一订单飞行任务的图传回执,不创建任务或更换飞机。 + @MainActor + func live(taskID: Int) async throws -> DroneDockLiveResponse +} + +/// 按已提供的 live 合同发送请求;不猜测 RTC 厂商、播放地址或连接凭证。 +@MainActor +final class DroneDockLiveAPI: DroneDockLiveServing { + private let client: APIClient + + /// 注入统一客户端,保留 Debug 禁飞阻断与纯内存测试传输。 + init(client: APIClient) { self.client = client } + + /// 只发送一次 GET,请求失败不自动重试或发出其他设备请求。 + func live(taskID: Int) async throws -> DroneDockLiveResponse { + try Task.checkCancellation() + guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID") } + let value: DroneDockLiveResponse = try await client.send(APIRequest( + method: .get, path: "/api/app/airport/live", + queryItems: [URLQueryItem(name: "id", value: String(taskID))] + )) + guard value.orderFlightTaskID == taskID, value.task?.id == nil || value.task?.id == taskID else { + throw APIError.decodeFailed("图传回执与当前拍摄任务不一致") + } + return value + } +} diff --git a/suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift b/suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift index 9a8aaf3..e2ffc0b 100644 --- a/suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift +++ b/suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift @@ -7,9 +7,16 @@ protocol DroneDockShootServing: Sendable { func shoot(taskID: Int) async throws -> DroneDockShootResponse } +/// 为已有失败任务提交重新召唤,不创建新任务或更换锁定飞机。 +protocol DroneDockResummonServing: Sendable { + /// 发送一次 restart=true 的召唤请求,调用方负责防重及受理后的状态核对。 + @MainActor + func resummon(taskID: Int) async throws -> DroneDockShootResponse +} + /// 朱工 shoot 接口适配,业务成功仅表示接口受理结果,不推断飞机已经到达。 @MainActor -final class DroneDockShootAPI: DroneDockShootServing { +final class DroneDockShootAPI: DroneDockShootServing, DroneDockResummonServing { private let client: APIClient /// 注入统一网络客户端,沿用登录凭证、HTTP 与业务码处理。 @@ -17,13 +24,22 @@ final class DroneDockShootAPI: DroneDockShootServing { /// 仅发送一次召唤 POST;不创建任务、不重试、不修改任务已选航线。 func shoot(taskID: Int) async throws -> DroneDockShootResponse { + try await send(taskID: taskID, restart: false) + } + + /// 复用同一订单飞行任务请求重启;当前仅由隔离模拟入口注入,真实传输仍受禁飞保护。 + func resummon(taskID: Int) async throws -> DroneDockShootResponse { + try await send(taskID: taskID, restart: true) + } + + private func send(taskID: Int, restart: Bool) async throws -> DroneDockShootResponse { try Task.checkCancellation() guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请先创建任务") } do { return try await client.send(APIRequest( method: .post, path: "/api/app/airport/shoot", - body: ShootBody(taskID: taskID) + body: ShootBody(taskID: taskID, restart: restart) )) } catch APIError.emptyData { // 统一客户端仅在 HTTP 和业务码均成功后抛 emptyData;此接口尚未约定成功 data 结构。 @@ -31,10 +47,10 @@ final class DroneDockShootAPI: DroneDockShootServing { } } - /// 本轮联调仅发送任务身份和非重启标记,完全省略 plane_id 与航线覆盖字段。 + /// 仅发送任务身份和重启标记,完全省略 plane_id 与航线覆盖字段。 private struct ShootBody: Encodable { let taskID: Int - let restart = false + let restart: Bool /// 朱工已建任务召唤参数映射。 private enum CodingKeys: String, CodingKey { diff --git a/suixinkan/Features/DroneDock/Models/DroneDockLiveModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockLiveModels.swift new file mode 100644 index 0000000..ab79bb8 --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneDockLiveModels.swift @@ -0,0 +1,68 @@ +import Foundation + +/// live 文档已明确的任务与设备回执;当前合同没有可用于播放的字段。 +struct DroneDockLiveResponse: Decodable, Equatable, Sendable { + /// 后端回显的订单飞行任务 ID,不能用请求值补齐。 + let orderFlightTaskID: Int + /// 设备明细尚未定义字段,保留原 JSON 类型。 + let airport: DroneDockHomeJSONValue? + /// 无人机明细尚未定义字段,保留原 JSON 类型。 + let drone: DroneDockHomeJSONValue? + /// 文档中的任务摘要,若提供身份必须与顶层任务一致。 + let task: DroneDockShootingTaskIdentity? + /// 已锁定机场序列号,不用于客户端选择或重新绑定设备。 + let airportSN: String? + /// 随接口返回的展示读数,不触发额外实时采集。 + let metrics: [DroneDockHomeMetric] + /// 完整回执,包含尚未建模字段,不解释成播放器配置。 + let dataJSON: String + + /// live 文档中的已知字段映射。 + private enum CodingKeys: String, CodingKey { + case orderFlightTaskID = "order_flight_task_id", airport, drone, task + case airportSN = "airport_sn", metrics + } + + /// 任务 ID 必须明确提供;未知字段及 null 留在完整 JSON 中供后续合同核对。 + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + orderFlightTaskID = try container.decode(Int.self, forKey: .orderFlightTaskID) + airport = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .airport) + drone = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .drone) + task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task) + airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN) + 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(DroneDockLiveJSONSnapshot(value: raw)), as: UTF8.self) + } +} + +/// 只负责原样编码解码所得的 JSON,不追加猜测的流媒体参数。 +private struct DroneDockLiveJSONSnapshot: Encodable { + let value: DroneDockHomeJSONValue + + /// 保持字典、数组、空值、数值与字符串的原始类型。 + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch value { + case .object(let value): try container.encode(value.mapValues { Self(value: $0) }) + case .array(let value): try container.encode(value.map { Self(value: $0) }) + case .string(let value): try container.encode(value) + case .number(let value): try container.encode(value) + case .bool(let value): try container.encode(value) + case .null: try container.encodeNil() + } + } +} + +/// 图传区域的明确状态;本地视频预览不代表设备连接或真实图传成功。 +enum DroneDockLiveState: Equatable, Sendable { + case restricted + case idle + case loading + case unavailable(String) + case failed(String) + case localPreview(URL) +} diff --git a/suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift index c3ab8c1..7c46d50 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift @@ -17,6 +17,36 @@ struct DroneDockShootResponse: Decodable, Equatable, Sendable { } } +/// 重新召唤回执中可核对的订单任务身份;顶层 task_id 属于实际航线任务,不作订单任务 ID 使用。 +struct DroneDockResummonReceiptIdentity: Decodable, Sendable { + /// 后端明确回显的订单飞行任务 ID,缺失时由后续 shooting 核对。 + let orderFlightTaskID: Int? + /// 后端已提供的订单任务摘要身份。 + let orderFlightTask: TaskIdentity? + /// 已锁定任务的飞机 ID;实际提供时核对是否仍为原任务飞机。 + let planeID: Int? + + /// 只读取已约定的订单任务身份字段。 + private enum CodingKeys: String, CodingKey { + case orderFlightTaskID = "order_flight_task_id", orderFlightTask = "order_flight_task", planeID = "plane_id" + } + + /// 嵌套订单任务的可选身份字段,不读取或推断设备执行阶段。 + struct TaskIdentity: Decodable, Sendable { + /// 原订单飞行任务 ID。 + let id: Int? + /// 任务所属订单。 + let orderNumber: String? + /// 任务所属景区。 + let scenicID: Int? + + /// 订单任务摘要字段映射。 + private enum CodingKeys: String, CodingKey { + case id, orderNumber = "order_number", scenicID = "scenic_id" + } + } +} + /// 将现有 JSON 值解码结果格式化,完整保留 shoot 尚未约定的成功数据结构。 private struct DroneDockShootJSONSnapshot: Encodable { let value: DroneDockHomeJSONValue diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockLiveViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockLiveViewModel.swift new file mode 100644 index 0000000..5df7338 --- /dev/null +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockLiveViewModel.swift @@ -0,0 +1,146 @@ +import Foundation + +/// 任务图传区域的单次请求与生命周期;正式入口不注入操作服务,模拟来源单独注入。 +final class DroneDockLiveViewModel { + /// 当前图传所属的账号、景区与门店范围。 + let context: DroneDockHomeContext + /// 固定订单飞行任务身份。 + let taskID: Int + /// 最近一次通过身份核对的图传回执,不用作实时播放配置。 + private(set) var response: DroneDockLiveResponse? + /// 图传区域当前可展示状态。 + private(set) var state: DroneDockLiveState + /// 请求期间阻止重复获取,不安排定时轮询。 + private(set) var isLoading = false + + private let service: (any DroneDockLiveServing)? + private let localPreviewURL: URL? + private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext + private var generation = 0 + private var identityInvalidated = false + + /// 本地素材仅供明确的模拟入口注入,后端 JSON 不能生成此 URL。 + init(context: DroneDockHomeContext, taskID: Int, service: (any DroneDockLiveServing)? = nil, + localPreviewURL: URL? = nil, + currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { + self.context = context + self.taskID = taskID + self.service = service + self.localPreviewURL = localPreviewURL + self.currentContext = currentContext + state = service == nil ? .restricted : .idle + } + + /// 仅有明确注入服务且身份有效时允许发起请求;正式禁飞入口始终为 false。 + var canLoad: Bool { service != nil && !isLoading && !identityInvalidated && context.canLoad && taskID > 0 } + + /// 仅返回明确注入且已经过本地文件检查的模拟视频,不使用后端未定义字段。 + var playbackURL: URL? { + if case .localPreview(let url) = state { return url } + return nil + } + + /// 图传区域主文案,不把接口受理视为设备连接成功。 + var title: String { + switch state { + case .restricted: return "当前调试已停用实时图传" + case .idle: return "实时图传" + case .loading: return "正在获取图传信息" + case .unavailable: return "图传暂不可用" + case .failed: return "图传加载失败" + case .localPreview: return "本地模拟画面" + } + } + + /// 缺失协议时说明真实限制,不给示例视频贴上实时来源。 + var message: String { + switch state { + case .restricted: return "禁飞调试期间不启动设备图传" + case .idle: return "按当前任务获取图传信息" + case .loading: return "请稍候" + case .unavailable(let reason), .failed(let reason): return reason + case .localPreview: return "仅播放本地样片,未连接无人机" + } + } + + /// 操作名称跟随当前阶段,模拟来源始终显式标记。 + var actionTitle: String? { + guard service != nil else { return nil } + if isLoading { return "正在加载…" } + switch state { + case .restricted: return nil + case .idle: return localPreviewURL == nil ? "获取图传信息" : "查看模拟图传" + case .loading: return "正在加载…" + case .failed, .unavailable: return "重试" + case .localPreview: return "重新加载模拟图传" + } + } + + /// 发起一次图传请求,拒绝重复点击、迟到响应、身份不符及远程模拟视频来源。 + @MainActor + func refresh(onRequestStarted: (@MainActor () -> Void)? = nil) async { + guard canLoad, let service else { return } + generation &+= 1 + let requestGeneration = generation + guard accepts(requestGeneration) else { return } + isLoading = true + if playbackURL == nil { state = .loading } + onRequestStarted?() + defer { + if generation == requestGeneration { + isLoading = false + if Task.isCancelled, state == .loading { state = .idle } + } + } + do { + let value = try await service.live(taskID: taskID) + guard accepts(requestGeneration) else { return } + guard value.orderFlightTaskID == taskID, value.task?.id == nil || value.task?.id == taskID, + value.task?.scenicID == nil || value.task?.scenicID == context.scenicID else { + throw APIError.decodeFailed("图传回执与当前拍摄任务不一致") + } + response = value + guard let airportSN = DroneDockHomeMetric.usableText(value.airportSN), !airportSN.isEmpty else { + state = .unavailable("当前任务尚未返回已锁定的机场信息") + return + } + if let localPreviewURL { + guard localPreviewURL.isFileURL, FileManager.default.fileExists(atPath: localPreviewURL.path) else { + state = .failed("本地模拟视频不可用") + return + } + state = .localPreview(localPreviewURL) + } else { + state = .unavailable("暂未提供图传播放参数") + } + } catch is CancellationError { + guard generation == requestGeneration else { return } + state = .idle + } catch { + guard accepts(requestGeneration) else { return } + state = .failed(error.localizedDescription) + } + } + + /// 离页、后台或取消时作废旧请求并清除本地播放来源,不向设备发送停止指令。 + @MainActor + func invalidate() { + generation &+= 1 + isLoading = false + response = nil + state = service == nil ? .restricted : .idle + } + + /// 只接受当前页面与当前身份下的结果,身份变化后不允许重新请求旧任务。 + @MainActor + private func accepts(_ requestGeneration: Int) -> Bool { + guard generation == requestGeneration else { return false } + guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else { + invalidate() + identityInvalidated = true + state = .failed("账号或景区已变化,请返回工作台重新进入") + return false + } + return !Task.isCancelled + } +} diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift index c26a7f9..9478d3a 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift @@ -34,10 +34,21 @@ final class DroneDockShootingTaskViewModel { private(set) var commandErrorMessage: String? /// 已发但结果不明确时保持锁定,普通读取不能自动解除或重发。 private(set) var commandOutcomeUnknown = false + /// 重新召唤提交及其后单次回查期间保留旧画面并锁定其他操作。 + private(set) var isResummoning = false + /// 重新召唤明确拒绝、本地拦截或待核对的说明。 + private(set) var resummonErrorMessage: String? + /// 请求已发送但受理结果未知,普通刷新不能解除重发锁。 + private(set) var resummonOutcomeUnknown = false + /// 当前页面已受理一次重召唤;旧失败快照不能使同一请求再次提交。 + private(set) var hasSubmittedResummon = false + /// 重新召唤的原始受理回执,不替代 shooting 的设备状态。 + private(set) var resummonResponse: DroneDockShootResponse? private let service: any DroneDockShootingServing private let startService: (any DroneDockStartShooting)? private let commandService: (any DroneDockCommandSending)? + private let resummonService: (any DroneDockResummonServing)? private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext private var generation = 0 private var identityInvalidated = false @@ -45,6 +56,9 @@ final class DroneDockShootingTaskViewModel { private var didSendStart = false private var commandGeneration = 0 private var didSendCommand = false + private var resummonGeneration = 0 + private var didSendResummon = false + private var awaitingResummonSnapshot = false // 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。 private var pendingAcceptedCommands: Set = [] @@ -53,6 +67,7 @@ final class DroneDockShootingTaskViewModel { service: any DroneDockShootingServing, startService: (any DroneDockStartShooting)? = nil, commandService: (any DroneDockCommandSending)? = nil, + resummonService: (any DroneDockResummonServing)? = nil, currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { self.context = context self.taskID = taskID @@ -60,6 +75,7 @@ final class DroneDockShootingTaskViewModel { self.service = service self.startService = startService self.commandService = commandService + self.resummonService = resummonService self.currentContext = currentContext } @@ -70,9 +86,10 @@ final class DroneDockShootingTaskViewModel { } @MainActor - private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false) async { + private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false, + allowWhileResummoning: Bool = false) async { guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting, - !isSendingCommand || allowWhileCommand else { return } + !isSendingCommand || allowWhileCommand, !isResummoning || allowWhileResummoning else { return } generation &+= 1 let requestGeneration = generation isLoading = true @@ -97,6 +114,9 @@ final class DroneDockShootingTaskViewModel { throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取") } response = value + if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) { + awaitingResummonSnapshot = false + } pendingAcceptedCommands.formIntersection(availableSafetyCommands) } catch { guard accepts(requestGeneration) else { return } @@ -109,6 +129,7 @@ final class DroneDockShootingTaskViewModel { func invalidate(preservingSnapshot: Bool = false) { invalidateStartShooting() invalidateCommand() + invalidateResummon() generation &+= 1 isLoading = false if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true } @@ -118,6 +139,8 @@ final class DroneDockShootingTaskViewModel { startErrorMessage = nil commandResponse = nil commandErrorMessage = nil + resummonResponse = nil + resummonErrorMessage = nil pendingAcceptedCommands.removeAll() errorMessage = "账号或景区已变化,请返回工作台重新进入" } else { @@ -129,9 +152,9 @@ final class DroneDockShootingTaskViewModel { /// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。 var canStartShooting: Bool { startService != nil && context.canLoad && taskID > 0 && !identityInvalidated - && !isLoading && !isStartingShooting && !isSendingCommand && errorMessage == nil + && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil && !hasSubmittedStart && !startOutcomeUnknown - && !commandOutcomeUnknown && pendingAcceptedCommands.isEmpty + && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty && resolvedDisplayPhase().0 == .ready && response?.executeGate?.canExecute == true && response?.executeGate?.primaryAction == "start_shoot" @@ -218,8 +241,9 @@ final class DroneDockShootingTaskViewModel { /// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。 func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool { commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated - && !isLoading && !isStartingShooting && !isSendingCommand && errorMessage == nil - && !startOutcomeUnknown && !commandOutcomeUnknown && !pendingAcceptedCommands.contains(command) + && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil + && !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot + && !pendingAcceptedCommands.contains(command) && (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID) && (response?.currentPlane?.id ?? 0) > 0 && availableSafetyCommands.contains(command) @@ -291,6 +315,88 @@ final class DroneDockShootingTaskViewModel { didSendCommand = false } + /// 本地模拟服务显式注入、当前任务明确失败且没有在途或未知操作时才可重召唤。 + /// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。 + var canResummon: Bool { + resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated + && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil + && !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown + && !hasSubmittedResummon && pendingAcceptedCommands.isEmpty + && resolvedDisplayPhase().0 == .failed + && (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID) + && (response?.currentPlane?.id ?? 0) > 0 + && !isResummonDeviceUnavailable + } + + /// 复用同一任务提交一次 restart=true;受理后只查询一次 shooting,不推断已经到达。 + @MainActor + func resummon(onStateChange: @escaping @MainActor () -> Void = {}) async { + guard canResummon, let resummonService else { return } + guard context.hasSameIdentity(as: currentContext()) else { + identityInvalidated = true + invalidate() + onStateChange() + return + } + guard !Task.isCancelled else { return } + resummonGeneration &+= 1 + let requestGeneration = resummonGeneration + isResummoning = true + didSendResummon = false + resummonResponse = nil + resummonErrorMessage = nil + onStateChange() + defer { + if resummonGeneration == requestGeneration { + if Task.isCancelled && didSendResummon && !hasSubmittedResummon { markResummonUnknown() } + isResummoning = false + didSendResummon = false + onStateChange() + } + } + guard acceptsResummon(requestGeneration) else { return } + do { + didSendResummon = true + let value = try await resummonService.resummon(taskID: taskID) + guard acceptsResummon(requestGeneration) else { return } + guard try matchesResummonReceipt(value) else { + throw APIError.decodeFailed("重新召唤回执与当前任务或订单不一致,请先核对任务状态") + } + resummonResponse = value + hasSubmittedResummon = true + resummonOutcomeUnknown = false + awaitingResummonSnapshot = true + hasSubmittedStart = false + startResponse = nil + startErrorMessage = nil + commandResponse = nil + commandErrorMessage = nil + onStateChange() + guard acceptsResummon(requestGeneration) else { return } + await refreshSnapshot(allowWhileStarting: false, allowWhileResummoning: true) + } catch { + if error is DeviceCommandDebugBlockedError, resummonGeneration == requestGeneration { didSendResummon = false } + guard acceptsResummon(requestGeneration) else { return } + if error is DeviceCommandDebugBlockedError { + resummonErrorMessage = DeviceCommandDebugPolicy.blockedMessage + } else if case APIError.serverCode = error { + didSendResummon = false + resummonErrorMessage = error.localizedDescription + } else { + markResummonUnknown(reason: error.localizedDescription) + } + } + } + + /// 离页或进入后台后忽略旧回执;发出后未确认的重新召唤继续保持待核对锁。 + @MainActor + func invalidateResummon() { + if isResummoning && didSendResummon && !hasSubmittedResummon { markResummonUnknown() } + resummonGeneration &+= 1 + isResummoning = false + didSendResummon = false + } + /// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。 var title: String { if let title = usable(response?.header?.title) { return title } @@ -328,6 +434,8 @@ final class DroneDockShootingTaskViewModel { if let errorMessage { return errorMessage } if isLoading { return "正在读取当前拍摄任务" } } + if let resummonErrorMessage { return resummonErrorMessage } + if awaitingResummonSnapshot { return "重新召唤请求已受理,请刷新核对任务状态" } if let commandErrorMessage { return commandErrorMessage } if resolvedDisplayPhase().0 == .failed { return failureMessage } if startOutcomeUnknown, let startErrorMessage { return startErrorMessage } @@ -355,7 +463,7 @@ final class DroneDockShootingTaskViewModel { let actionTitle: String? let enabled: Bool switch phase { - case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown: + case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown || resummonOutcomeUnknown: action = .refresh actionTitle = "刷新状态" enabled = !identityInvalidated @@ -372,10 +480,14 @@ final class DroneDockShootingTaskViewModel { action = .materials actionTitle = "查看素材" enabled = true + case .failed where hasSubmittedResummon || resummonOutcomeUnknown: + action = .refresh + actionTitle = "刷新状态" + enabled = !identityInvalidated case .failed: action = .retry - actionTitle = "重新召唤无人机" - enabled = false + actionTitle = isResummoning ? "正在重新召唤…" : "重新召唤无人机" + enabled = canResummon default: action = .refresh actionTitle = "刷新状态" @@ -383,8 +495,8 @@ final class DroneDockShootingTaskViewModel { } return DroneDockTaskPresentation(phase: phase, title: title, message: message, deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle, - isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !identityInvalidated && (errorMessage == nil || action == .refresh), - actionNote: phase == .failed ? retryUnavailableNote : nil) + isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh), + actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil) } /// 后端六项展示读数,不解析文案反推设备状态或数值单位。 @@ -433,6 +545,35 @@ final class DroneDockShootingTaskViewModel { return !Task.isCancelled } + @MainActor + private func acceptsResummon(_ requestGeneration: Int) -> Bool { + guard resummonGeneration == requestGeneration else { return false } + guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else { + identityInvalidated = true + invalidate() + return false + } + return !Task.isCancelled + } + + private func markResummonUnknown(reason: String? = nil) { + resummonOutcomeUnknown = true + resummonErrorMessage = (reason.map { "\($0)。" } ?? "") + "重新召唤结果待核对,请刷新任务状态,勿重复提交" + } + + /// shoot 顶层 task_id 是实际航线任务 ID;只核对明确的订单任务身份,不混淆两种任务。 + private func matchesResummonReceipt(_ value: DroneDockShootResponse) throws -> Bool { + guard let json = value.dataJSON else { return true } + let data = Data(json.utf8) + guard case .object = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: data) else { return true } + let identity = try JSONDecoder().decode(DroneDockResummonReceiptIdentity.self, from: data) + return (identity.orderFlightTaskID == nil || identity.orderFlightTaskID == taskID) + && (identity.orderFlightTask?.id == nil || identity.orderFlightTask?.id == taskID) + && (identity.orderFlightTask?.orderNumber == nil || identity.orderFlightTask?.orderNumber == order.orderNumber) + && (identity.orderFlightTask?.scenicID == nil || identity.orderFlightTask?.scenicID == context.scenicID) + && (identity.planeID == nil || identity.planeID == response?.currentPlane?.id) + } + private func markCommandUnknown(reason: String? = nil) { commandOutcomeUnknown = true commandErrorMessage = (reason.map { "\($0)。" } ?? "") + "安全指令结果待核对,请刷新任务状态,勿重复提交" @@ -524,7 +665,15 @@ final class DroneDockShootingTaskViewModel { ?? usable(response?.executeGate?.message) ?? usable(response?.ui?.message) ?? "暂未返回具体失败原因" } - /// 重新召唤尚未接入;只补充明确设备状态,不将开始许可、空闲或失败推断为允许重试。 + /// 明确离线或返航时保持禁用,不从普通空闲文案推导后端重试许可。 + private var isResummonDeviceUnavailable: Bool { + let plane = response?.currentPlane + return response?.planeStatus?.connected == false || plane?.onlineStatus == 2 || plane?.workStatus == 0 + || ["离线", "返航中", "正在返航"].contains(usable(plane?.workStatusLabel) ?? "") + || response?.ui?.phase == "returning" + } + + /// 正式入口未注入操作服务时说明当前限制;模拟页保留实际设备不可用原因。 private var retryUnavailableNote: String { let plane = response?.currentPlane if plane?.onlineStatus == 2 || plane?.workStatus == 0 || usable(plane?.workStatusLabel) == "离线" { diff --git a/suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift b/suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift index e943eb4..8d1f334 100644 --- a/suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift +++ b/suixinkan/Features/ScenicMaterials/ViewModels/ScenicMaterialsViewModel.swift @@ -150,7 +150,7 @@ final class ScenicMaterialsViewModel { var emptyMessage: String { if isLoading { return "请稍候" } if let loadError { return loadError } - return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里" + return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区素材更新后,将显示在这里" } /// 刷新当前筛选第一页,并读取该页完整片段;详情失败时整页可重试,不混入演示数据。 diff --git a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift index dc06568..8ede6f5 100644 --- a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift @@ -1,17 +1,19 @@ import SnapKit import UIKit -/// 拍摄任务页:真实入口只读,本地模拟入口可验证开拍与底部安全指令合同。 +/// 拍摄任务页:真实入口只读,本地模拟入口可验证图传、重召唤、开拍与安全指令合同。 @MainActor final class DroneDockShootingTaskViewController: BaseViewController { /// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。 let viewModel: DroneDockShootingTaskViewModel + /// 图传使用独立状态,刷新与播放不会影响任务阶段或固定布局。 + let liveViewModel: DroneDockLiveViewModel private let topView = UIView() private let summaryView = UIView() private let taskTitleLabel = DroneDockStyle.label(size: 17, weight: .semibold) private let subtitleLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) - private let feedPlaceholder = DroneDockTaskFeedPlaceholderView() + private let feedPlaceholder = DroneDockTaskLiveView() private let telemetryView = DroneShootingTaskTelemetryView() private let statusView = DroneDockTaskStatusView() private let safetyView = DroneDockTaskSafetyView() @@ -24,18 +26,26 @@ final class DroneDockShootingTaskViewController: BaseViewController { private var refreshTask: Task? private var startTask: Task? private var commandTask: Task? + private var resummonTask: Task? + private var liveTask: Task? + private var liveGeneration = 0 private var requestGeneration = 0 private var isPageVisible = false private var isApplicationActive = false private var isRequesting = false private var isStartingAction = false private var isSendingSafetyAction = false + private var isResummoningAction = false /// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。 init(viewModel: DroneDockShootingTaskViewModel, + liveViewModel: DroneDockLiveViewModel? = nil, materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil, simulationRecordsProvider: (@MainActor () -> String)? = nil) { self.viewModel = viewModel + self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel( + context: viewModel.context, taskID: viewModel.taskID, + currentContext: { DroneDockHomeViewController.currentContext() }) self.simulationRecordsProvider = simulationRecordsProvider self.materialsControllerFactory = materialsControllerFactory ?? { order, context in DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel( @@ -54,6 +64,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { refreshTask?.cancel() startTask?.cancel() commandTask?.cancel() + resummonTask?.cancel() + liveTask?.cancel() NotificationCenter.default.removeObserver(self) } @@ -160,6 +172,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() } statusView.onDetails = { [weak self] in self?.showStatusDetails() } safetyView.onCommand = { [weak self] command in self?.safetyCommandTriggered(command) } + feedPlaceholder.onRequest = { [weak self] in self?.refreshLiveIfVisible() } NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), @@ -172,6 +185,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { isPageVisible = true isApplicationActive = UIApplication.shared.applicationState == .active refreshTaskIfVisible() + refreshLiveIfVisible() } /// 离页立即取消未完成的读取,使迟到响应失效。 @@ -179,12 +193,15 @@ final class DroneDockShootingTaskViewController: BaseViewController { super.viewWillDisappear(animated) isPageVisible = false cancelRefresh() + stopLive() } private func applySnapshot() { guard isViewLoaded else { return } let loading = isRequesting || viewModel.isLoading || isStartingAction || viewModel.isStartingShooting - || isSendingSafetyAction || viewModel.isSendingCommand + || isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning + feedPlaceholder.apply(liveViewModel) + feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive) taskTitleLabel.text = viewModel.title subtitleLabel.text = viewModel.subtitle let telemetry = viewModel.telemetry @@ -205,7 +222,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func primaryActionTriggered() { guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading, !isStartingAction, !viewModel.isStartingShooting, - !isSendingSafetyAction, !viewModel.isSendingCommand else { return } + !isSendingSafetyAction, !viewModel.isSendingCommand, + !isResummoningAction, !viewModel.isResummoning else { return } let state = viewModel.presentation guard state.isActionEnabled else { return } switch state.action { @@ -213,10 +231,12 @@ final class DroneDockShootingTaskViewController: BaseViewController { refreshTaskIfVisible() case .start: startShootingIfAllowed() + case .retry: + resummonIfAllowed() case .materials: guard let navigationController, navigationController.topViewController === self else { return } navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true) - case .resume, .retry, .none: + case .resume, .none: break } } @@ -230,6 +250,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { } if let error = viewModel.startErrorMessage { texts.append(error) } if let error = viewModel.commandErrorMessage { texts.append(error) } + if let error = viewModel.resummonErrorMessage { 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) @@ -241,7 +262,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func refreshTaskIfVisible() { guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading, !isStartingAction, !viewModel.isStartingShooting, - !isSendingSafetyAction, !viewModel.isSendingCommand else { return } + !isSendingSafetyAction, !viewModel.isSendingCommand, + !isResummoningAction, !viewModel.isResummoning else { return } requestGeneration &+= 1 let generation = requestGeneration isRequesting = true @@ -268,6 +290,9 @@ final class DroneDockShootingTaskViewController: BaseViewController { startTask = nil commandTask?.cancel() commandTask = nil + resummonTask?.cancel() + resummonTask = nil + isResummoningAction = false isSendingSafetyAction = false isStartingAction = false isRequesting = false @@ -277,7 +302,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { /// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。 private func startShootingIfAllowed() { - guard !isStartingAction, !isSendingSafetyAction, viewModel.canStartShooting else { return } + guard !isStartingAction, !isSendingSafetyAction, !isResummoningAction, viewModel.canStartShooting else { return } requestGeneration &+= 1 let generation = requestGeneration isStartingAction = true @@ -298,11 +323,65 @@ final class DroneDockShootingTaskViewController: BaseViewController { } } + /// 重召唤只在显式模拟入口开放;点击后锁定按钮,使用原任务 ID,并由状态回查更新页面。 + private func resummonIfAllowed() { + guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive, + !isResummoningAction, !isStartingAction, !isSendingSafetyAction, + !isRequesting, viewModel.canResummon else { return } + requestGeneration &+= 1 + let generation = requestGeneration + isResummoningAction = true + applySnapshot() + resummonTask = Task { @MainActor [weak self] in + guard let self else { return } + await self.viewModel.resummon { [weak self] in self?.applySnapshot() } + guard self.isPageVisible, self.isApplicationActive, + self.requestGeneration == generation, !Task.isCancelled else { return } + self.resummonTask = nil + self.isResummoningAction = false + self.applySnapshot() + if let error = self.viewModel.resummonErrorMessage { + self.showToast(error) + } else if self.viewModel.hasSubmittedResummon, let error = self.viewModel.errorMessage { + self.showToast("模拟重召唤已受理,状态刷新失败:\(error)") + } else if self.viewModel.hasSubmittedResummon { + self.showToast("本地模拟重召唤已受理,未发送设备指令") + } else if let error = self.viewModel.errorMessage { + self.showToast(error) + } + } + } + + /// 图传只读取一次,不轮询;正式入口没有图传服务,不能向设备发出开流请求。 + private func refreshLiveIfVisible() { + guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return } + liveGeneration &+= 1 + let generation = liveGeneration + liveTask = Task { @MainActor [weak self] in + guard let self else { return } + await self.liveViewModel.refresh { [weak self] in self?.applySnapshot() } + guard self.liveGeneration == generation, self.isPageVisible, self.isApplicationActive, + !Task.isCancelled else { return } + self.liveTask = nil + self.applySnapshot() + } + } + + /// 离页或进入后台立即释放播放器,使旧图传响应无法恢复播放。 + private func stopLive() { + liveGeneration &+= 1 + liveTask?.cancel() + liveTask = nil + liveViewModel.invalidate() + feedPlaceholder.setPlaybackActive(false) + feedPlaceholder.apply(liveViewModel) + } + /// 仅模拟入口响应安全按钮;返航会中断任务,先明确展示其含义再提交一次。 private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) { guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive, presentedViewController == nil, !isSendingSafetyAction, !isStartingAction, - !isRequesting, viewModel.canSendCommand(command) else { return } + !isResummoningAction, !isRequesting, viewModel.canSendCommand(command) else { return } if command == .returnHome { let alert = UIAlertController(title: "立即返航(本地模拟)", message: "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。", preferredStyle: .alert) @@ -319,7 +398,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { /// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。 private func sendSafetyCommand(_ command: DroneDockSafetyCommand) { guard simulationRecordsProvider != nil, isPageVisible, isApplicationActive, - !isSendingSafetyAction, !isStartingAction, !isRequesting, + !isSendingSafetyAction, !isStartingAction, !isResummoningAction, !isRequesting, viewModel.canSendCommand(command) else { return } requestGeneration &+= 1 let generation = requestGeneration @@ -360,12 +439,14 @@ final class DroneDockShootingTaskViewController: BaseViewController { @objc private func applicationWillResignActive() { isApplicationActive = false cancelRefresh() + stopLive() } @objc private func applicationDidBecomeActive() { guard !isApplicationActive else { return } isApplicationActive = true refreshTaskIfVisible() + refreshLiveIfVisible() } } @@ -501,34 +582,3 @@ private final class DroneDockTaskSafetyView: UIView { buttonHeight?.update(offset: compact ? 56 : 62) } } - -/// 真实图传尚未接入时的中性占位,不使用演示图片、播放进度或虚假连接状态。 -@MainActor -private final class DroneDockTaskFeedPlaceholderView: UIView { - override init(frame: CGRect) { - super.init(frame: frame) - backgroundColor = UIColor(hex: 0x172033) - accessibilityIdentifier = "drone.task.remote.feedPlaceholder" - let icon = UIImageView(image: UIImage(systemName: "video.slash")) - icon.contentMode = .scaleAspectFit - icon.tintColor = UIColor.white.withAlphaComponent(0.6) - let title = DroneDockStyle.label("图传暂未接入", size: 15, weight: .medium, color: .white) - let detail = DroneDockStyle.label("任务状态将在下方更新", size: 12, color: .white.withAlphaComponent(0.65)) - let stack = UIStackView(arrangedSubviews: [icon, title, detail]) - stack.axis = .vertical - stack.spacing = 9 - stack.alignment = .center - addSubview(stack) - icon.snp.makeConstraints { make in make.size.equalTo(31) } - stack.snp.makeConstraints { make in - make.center.equalToSuperview() - make.leading.greaterThanOrEqualToSuperview().offset(20) - make.trailing.lessThanOrEqualToSuperview().offset(-20) - } - isAccessibilityElement = true - accessibilityLabel = "图传暂未接入,任务状态将在下方更新" - } - - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } -} diff --git a/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift b/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift index 0535d42..ae45765 100644 --- a/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift +++ b/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift @@ -9,7 +9,10 @@ enum DroneDockStartShootSimulation { static func makeController(arguments: [String]) -> UIViewController? { let startsAtPreparation = arguments.contains("--dock-preparation-mock") let startsAtCommands = arguments.contains("--dock-command-mock") - guard startsAtPreparation || startsAtCommands || arguments.contains("--dock-start-shoot-mock") else { return nil } + let startsAtResummon = arguments.contains("--dock-resummon-mock") + let showsLive = arguments.contains("--dock-live-mock") + guard startsAtPreparation || startsAtCommands || startsAtResummon || showsLive + || 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))) @@ -18,8 +21,16 @@ enum DroneDockStartShootSimulation { let commandResult = commandResultArgument.flatMap { DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-command-result=".count))) } ?? .success + let resummonResult = arguments.first { $0.hasPrefix("--dock-resummon-result=") }.flatMap { + DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-resummon-result=".count))) + } ?? .success + let liveResult = arguments.first { $0.hasPrefix("--dock-live-result=") }.map { + String($0.dropFirst("--dock-live-result=".count)) + } ?? "success" return makeFlow(result: result, startsAtPreparation: startsAtPreparation, - commandResult: commandResult, startsAtCommands: startsAtCommands) + commandResult: commandResult, startsAtCommands: startsAtCommands, + startsAtResummon: startsAtResummon, resummonResult: resummonResult, + showsLive: showsLive, liveResult: liveResult) } /// 从正式准备页进入全新的纯内存模拟,不携带真实订单、账号或设备身份。 @@ -30,9 +41,13 @@ enum DroneDockStartShootSimulation { private static func makeFlow(result: DroneDockStartShootMockResult, startsAtPreparation: Bool, commandResult: DroneDockStartShootMockResult = .success, - startsAtCommands: Bool = false) -> UIViewController? { + startsAtCommands: Bool = false, startsAtResummon: Bool = false, + resummonResult: DroneDockStartShootMockResult = .success, + showsLive: Bool = false, liveResult: String = "success") -> UIViewController? { let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation, - commandResult: commandResult, hasStarted: startsAtCommands && !startsAtPreparation) + commandResult: commandResult, hasStarted: startsAtCommands && !startsAtPreparation, + hasFailed: startsAtResummon && !startsAtPreparation, resummonResult: resummonResult, + liveResult: liveResult) let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!, webSocketURL: URL(string: "wss://mock.invalid/unused")!) let client = APIClient(environment: environment, session: session) @@ -45,8 +60,14 @@ enum DroneDockStartShootSimulation { let model = DroneDockShootingTaskViewModel(context: taskContext, taskID: taskID, order: taskOrder, service: DroneDockShootingAPI(client: client), startService: DroneDockStartShootAPI(client: client), - commandService: DroneDockCommandAPI(client: client), currentContext: { context }) - return DroneDockShootingTaskViewController(viewModel: model, + commandService: DroneDockCommandAPI(client: client), + resummonService: startsAtResummon ? DroneDockShootAPI(client: client) : nil, + currentContext: { context }) + let live = showsLive ? DroneDockLiveViewModel(context: taskContext, taskID: taskID, + service: DroneDockLiveAPI(client: client), + localPreviewURL: liveResult == "success" ? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4") : nil, + currentContext: { context }) : nil + return DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live, materialsControllerFactory: { _, _ in let unavailable = UIViewController() unavailable.title = "本地模拟不连接素材库" @@ -79,6 +100,8 @@ private enum DroneDockStartShootMockResult: String { private final class DroneDockStartShootMockSession: LocalSimulationURLSession { private let result: DroneDockStartShootMockResult private let commandResult: DroneDockStartShootMockResult + private let resummonResult: DroneDockStartShootMockResult + private let liveResult: String private let lock = NSLock() private var hasCreated: Bool private var hasSummoned: Bool @@ -86,14 +109,19 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { private var isPaused = false private var isReturning = false private var wasInterrupted = false + private var hasFailed: Bool private var exchanges: [Exchange] = [] /// 固定当前实例结果,不能用参数切换到真实传输。 init(result: DroneDockStartShootMockResult, requiresPreparation: Bool, - commandResult: DroneDockStartShootMockResult, hasStarted: Bool) { + commandResult: DroneDockStartShootMockResult, hasStarted: Bool, + hasFailed: Bool, resummonResult: DroneDockStartShootMockResult, liveResult: String) { self.result = result self.commandResult = commandResult self.hasStarted = hasStarted + self.hasFailed = hasFailed + self.resummonResult = resummonResult + self.liveResult = liveResult hasCreated = !requiresPreparation hasSummoned = !requiresPreparation } @@ -188,8 +216,22 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { let object = try JSONSerialization.jsonObject(with: body) as? [String: Any], Set(object.keys) == ["id", "restart"], let values = try? JSONDecoder().decode(ShootBody.self, from: body), - values.id == 901, !values.restart else { throw URLError(.badURL) } - guard hasCreated, !hasSummoned else { + values.id == 901 else { throw URLError(.badURL) } + if values.restart { + guard hasCreated, hasSummoned, hasFailed else { + return try envelope([:], code: 100099, message: "本地模拟:当前任务不允许重新召唤") + } + switch resummonResult { + case .businessFailure: + return try envelope([:], code: 100099, message: "本地模拟:设备暂不可用,重新召唤被拒绝") + case .timeout: + throw URLError(.timedOut) + case .success: + hasFailed = false + hasStarted = false + isPaused = false + } + } else if !hasCreated || hasSummoned { return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤") } hasSummoned = true @@ -207,6 +249,16 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") } return try envelope(shootingData()) } + if request.httpMethod == "GET", url.path == "/api/app/airport/live" { + guard queryMatches(url, required: ["id": "901"]), hasSummoned else { throw URLError(.badURL) } + if liveResult == "timeout" { throw URLError(.timedOut) } + if liveResult == "business-failure" { + return try envelope([:], code: 100099, message: "本地模拟:图传连接不可用") + } + // 文档未提供播放协议;这里只模拟已知字段,本地视频通过独立依赖注入,绝不伪装成后端字段。 + return try envelope(["order_flight_task_id": 901, "airport": [:], "drone": [:], + "task": taskData(), "airport_sn": "LOCAL-MOCK-DOCK-201", "metrics": simulatedMetrics]) + } 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], @@ -243,7 +295,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { throw URLError(.unsupportedURL) } guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") } - guard !isPaused, !wasInterrupted else { + guard !isPaused, !wasInterrupted, !hasFailed else { return try envelope([:], code: 100099, message: "本地模拟:任务暂停或已中断,不可开始拍摄") } guard !hasStarted else { @@ -282,9 +334,11 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { } private func shootingData() -> [String: Any] { - let canStart = !hasStarted && !isPaused && !wasInterrupted + let canStart = !hasStarted && !isPaused && !wasInterrupted && !hasFailed let phaseTitle: String - if wasInterrupted { + if hasFailed { + phaseTitle = "本地模拟:航线执行失败,可验证重新召唤流程" + } else if wasInterrupted { phaseTitle = isReturning ? "本地模拟:立即返航中断任务;无人机返航中" : "本地模拟:返航已取消,任务仍已中断" } else if isPaused { phaseTitle = "拍摄已暂停(模拟)" @@ -322,7 +376,13 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { private func taskData() -> [String: Any] { 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 { + if hasFailed { + task["status"] = 40 + task["status_label"] = "任务失败(模拟)" + task["wayline_status"] = 91 + task["wayline_status_label"] = "执行失败(模拟)" + task["result_message"] = "本地模拟:航线执行失败,无人机空闲待命。" + } else if wasInterrupted { task["status"] = 40 task["status_label"] = "任务已中断(模拟)" task["wayline_status"] = 40 @@ -335,13 +395,14 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { } private var availableCommands: [DroneDockSafetyCommand] { - guard hasSummoned else { return [] } + guard hasSummoned, !hasFailed else { return [] } if isReturning { return [.cancelReturn] } if wasInterrupted { return [] } return [isPaused ? .resume : .pause, .returnHome] } private var simulatedPhase: String { + if hasFailed { return "failed" } if isReturning { return "returning" } if wasInterrupted { return "failed" } if isPaused { return "paused" } @@ -380,7 +441,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { } } - /// 召唤只接受同一模拟任务且禁止重启,不产生真实设备操作。 + /// 首次召唤或失败重召唤只接受同一模拟任务,不产生真实设备操作。 private struct ShootBody: Decodable { let id: Int let restart: Bool diff --git a/suixinkan/UI/DroneDock/DroneDockTaskFailureView.swift b/suixinkan/UI/DroneDock/DroneDockTaskFailureView.swift index 8188109..4764ecf 100644 --- a/suixinkan/UI/DroneDock/DroneDockTaskFailureView.swift +++ b/suixinkan/UI/DroneDock/DroneDockTaskFailureView.swift @@ -1,11 +1,13 @@ import SnapKit import UIKit -/// 对齐体验网页的任务失败组合:警示、原因、排查提示、重召占位及设备提示。 +/// 对齐体验网页的任务失败组合:警示、原因、排查提示、重召或刷新操作及设备提示。 @MainActor final class DroneDockTaskFailureView: UIView { /// 点击原因区域查看完整后端说明,页面无需额外占用一个详情按钮。 var onDetails: (() -> Void)? + /// 将重召唤或结果核对操作交给任务页,视图不直接发送请求。 + var onPrimaryAction: (() -> Void)? /// 内部排版参考比例,不对视图或点击区域使用整体缩放。 private(set) var effectiveScale: CGFloat = 1 /// 当前是否使用适配固定小高度的紧凑排版。 @@ -44,13 +46,16 @@ final class DroneDockTaskFailureView: UIView { required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 更新真实失败原因及不可重召原因,不把开始拍摄许可当作重召许可。 - func apply(_ value: DroneDockTaskPresentation) { + func apply(_ value: DroneDockTaskPresentation, isRefreshing: Bool = false) { presentation = value titleLabel.text = value.title let reason = DroneDockHomeMetric.usableText(value.message).flatMap { $0 == "—" ? nil : $0 } ?? "服务端暂未提供具体原因" reasonLabel.text = reason.hasPrefix("失败原因:") ? reason : "失败原因:\(reason)" - noteLabel.text = value.actionNote ?? "暂不可重新召唤,请返回准备页确认设备状态" + noteLabel.text = value.actionNote ?? (value.action == .refresh ? "请核对原任务状态,勿重复召唤" : "") + retryButton.configuration?.title = value.actionTitle + retryButton.configuration?.image = UIImage(systemName: value.action == .refresh ? "arrow.clockwise" : "arrow.triangle.2.circlepath") + retryButton.isEnabled = value.isActionEnabled && !isRefreshing notice.accessibilityLabel = [value.title, reasonLabel.text, adviceLabel.text].compactMap { $0 }.joined(separator: "。") setNeedsLayout() } @@ -107,11 +112,12 @@ final class DroneDockTaskFailureView: UIView { configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8) retryButton.configuration = configuration retryButton.configurationUpdateHandler = { button in - button.configuration?.baseForegroundColor = UIColor(hex: 0x939CB0) - button.configuration?.background.backgroundColor = UIColor(hex: 0xE8EBF1) + button.configuration?.baseForegroundColor = button.isEnabled ? .white : UIColor(hex: 0x939CB0) + button.configuration?.background.backgroundColor = button.isEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE8EBF1) } retryButton.isEnabled = false retryButton.accessibilityIdentifier = "drone.task.remote.failureRetry" + retryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside) } private func setupConstraints() { @@ -205,4 +211,9 @@ final class DroneDockTaskFailureView: UIView { } @objc private func showDetails() { onDetails?() } + + @objc private func primaryTapped() { + guard retryButton.isEnabled else { return } + onPrimaryAction?() + } } diff --git a/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift b/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift new file mode 100644 index 0000000..124a4a7 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift @@ -0,0 +1,143 @@ +import AVFoundation +import SnapKit +import UIKit + +/// 固定图传区域:展示接口状态或明确标记的本地样片,不自行发请求或读取远程视频。 +@MainActor +final class DroneDockTaskLiveView: UIView { + /// 用户主动获取或重试图传信息,具体请求由控制器协调。 + var onRequest: (() -> Void)? + + private let playerLayer = AVPlayerLayer() + private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: .white) + private let messageLabel = DroneDockStyle.label(size: 12, color: .lightGray) + private let sourceLabel = DroneDockStyle.label(size: 11, weight: .medium, color: .white) + private let requestButton = UIButton(type: .system) + private let labels = UIStackView() + private var player: AVQueuePlayer? + private var looper: AVPlayerLooper? + private var requestedURL: URL? + private var activeURL: URL? + private var isPlaybackActive = false + + /// 保留原任务页图传区域的访问标识,外部负责 16:9 约束。 + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + setupConstraints() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 根据外部固定容器尺寸更新播放器画面,不改变任务布局。 + override func layoutSubviews() { + super.layoutSubviews() + CATransaction.begin() + CATransaction.setDisableActions(true) + playerLayer.frame = bounds + CATransaction.commit() + } + + /// 在明确时机应用模型;远程 URL 即使错误传入也不会创建播放器。 + func apply(_ model: DroneDockLiveViewModel) { + titleLabel.text = model.title + messageLabel.text = model.message + requestButton.setTitle(model.actionTitle, for: .normal) + requestButton.isHidden = model.actionTitle == nil + requestButton.isEnabled = model.canLoad + requestedURL = model.playbackURL.flatMap { $0.isFileURL ? $0 : nil } + let hasLocalPreview = requestedURL != nil + sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : nil + sourceLabel.isHidden = !hasLocalPreview + titleLabel.isHidden = hasLocalPreview + messageLabel.isHidden = hasLocalPreview + accessibilityLabel = hasLocalPreview ? sourceLabel.text : "\(model.title),\(model.message)" + updatePlayback() + } + + /// 页面离开或进入后台立即释放播放器;回来后仅恢复已经明确注入的本地来源。 + func setPlaybackActive(_ active: Bool) { + isPlaybackActive = active + updatePlayback() + } + + private func setupUI() { + backgroundColor = UIColor(hex: 0x171B22) + clipsToBounds = true + accessibilityIdentifier = "drone.task.remote.feedPlaceholder" + layer.addSublayer(playerLayer) + playerLayer.videoGravity = .resizeAspect + titleLabel.textAlignment = .center + messageLabel.textAlignment = .center + messageLabel.numberOfLines = 2 + messageLabel.accessibilityIdentifier = "drone.task.remote.live.status" + titleLabel.accessibilityIdentifier = "drone.task.remote.live.title" + sourceLabel.accessibilityIdentifier = "drone.task.remote.live.source" + sourceLabel.backgroundColor = UIColor.black.withAlphaComponent(0.65) + sourceLabel.textAlignment = .center + sourceLabel.layer.cornerRadius = 4 + sourceLabel.clipsToBounds = true + sourceLabel.isHidden = true + requestButton.tintColor = .white + requestButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) + requestButton.backgroundColor = UIColor.black.withAlphaComponent(0.45) + requestButton.layer.cornerRadius = 6 + requestButton.accessibilityIdentifier = "drone.task.remote.live.request" + requestButton.addTarget(self, action: #selector(requestTapped), for: .touchUpInside) + labels.axis = .vertical + labels.spacing = 8 + labels.alignment = .fill + labels.addArrangedSubview(titleLabel) + labels.addArrangedSubview(messageLabel) + addSubview(labels) + addSubview(sourceLabel) + addSubview(requestButton) + } + + private func setupConstraints() { + labels.snp.makeConstraints { make in + make.centerY.equalToSuperview().offset(-15) + make.leading.trailing.equalToSuperview().inset(20) + } + requestButton.snp.makeConstraints { make in + make.centerX.equalToSuperview() + make.bottom.equalToSuperview().inset(12) + make.width.greaterThanOrEqualTo(150) + make.height.equalTo(36) + } + sourceLabel.snp.makeConstraints { make in + make.top.leading.equalToSuperview().inset(10) + make.height.equalTo(24) + make.width.equalTo(200) + } + } + + private func updatePlayback() { + guard isPlaybackActive, let requestedURL, requestedURL.isFileURL else { + releasePlayer() + return + } + guard activeURL != requestedURL || player == nil else { return } + releasePlayer() + let queue = AVQueuePlayer() + queue.isMuted = true + looper = AVPlayerLooper(player: queue, templateItem: AVPlayerItem(url: requestedURL)) + player = queue + activeURL = requestedURL + playerLayer.player = queue + queue.play() + } + + private func releasePlayer() { + player?.pause() + looper?.disableLooping() + player?.removeAllItems() + playerLayer.player = nil + looper = nil + player = nil + activeURL = nil + } + + @objc private func requestTapped() { onRequest?() } +} diff --git a/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift b/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift index 91284f0..5284827 100644 --- a/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift +++ b/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift @@ -55,7 +55,7 @@ final class DroneDockTaskStatusView: UIView { contentStack.isHidden = isFailure failureView.isHidden = !isFailure if isFailure { - failureView.apply(presentation) + failureView.apply(presentation, isRefreshing: isRefreshing) setNeedsLayout() return } @@ -94,6 +94,7 @@ final class DroneDockTaskStatusView: UIView { addSubview(failureView) failureView.isHidden = true failureView.onDetails = { [weak self] in self?.onDetails?() } + failureView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() } contentStack.axis = .vertical contentStack.alignment = .fill contentStack.spacing = 10 diff --git a/suixinkanTests/DroneDockLiveAPITests.swift b/suixinkanTests/DroneDockLiveAPITests.swift new file mode 100644 index 0000000..794cedd --- /dev/null +++ b/suixinkanTests/DroneDockLiveAPITests.swift @@ -0,0 +1,118 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// live 请求合同只交给纯内存传输,测试不会连接后端或启动设备图传。 +@MainActor +final class DroneDockLiveAPITests: XCTestCase { + /// 仅向 live 发送同一任务 ID 的 GET,并复用统一鉴权。 + func testRequestContainsOnlyTaskIDAndNoBody() async throws { + let session = MockURLSession(responses: [try DroneDockLiveTestData.envelope()]) + let client = APIClient(environment: .testing, session: session) + client.bindAuthTokenProvider { "live-test-token" } + let response = try await DroneDockLiveAPI(client: client).live(taskID: 501) + let request = try XCTUnwrap(session.requests.first) + XCTAssertEqual(session.requests.count, 1) + XCTAssertEqual(request.httpMethod, "GET") + XCTAssertEqual(request.url?.path, "/api/app/airport/live") + XCTAssertNil(request.httpBody) + XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "live-test-token") + XCTAssertEqual(URLComponents(url: try XCTUnwrap(request.url), resolvingAgainstBaseURL: false)?.queryItems, + [URLQueryItem(name: "id", value: "501")]) + XCTAssertEqual(response.orderFlightTaskID, 501) + XCTAssertEqual(response.airportSN, "TEST-LIVE-AIRPORT") + XCTAssertEqual(response.metrics.first?.displayText, "0%") + } + + /// 未定义的字段与原类型保留在回执中,不解析成真实连接参数。 + func testUnknownJSONFieldsPreserveOriginalTypes() throws { + let fields = DroneDockLiveTestData.payload().merging([ + "future": ["flag": false, "values": [NSNull(), "001", 0, 1.5]] as [String: Any], + "play_url": "https://example.invalid/not-a-confirmed-contract" + ]) { _, new in new } + let response = try DroneDockLiveTestData.response(fields) + let result = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(response.dataJSON.utf8)) as? [String: Any]) + XCTAssertTrue(NSDictionary(dictionary: result).isEqual(to: fields)) + XCTAssertEqual(response.airport, .object([:])) + } + + /// 缺失身份、字符串任务 ID 和非对象 data 不作为可信回执。 + func testMissingOrMalformedIdentityIsRejected() throws { + XCTAssertThrowsError(try DroneDockLiveTestData.response([:])) + XCTAssertThrowsError(try DroneDockLiveTestData.response(["order_flight_task_id": "501"])) + XCTAssertThrowsError(try DroneDockLiveTestData.response(["order_flight_task_id": true])) + XCTAssertThrowsError(try JSONDecoder().decode(DroneDockLiveResponse.self, from: Data("[]".utf8))) + } + + /// 顶层与嵌套任务均参与核对,避免给当前页返回其他任务的图传。 + func testMismatchedTaskIdentitiesAreRejected() async throws { + for changes: [String: Any] in [["order_flight_task_id": 502], ["task": ["id": 502]]] { + let fields = DroneDockLiveTestData.payload().merging(changes) { _, new in new } + let session = MockURLSession(responses: [try DroneDockLiveTestData.envelope(fields)]) + do { + _ = try await DroneDockLiveAPI(client: APIClient(environment: .testing, session: session)).live(taskID: 501) + XCTFail("应拒绝其他任务的图传回执") + } catch let APIError.decodeFailed(message) { XCTAssertFalse(message.isEmpty) } + XCTAssertEqual(session.requests.count, 1) + } + } + + /// 后端业务拒绝保留原码与说明,不变为占位的成功连接。 + func testBusinessRejectionPreservesReason() async throws { + let session = MockURLSession(responses: [try TestJSON.errorEnvelope(code: 100099, msg: "任务尚未锁定机场")]) + do { + _ = try await DroneDockLiveAPI(client: APIClient(environment: .testing, session: session)).live(taskID: 501) + XCTFail("业务拒绝不应算成功") + } catch let APIError.serverCode(code, message) { + XCTAssertEqual(code, 100099) + XCTAssertEqual(message, "任务尚未锁定机场") + } + } + + /// HTTP 失败及超时各只提交一次,不在适配器中重试或使用其他机场接口。 + func testTransportFailuresDoNotRetry() async throws { + let sessions = [MockURLSession(responses: [try DroneDockLiveTestData.envelope()], statusCode: 503), + MockURLSession(results: [.failure(URLError(.timedOut))])] + for session in sessions { + do { + _ = try await DroneDockLiveAPI(client: APIClient(environment: .testing, session: session)).live(taskID: 501) + XCTFail("传输失败不应算成功") + } catch {} + XCTAssertEqual(session.requests.count, 1) + } + } + + /// 无效任务 ID 与调用前取消都在传输前结束。 + func testInvalidOrCancelledRequestDoesNotReachTransport() async throws { + let session = MockURLSession(responses: []) + let api = DroneDockLiveAPI(client: APIClient(environment: .testing, session: session)) + for id in [0, -1] { + do { _ = try await api.live(taskID: id); XCTFail("应拒绝无效 ID") } catch {} + } + let task = Task { @MainActor in try await api.live(taskID: 501) } + task.cancel() + do { _ = try await task.value; XCTFail("应处理取消") } catch is CancellationError {} + XCTAssertTrue(session.requests.isEmpty) + } +} + +/// live 测试仅使用文档已说明字段;不存在任何可连接的真实设备身份。 +enum DroneDockLiveTestData { + /// 构造含明确任务身份、空设备明细与零电量读数的匿名数据。 + static func payload() -> [String: Any] { + ["order_flight_task_id": 501, "airport": [:], "drone": [:], + "airport_sn": "TEST-LIVE-AIRPORT", "task": ["id": 501, "status": 20], + "metrics": [["key": "battery", "value": "0%"]]] + } + + /// 将匿名对象解析为正式 DTO,不伪造服务层已验证结论。 + static func response(_ value: [String: Any]? = nil) throws -> DroneDockLiveResponse { + try JSONDecoder().decode(DroneDockLiveResponse.self, + from: JSONSerialization.data(withJSONObject: value ?? payload())) + } + + /// 将匿名 data 包装为统一成功响应,仅供内存传输。 + static func envelope(_ value: [String: Any]? = nil) throws -> Data { + try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "success", "data": value ?? payload()]) + } +} diff --git a/suixinkanTests/DroneDockLiveViewModelTests.swift b/suixinkanTests/DroneDockLiveViewModelTests.swift new file mode 100644 index 0000000..9fed95b --- /dev/null +++ b/suixinkanTests/DroneDockLiveViewModelTests.swift @@ -0,0 +1,220 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证图传参数不足、显式本地来源与生命周期;测试不访问网络或播放器。 +@MainActor +final class DroneDockLiveViewModelTests: XCTestCase { + /// 正式入口没有注入服务时保留禁飞状态,调用刷新也不会变为可播放。 + func testDefaultEntryRemainsRestricted() async { + let model = makeModel() + await model.refresh() + XCTAssertEqual(model.state, .restricted) + XCTAssertEqual(model.title, "当前调试已停用实时图传") + XCTAssertFalse(model.canLoad) + XCTAssertNil(model.playbackURL) + XCTAssertNil(model.response) + } + + /// 文档回执本身不含播放参数,GET 成功仍显示参数未提供。 + func testDocumentResponseDoesNotPretendVideoIsConnected() async throws { + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response())) + let model = makeModel(service: service) + await model.refresh() + XCTAssertEqual(model.state, .unavailable("暂未提供图传播放参数")) + XCTAssertNil(model.playbackURL) + XCTAssertEqual(model.response?.orderFlightTaskID, 501) + XCTAssertEqual(service.requests, [501]) + } + + /// 后端未知字段即使看起来像播放地址,也不能开启未约定的流媒体连接。 + func testUnspecifiedPlaybackFieldIsIgnored() async throws { + var fields = DroneDockLiveTestData.payload() + fields["play_url"] = "https://example.invalid/stream.m3u8" + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response(fields))) + let model = makeModel(service: service) + await model.refresh() + XCTAssertNil(model.playbackURL) + XCTAssertEqual(model.state, .unavailable("暂未提供图传播放参数")) + } + + /// 显式注入的本地文件与设备回执分离,界面始终标明模拟来源。 + func testExplicitLocalFileEnablesOnlyMarkedSimulation() async throws { + let file = try localFixture() + defer { try? FileManager.default.removeItem(at: file) } + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response())) + let model = makeModel(service: service, file: file) + await model.refresh() + XCTAssertEqual(model.state, .localPreview(file)) + XCTAssertEqual(model.playbackURL, file) + XCTAssertEqual(model.title, "本地模拟画面") + XCTAssertTrue(model.message.contains("未连接无人机")) + model.invalidate() + XCTAssertNil(model.playbackURL) + XCTAssertNil(model.response) + XCTAssertEqual(model.state, .idle) + } + + /// 模拟注入也拒绝远程地址与不存在的文件,不能通过假模拟连接设备或外网。 + func testRemoteAndMissingLocalPreviewAreRejected() async throws { + for file in [URL(string: "https://example.invalid/live.mp4")!, + FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)] { + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response())) + let model = makeModel(service: service, file: file) + await model.refresh() + XCTAssertEqual(model.state, .failed("本地模拟视频不可用")) + XCTAssertNil(model.playbackURL) + } + } + + /// 没有已锁定机场时,不因注入了本地样片就跳过合同前置条件。 + func testMissingLockedAirportDoesNotBecomeSimulationSuccess() async throws { + let file = try localFixture() + defer { try? FileManager.default.removeItem(at: file) } + var fields = DroneDockLiveTestData.payload() + fields["airport_sn"] = NSNull() + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response(fields))) + let model = makeModel(service: service, file: file) + await model.refresh() + XCTAssertEqual(model.state, .unavailable("当前任务尚未返回已锁定的机场信息")) + XCTAssertNil(model.playbackURL) + } + + /// 纯内存服务也必须匹配任务和景区,不能绕过 API 适配层的身份校验。 + func testMismatchedTaskOrScenicIsRejected() async throws { + for change: [String: Any] in [["order_flight_task_id": 502], ["task": ["id": 501, "scenic_id": 129]]] { + let fields = DroneDockLiveTestData.payload().merging(change) { _, new in new } + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response(fields))) + let model = makeModel(service: service) + await model.refresh() + XCTAssertNil(model.response) + XCTAssertNil(model.playbackURL) + guard case .failed = model.state else { return XCTFail("不一致回执应失败") } + } + } + + /// 进行中重复点击不重复请求,加载开始回调可以同步刷新按钮状态。 + func testInFlightRequestIsExclusiveAndNotifiesLoadingOnce() async throws { + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response()), suspended: true) + let model = makeModel(service: service) + var starts = 0 + let pending = Task { @MainActor in + await model.refresh { starts += 1; XCTAssertTrue(model.isLoading); XCTAssertFalse(model.canLoad) } + } + await waitForRequest(service) + await model.refresh { starts += 1 } + XCTAssertEqual(service.requests, [501]) + XCTAssertEqual(starts, 1) + service.finish() + await pending.value + XCTAssertFalse(model.isLoading) + XCTAssertTrue(model.canLoad) + } + + /// 离页后迟到成功响应不能重建已释放的播放来源。 + func testInvalidationDiscardsLateResponse() async throws { + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response()), suspended: true) + let model = makeModel(service: service) + let pending = Task { @MainActor in await model.refresh() } + await waitForRequest(service) + model.invalidate() + service.finish() + await pending.value + XCTAssertEqual(model.state, .idle) + XCTAssertNil(model.response) + XCTAssertNil(model.playbackURL) + } + + /// 登录或景区切换后旧任务永久停用,不能用同一页面重试新身份的请求。 + func testIdentityChangeInvalidatesOldPage() async throws { + let scope = LiveContextTestBox() + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response()), suspended: true) + let model = DroneDockLiveViewModel(context: scope.value, taskID: 501, service: service, currentContext: { scope.value }) + let pending = Task { @MainActor in await model.refresh() } + await waitForRequest(service) + scope.value = DroneDockShootingTaskTestData.context(scenicID: 129) + service.finish() + await pending.value + XCTAssertFalse(model.canLoad) + XCTAssertNil(model.response) + XCTAssertEqual(model.state, .failed("账号或景区已变化,请返回工作台重新进入")) + await model.refresh() + XCTAssertEqual(service.requests, [501]) + } + + /// 请求取消不残留正在加载状态,迟到响应也不能显示成功。 + func testCancellationDiscardsLateSuccess() async throws { + let service = LiveParameterTestService(result: .success(try DroneDockLiveTestData.response()), suspended: true) + let model = makeModel(service: service) + let pending = Task { @MainActor in await model.refresh() } + await waitForRequest(service) + pending.cancel() + service.finish() + await pending.value + XCTAssertEqual(model.state, .idle) + XCTAssertFalse(model.isLoading) + XCTAssertNil(model.response) + } + + /// 超时只展示失败,由用户显式重试同一任务,没有后台自动重试。 + func testTimeoutRequiresExplicitRetry() async throws { + let service = LiveParameterTestService(result: .failure(URLError(.timedOut))) + let model = makeModel(service: service) + await model.refresh() + guard case .failed = model.state else { return XCTFail("超时应展示失败") } + XCTAssertEqual(service.requests, [501]) + service.result = .success(try DroneDockLiveTestData.response()) + await model.refresh() + XCTAssertEqual(service.requests, [501, 501]) + XCTAssertEqual(model.state, .unavailable("暂未提供图传播放参数")) + } + + private func makeModel(service: (any DroneDockLiveServing)? = nil, file: URL? = nil) -> DroneDockLiveViewModel { + let context = DroneDockShootingTaskTestData.context() + return DroneDockLiveViewModel(context: context, taskID: 501, service: service, localPreviewURL: file, + currentContext: { context }) + } + + private func localFixture() throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).mp4") + // ViewModel 只检查本地来源;这里不启动播放器,不把该测试字节当作可播放的视频。 + try Data("local-fixture".utf8).write(to: url) + return url + } + + private func waitForRequest(_ service: LiveParameterTestService) async { + for _ in 0..<100 where service.requests.isEmpty { await Task.yield() } + XCTAssertFalse(service.requests.isEmpty) + } +} + +/// 可暂停的图传参数替身,用于验证重复点击和离页后迟到回执。 +@MainActor +private final class LiveParameterTestService: DroneDockLiveServing { + var result: Result + private(set) var requests: [Int] = [] + private let suspended: Bool + private var continuation: CheckedContinuation? + + /// 配置纯内存结果,可暂停直到测试明确释放。 + init(result: Result, suspended: Bool = false) { + self.result = result + self.suspended = suspended + } + + /// 记录同一任务读取,不提供实际网络传输能力。 + func live(taskID: Int) async throws -> DroneDockLiveResponse { + requests.append(taskID) + if suspended { await withCheckedContinuation { continuation = $0 } } + return try result.get() + } + + /// 手动完成挂起请求,可模拟取消之后仍收到旧响应。 + func finish() { continuation?.resume(); continuation = nil } +} + +/// 允许主 Actor 测试显式切换当前身份,避免捕获可并发修改的局部变量。 +@MainActor +private final class LiveContextTestBox { + var value = DroneDockShootingTaskTestData.context() +} diff --git a/suixinkanTests/DroneDockResummonAPITests.swift b/suixinkanTests/DroneDockResummonAPITests.swift new file mode 100644 index 0000000..f4a7fec --- /dev/null +++ b/suixinkanTests/DroneDockResummonAPITests.swift @@ -0,0 +1,75 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 使用隔离网络验证重新召唤合同及禁飞拦截,不连接真实设备。 +@MainActor +final class DroneDockResummonAPITests: XCTestCase { + /// 重召唤只提交同一订单任务及布尔重启标记,不创建任务或覆盖选机、航线。 + func testResummonSendsOnlyExistingTaskAndTrueRestart() async throws { + let session = MockURLSession(responses: [Data(#"{"code":100000,"data":{"order_flight_task":{"id":501},"task_id":9001}}"#.utf8)]) + let client = APIClient(environment: .testing, session: session) + client.bindAuthTokenProvider { "resummon-test-token" } + let receipt = try await DroneDockShootAPI(client: client).resummon(taskID: 501) + XCTAssertEqual(session.requests.count, 1) + let request = try XCTUnwrap(session.requests.first) + XCTAssertEqual(request.url?.path, "/api/app/airport/shoot") + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "resummon-test-token") + let body = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: XCTUnwrap(request.httpBody)) + XCTAssertEqual(body, .object(["id": .number(501), "restart": .bool(true)])) + XCTAssertNotNil(receipt.dataJSON) + } + + /// 非正任务 ID 和调用前取消均在进入传输前终止。 + func testInvalidAndCancelledRequestsNeverReachTransport() async throws { + let session = MockURLSession(responses: []) + let api = DroneDockShootAPI(client: APIClient(environment: .testing, session: session)) + for id in [0, -1] { + do { _ = try await api.resummon(taskID: id); XCTFail("无效任务不应发送") } catch {} + } + let task = Task { try await api.resummon(taskID: 501) } + task.cancel() + do { _ = try await task.value; XCTFail("已取消请求不应发送") } catch is CancellationError {} + XCTAssertTrue(session.requests.isEmpty) + } + + /// 明确拒绝和超时均不在 API 层重发 POST。 + func testRejectedOrTimedOutResummonDoesNotRetry() async throws { + let rejection = MockURLSession(responses: [Data(#"{"code":100099,"msg":"模拟重启拒绝","data":[]}"#.utf8)]) + do { + _ = try await DroneDockShootAPI(client: APIClient(environment: .testing, session: rejection)).resummon(taskID: 501) + XCTFail("业务拒绝不能成功") + } catch let APIError.serverCode(code, message) { + XCTAssertEqual(code, 100099) + XCTAssertEqual(message, "模拟重启拒绝") + } + XCTAssertEqual(rejection.requests.count, 1) + let timeout = MockURLSession(results: [.failure(URLError(.timedOut))]) + do { + _ = try await DroneDockShootAPI(client: APIClient(environment: .testing, session: timeout)).resummon(taskID: 501) + XCTFail("超时不能成功") + } catch {} + XCTAssertEqual(timeout.requests.count, 1) + } + + /// 未声明隔离模拟传输时,restart=true 与首次召唤一样在请求发送前被阻断。 + func testDefaultTransportCannotSendRestartCommand() async throws { + let probe = ResummonTransportProbe() + let api = DroneDockShootAPI(client: APIClient(environment: .testing, session: probe)) + do { _ = try await api.resummon(taskID: 501); XCTFail("禁飞保护必须生效") } + catch is DeviceCommandDebugBlockedError {} + XCTAssertEqual(probe.requestCount, 0) + } +} + +/// 没有网络能力也没有模拟豁免标记,用于核对发送前拦截。 +private final class ResummonTransportProbe: URLSessionProtocol { + private(set) var requestCount = 0 + + /// 若被错误调用则记录后立即失败,永不回退 URLSession。 + func data(for request: URLRequest) async throws -> (Data, URLResponse) { + requestCount += 1 + throw URLError(.unsupportedURL) + } +} diff --git a/suixinkanTests/DroneDockResummonLiveViewTests.swift b/suixinkanTests/DroneDockResummonLiveViewTests.swift new file mode 100644 index 0000000..6646127 --- /dev/null +++ b/suixinkanTests/DroneDockResummonLiveViewTests.swift @@ -0,0 +1,290 @@ +import AVFoundation +import UIKit +import XCTest +@testable import suixinkan + +/// 通过隔离模拟入口验证重新召唤与图传区域交互,不连接后端或无人机。 +@MainActor +final class DroneDockResummonLiveViewTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 双击重召唤只提交一次原任务,回查更新页面,固定区域与旧读数保持不变。 + func testResummonSuccessUsesSameTaskOnceAndPreservesFixedLayout() async throws { + let controller = try makeController(kind: "resummon", result: "success") + let window = makeWindow(controller) + defer { close(window) } + let model = controller.viewModel + try await settle(window) { model.canResummon } + 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 + let button = try XCTUnwrap(find(controller.view, suffix: "failureRetry") as? UIButton) + capture(window, name: "重新召唤-失败任务-本地模拟") + + button.sendActions(for: .touchUpInside) + button.sendActions(for: .touchUpInside) + XCTAssertFalse(button.isEnabled) + XCTAssertEqual(model.presentation.title, oldTitle) + XCTAssertEqual(find(controller.view, suffix: "metric.battery")?.accessibilityValue, oldBattery) + try await settle(window) { + model.hasSubmittedResummon && !model.isResummoning && model.presentation.phase == .ready + } + XCTAssertFalse(model.canResummon) + XCTAssertTrue(model.canStartShooting) + for (suffix, frame) in zip(fixedIDs, frames) { + XCTAssertEqual(find(controller.view, suffix: suffix)?.frame, frame) + } + capture(window, name: "重新召唤-同任务回查成功-本地模拟") + + let entries = try await records(controller, window: window, name: "重新召唤-成功") + XCTAssertEqual(entries.compactMap { $0["method"] as? String }, ["GET", "POST", "GET"]) + let posts = entries.filter { $0["method"] as? String == "POST" } + XCTAssertEqual(posts.count, 1) + XCTAssertEqual(posts.first?["path"] as? String, "/api/app/airport/shoot") + let body = try XCTUnwrap(posts.first?["request_body"] as? [String: Any]) + XCTAssertEqual(Set(body.keys), ["id", "restart"]) + XCTAssertEqual(body["id"] as? Int, 901) + XCTAssertEqual(body["restart"] as? Bool, true) + XCTAssertEqual(entries.filter { $0["path"] as? String == "/api/app/airport/shooting" }.count, 2) + XCTAssertFalse(entries.contains { ($0["path"] as? String)?.contains("/tasks/create") == true }) + } + + /// 明确业务拒绝保留失败快照,只有用户再次点击才重新请求,不偷偷创建任务。 + func testResummonBusinessFailureAllowsExplicitRetry() async throws { + let controller = try makeController(kind: "resummon", result: "business-failure") + let window = makeWindow(controller) + defer { close(window) } + let model = controller.viewModel + try await settle(window) { model.canResummon } + let original = model.response + let button = try XCTUnwrap(find(controller.view, suffix: "failureRetry") as? UIButton) + button.sendActions(for: .touchUpInside) + try await settle(window) { model.resummonErrorMessage != nil && !model.isResummoning } + XCTAssertFalse(model.resummonOutcomeUnknown) + XCTAssertFalse(model.hasSubmittedResummon) + XCTAssertEqual(model.response, original) + XCTAssertTrue(model.canResummon) + XCTAssertTrue(button.isEnabled) + capture(window, name: "重新召唤-业务拒绝-本地模拟") + + button.sendActions(for: .touchUpInside) + try await settle(window) { model.resummonErrorMessage != nil && !model.isResummoning } + let entries = try await records(controller, window: window, name: "重新召唤-明确拒绝后手动重试") + XCTAssertEqual(entries.compactMap { $0["method"] as? String }, ["GET", "POST", "POST"]) + XCTAssertTrue(entries.filter { $0["method"] as? String == "POST" }.allSatisfy { + $0["path"] as? String == "/api/app/airport/shoot" + && ($0["request_body"] as? [String: Any])?["restart"] as? Bool == true + }) + XCTAssertFalse(entries.contains { ($0["path"] as? String)?.contains("/tasks/create") == true }) + } + + /// 超时后锁定重复重召唤,旧失败快照不解锁,只允许手动读取同一任务。 + func testResummonTimeoutKeepsReadRefreshButPreventsSecondPost() async throws { + let controller = try makeController(kind: "resummon", result: "timeout") + let window = makeWindow(controller) + defer { close(window) } + let model = controller.viewModel + try await settle(window) { model.canResummon } + let button = try XCTUnwrap(find(controller.view, suffix: "failureRetry") as? UIButton) + button.sendActions(for: .touchUpInside) + try await settle(window) { model.resummonOutcomeUnknown && !model.isResummoning } + XCTAssertFalse(model.canResummon) + XCTAssertEqual(model.presentation.action, .refresh) + capture(window, name: "重新召唤-超时待核对-本地模拟") + + 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 && model.resummonOutcomeUnknown } + XCTAssertFalse(model.canResummon) + let entries = try await records(controller, window: window, name: "重新召唤-超时后只读回查") + XCTAssertEqual(entries.filter { $0["method"] as? String == "POST" }.count, 1) + XCTAssertEqual(entries.filter { $0["path"] as? String == "/api/app/airport/shooting" }.count, 2) + XCTAssertFalse(entries.contains { ($0["path"] as? String)?.contains("/tasks/create") == true }) + } + + /// 图传只读取一次并播放明确标记的本地样片;离开页面后释放 AVPlayer。 + func testLocalLivePreviewIsLabeledDoesNotPollAndStopsOnLeaving() async throws { + let controller = try makeController(kind: "live", result: "success") + let window = makeWindow(controller) + defer { close(window) } + try await settle(window) { + controller.liveViewModel.playbackURL != nil && !controller.viewModel.isLoading + } + let url = try XCTUnwrap(controller.liveViewModel.playbackURL) + XCTAssertTrue(url.isFileURL) + XCTAssertEqual(controller.liveViewModel.state, .localPreview(url)) + let source = try XCTUnwrap(find(controller.view, suffix: "live.source") as? UILabel) + XCTAssertFalse(source.isHidden) + XCTAssertEqual(source.text, "本地模拟画面 · 未连接无人机") + let feed = try XCTUnwrap(find(controller.view, suffix: "feedPlaceholder")) + let playerLayer = try XCTUnwrap(feed.layer.sublayers?.compactMap { $0 as? AVPlayerLayer }.first) + XCTAssertNotNil(playerLayer.player) + capture(window, name: "图传-明确标记的本地画面") + try await Task.sleep(nanoseconds: 350_000_000) + + let entries = try await records(controller, window: window, name: "图传-单次本地请求") + let liveEntries = entries.filter { $0["path"] as? String == "/api/app/airport/live" } + XCTAssertEqual(liveEntries.count, 1) + XCTAssertEqual(liveEntries.first?["method"] as? String, "GET") + XCTAssertEqual(liveEntries.first?["query"] as? String, "id=901") + XCTAssertFalse(entries.contains { $0["method"] as? String == "POST" }) + + controller.dismiss(animated: false) + try await settle(window) { controller.presentedViewController == nil } + controller.navigationController?.pushViewController(UIViewController(), animated: false) + try await settle(window) { playerLayer.player == nil } + XCTAssertNil(controller.liveViewModel.playbackURL) + } + + /// 接口只返回设备和任务时显示缺少播放参数,不用演示视频伪装真实流。 + func testLiveMissingPlaybackParametersShowsUnavailableWithoutPlayer() async throws { + let controller = try makeController(kind: "live", result: "missing-parameters") + let window = makeWindow(controller) + defer { close(window) } + try await settle(window) { controller.liveViewModel.response != nil && !controller.liveViewModel.isLoading } + XCTAssertEqual(controller.liveViewModel.state, .unavailable("暂未提供图传播放参数")) + XCTAssertNil(controller.liveViewModel.playbackURL) + XCTAssertEqual((find(controller.view, suffix: "live.status") as? UILabel)?.text, "暂未提供图传播放参数") + XCTAssertTrue(try XCTUnwrap(find(controller.view, suffix: "live.source")).isHidden) + let feed = try XCTUnwrap(find(controller.view, suffix: "feedPlaceholder")) + XCTAssertNil(feed.layer.sublayers?.compactMap { $0 as? AVPlayerLayer }.first?.player) + capture(window, name: "图传-缺少播放参数") + let entries = try await records(controller, window: window, name: "图传-缺少播放参数") + XCTAssertEqual(entries.filter { $0["path"] as? String == "/api/app/airport/live" }.count, 1) + XCTAssertFalse(entries.contains { $0["method"] as? String == "POST" }) + } + + /// 图传业务拒绝和超时均显示错误并允许显式重试,快速双击不叠加请求。 + func testLiveFailureAndTimeoutCanRetryWithoutStartingDeviceCommands() async throws { + for result in ["business-failure", "timeout"] { + let controller = try makeController(kind: "live", result: result) + let window = makeWindow(controller) + defer { close(window) } + try await settle(window) { + if case .failed = controller.liveViewModel.state { return !controller.liveViewModel.isLoading } + return false + } + XCTAssertNil(controller.liveViewModel.playbackURL) + XCTAssertFalse(controller.liveViewModel.message.isEmpty) + XCTAssertEqual((find(controller.view, suffix: "live.title") as? UILabel)?.text, "图传加载失败") + let button = try XCTUnwrap(find(controller.view, suffix: "live.request") as? UIButton) + XCTAssertTrue(button.isEnabled) + button.sendActions(for: .touchUpInside) + button.sendActions(for: .touchUpInside) + try await settle(window) { + if case .failed = controller.liveViewModel.state { return !controller.liveViewModel.isLoading } + return false + } + capture(window, name: "图传-\(result)-本地模拟") + let entries = try await records(controller, window: window, name: "图传-\(result)-手动重试") + XCTAssertEqual(entries.filter { $0["path"] as? String == "/api/app/airport/live" }.count, 2) + XCTAssertFalse(entries.contains { $0["method"] as? String == "POST" }) + } + } + + /// 默认页面不注入图传或重召唤能力,仅用隔离替身读取状态,保护不依赖模拟入口标签。 + func testDefaultPageKeepsLiveAndResummonRestricted() async throws { + let context = DroneDockShootingTaskTestData.context() + let service = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.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 } + XCTAssertEqual(controller.liveViewModel.state, .restricted) + XCTAssertFalse(controller.liveViewModel.canLoad) + XCTAssertFalse(model.canResummon) + XCTAssertNil(controller.liveViewModel.playbackURL) + XCTAssertTrue(try XCTUnwrap(find(controller.view, suffix: "live.request")).isHidden) + XCTAssertEqual((find(controller.view, suffix: "live.title") as? UILabel)?.text, "当前调试已停用实时图传") + XCTAssertEqual(service.requests.count, 1) + } + + private func makeController(kind: String, result: String) throws -> DroneDockShootingTaskViewController { + try XCTUnwrap(DroneDockStartShootSimulation.makeController( + arguments: ["--dock-\(kind)-mock", "--dock-\(kind)-result=\(result)"]) + as? DroneDockShootingTaskViewController) + } + + private func records(_ controller: UIViewController, window: UIWindow, name: String) 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 data = Data(text.text.utf8) + let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.json") + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + let transcript = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual(transcript["source"] as? String, "local_mock") + XCTAssertEqual(transcript["network_sent"] as? Bool, false) + return try XCTUnwrap(transcript["records"] as? [[String: Any]]) + } + + 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..<200 { + window.layoutIfNeeded() + if condition() { + try await Task.sleep(nanoseconds: 80_000_000) + window.layoutIfNeeded() + if condition() { return } + } + try await Task.sleep(nanoseconds: 15_000_000) + } + XCTFail("重新召唤或图传页面未在预期时间内完成状态更新") + throw NSError(domain: "DroneDockResummonLiveViewTests", 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/suixinkanTests/DroneDockResummonViewModelTests.swift b/suixinkanTests/DroneDockResummonViewModelTests.swift new file mode 100644 index 0000000..a01972a --- /dev/null +++ b/suixinkanTests/DroneDockResummonViewModelTests.swift @@ -0,0 +1,334 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 重召唤的同任务、防重和旧快照保护;全部依赖只在内存运行。 +@MainActor +final class DroneDockResummonViewModelTests: XCTestCase { + /// 正式入口未注入重启服务,即使任务失败也不会开放操作。 + func testDefaultReadonlyModelCannotResummon() async throws { + let fixture = try ResummonFixture(enabled: false) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canResummon) + XCTAssertFalse(fixture.model.presentation.isActionEnabled) + await fixture.model.resummon() + XCTAssertTrue(fixture.write.requests.isEmpty) + } + + /// 只开放当前任务明确失败的模拟状态,离线、返航及身份不完整不允许请求。 + func testIncompleteOrUnavailableSnapshotDoesNotPermitResummon() async throws { + let samples = [ + try ResummonData.snapshot(phase: "shooting", status: 20), + try ResummonData.snapshot(phase: "returning"), + try ResummonData.snapshot(plane: ["id": 58, "online_status": 2]), + try ResummonData.snapshot(plane: ["id": 0]), + try DroneDockShootingTaskTestData.response(changes: ["task": ["status": 40], "order_flight_task": ["status": 40]]) + ] + for snapshot in samples { + let fixture = try ResummonFixture() + fixture.read.result = .success(snapshot) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canResummon) + await fixture.model.resummon() + XCTAssertTrue(fixture.write.requests.isEmpty) + } + } + + /// 受理回执不切换成到达,待同任务 GET 成功后才更新状态。 + func testSuccessPreservesOldSnapshotUntilSingleSameTaskRefresh() async throws { + let fixture = try ResummonFixture() + await fixture.model.refresh() + let previous = fixture.model.response + let next = try ResummonData.snapshot(phase: "arrived_pending_start", status: 20) + fixture.write.onRequest = { fixture.read.result = .success(next) } + var sawReceiptWithOldSnapshot = false + await fixture.model.resummon { + if fixture.model.resummonResponse != nil && fixture.model.response == previous { + sawReceiptWithOldSnapshot = true + XCTAssertTrue(fixture.model.isResummoning) + XCTAssertFalse(fixture.model.presentation.isActionEnabled) + } + } + XCTAssertTrue(sawReceiptWithOldSnapshot) + XCTAssertEqual(fixture.write.requests, [501]) + XCTAssertEqual(fixture.read.requests.map(\.taskID), [501, 501]) + XCTAssertEqual(fixture.model.response, next) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertTrue(fixture.model.canStartShooting) + XCTAssertTrue(fixture.model.hasSubmittedResummon) + XCTAssertFalse(fixture.model.isResummoning) + } + + /// 后端仍返回旧失败快照时,刷新或离页回来不能使已受理重启再次发送。 + func testStaleFailureNeverReopensAcceptedResummon() async throws { + let fixture = try ResummonFixture() + await fixture.model.refresh() + await fixture.model.resummon() + XCTAssertEqual(fixture.model.presentation.phase, .failed) + XCTAssertEqual(fixture.model.presentation.action, .refresh) + XCTAssertTrue(fixture.model.presentation.isActionEnabled) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + fixture.model.invalidate(preservingSnapshot: true) + await fixture.model.refresh() + await fixture.model.resummon() + XCTAssertEqual(fixture.write.requests, [501]) + XCTAssertTrue(fixture.model.hasSubmittedResummon) + XCTAssertFalse(fixture.model.resummonOutcomeUnknown) + } + + /// 明确业务拒绝保留旧画面,仅用户再次点击时允许重试同一个任务。 + func testBusinessRejectionAllowsExplicitRetry() async throws { + let fixture = try ResummonFixture() + await fixture.model.refresh() + fixture.write.result = .failure(APIError.serverCode(100099, "模拟设备暂不可重启")) + await fixture.model.resummon() + XCTAssertEqual(fixture.model.resummonErrorMessage, "模拟设备暂不可重启") + XCTAssertFalse(fixture.model.resummonOutcomeUnknown) + XCTAssertTrue(fixture.model.canResummon) + XCTAssertEqual(fixture.read.requests.count, 1) + fixture.write.result = .success(ResummonData.receipt()) + await fixture.model.resummon() + XCTAssertEqual(fixture.write.requests, [501, 501]) + } + + /// 超时、HTTP 或解码错误结果未知,后续刷新只能查看,不能重复重启或控制。 + func testUnknownOutcomeRemainsLockedAcrossRefresh() async throws { + for failure in [APIError.networkFailed("超时"), APIError.httpStatus(500, "错误"), APIError.decodeFailed("损坏回执")] { + let fixture = try ResummonFixture() + await fixture.model.refresh() + let previous = fixture.model.response + fixture.write.result = .failure(failure) + await fixture.model.resummon() + XCTAssertTrue(fixture.model.resummonOutcomeUnknown) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertTrue(fixture.model.statusMessage.contains("重新召唤结果待核对")) + XCTAssertEqual(fixture.model.presentation.action, .refresh) + fixture.model.invalidate(preservingSnapshot: true) + fixture.read.result = .success(try ResummonData.snapshot(phase: "arrived_pending_start", status: 20)) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + await fixture.model.resummon() + XCTAssertEqual(fixture.write.requests, [501]) + } + } + + /// 本地拦截保证未发指令,不能被记录成后端结果未知。 + func testLocalBlockIsNotUnknownRemoteOutcome() async throws { + let fixture = try ResummonFixture() + await fixture.model.refresh() + fixture.write.result = .failure(DeviceCommandDebugBlockedError()) + await fixture.model.resummon() + fixture.model.invalidate(preservingSnapshot: true) + XCTAssertFalse(fixture.model.resummonOutcomeUnknown) + XCTAssertNil(fixture.model.resummonResponse) + XCTAssertEqual(fixture.model.resummonErrorMessage, DeviceCommandDebugPolicy.blockedMessage) + XCTAssertEqual(fixture.read.requests.count, 1) + } + + /// 重启在途禁止第二次重启、开拍、控制和刷新,旧快照仍可显示。 + func testPendingResummonMutuallyExcludesOtherOperations() async throws { + let fixture = try ResummonFixture() + 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.resummon() } + await fulfillment(of: [sent], timeout: 2) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertTrue(fixture.model.isResummoning) + await fixture.model.resummon() + await fixture.model.startShooting() + await fixture.model.sendCommand(.pause) + await fixture.model.refresh() + XCTAssertEqual(fixture.write.requests, [501]) + XCTAssertEqual(fixture.read.requests.count, 1) + XCTAssertEqual(fixture.actions.startCount, 0) + XCTAssertEqual(fixture.actions.commandCount, 0) + fixture.write.finish() + await pending.value + } + + /// 取消或页面失效后即使服务迟到返回成功,也不得回填或继续 GET。 + func testCancellationOrInvalidationIgnoresLateReceipt() async throws { + for invalidate in [false, true] { + let fixture = try ResummonFixture() + 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.resummon() } + await fulfillment(of: [sent], timeout: 2) + if invalidate { fixture.model.invalidate(preservingSnapshot: true) } else { pending.cancel() } + fixture.write.finish() + await pending.value + XCTAssertTrue(fixture.model.resummonOutcomeUnknown) + XCTAssertNil(fixture.model.resummonResponse) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertEqual(fixture.read.requests.count, 1) + XCTAssertFalse(fixture.model.isResummoning) + } + } + + /// 切换账号范围前不发请求,切换期间迟到回执撤下旧状态。 + func testIdentityChangeBeforeOrDuringSubmissionRejectsOldScope() async throws { + let before = try ResummonFixture() + await before.model.refresh() + before.scope.scenicID = 999 + await before.model.resummon() + XCTAssertTrue(before.write.requests.isEmpty) + XCTAssertNil(before.model.response) + let during = try ResummonFixture() + await during.model.refresh() + during.write.onRequest = { during.scope.scenicID = 999 } + await during.model.resummon() + XCTAssertNil(during.model.response) + XCTAssertNil(during.model.resummonResponse) + XCTAssertNil(during.model.resummonErrorMessage) + XCTAssertEqual(during.read.requests.count, 1) + } + + /// 错误订单任务身份不能当作成功;顶层航线 task_id 与订单任务不同是允许的。 + func testMismatchedReceiptDoesNotTriggerRead() async throws { + for json in [#"{"order_flight_task_id":999}"#, #"{"order_flight_task":{"id":999}}"#, + #"{"order_flight_task":{"order_number":"OTHER"}}"#, #"{"order_flight_task":{"scenic_id":999}}"#, + #"{"plane_id":999}"#] { + let fixture = try ResummonFixture() + await fixture.model.refresh() + fixture.write.result = .success(DroneDockShootResponse(dataJSON: json)) + await fixture.model.resummon() + XCTAssertTrue(fixture.model.resummonOutcomeUnknown) + XCTAssertNil(fixture.model.resummonResponse) + XCTAssertEqual(fixture.read.requests.count, 1) + } + } + + /// 受理后回查失败仍保留回执和旧状态,允许手动回查,不重复写入。 + func testAcceptedResummonWithFailedRefreshKeepsReceiptAndOldSnapshot() async throws { + let fixture = try ResummonFixture() + await fixture.model.refresh() + let previous = fixture.model.response + fixture.read.result = .failure(APIError.networkFailed("模拟查询失败")) + await fixture.model.resummon() + XCTAssertNotNil(fixture.model.resummonResponse) + XCTAssertEqual(fixture.model.response, previous) + XCTAssertFalse(fixture.model.resummonOutcomeUnknown) + XCTAssertEqual(fixture.model.presentation.action, .refresh) + XCTAssertTrue(fixture.model.presentation.isActionEnabled) + XCTAssertFalse(fixture.model.canResummon) + } + + /// 前一次开拍成功后任务失败,重启的新就绪快照可开始新一轮拍摄。 + func testNewReadySnapshotResetsPreviousStartSubmissionLock() async throws { + let fixture = try ResummonFixture() + fixture.read.result = .success(try ResummonData.snapshot(phase: "arrived_pending_start", status: 20)) + await fixture.model.refresh() + await fixture.model.startShooting() + XCTAssertTrue(fixture.model.hasSubmittedStart) + fixture.read.result = .success(try ResummonData.snapshot()) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.canResummon) + let nextReady = try ResummonData.snapshot(phase: "arrived_pending_start", status: 20) + fixture.write.onRequest = { fixture.read.result = .success(nextReady) } + await fixture.model.resummon() + XCTAssertFalse(fixture.model.hasSubmittedStart) + XCTAssertTrue(fixture.model.canStartShooting) + } + + /// 调用前已取消不发送,也不设置未知结果。 + func testCancelledBeforeSubmissionDoesNotSend() async throws { + let fixture = try ResummonFixture() + await fixture.model.refresh() + let pending = Task { await fixture.model.resummon() } + pending.cancel() + await pending.value + XCTAssertTrue(fixture.write.requests.isEmpty) + XCTAssertFalse(fixture.model.resummonOutcomeUnknown) + } +} + +/// 每个用例独立的只读、重启和控制替身,不访问共享登录状态。 +@MainActor +private struct ResummonFixture { + let scope = ResummonScope() + let read: DroneDockShootingTaskTestService + let write = ResummonWriteService() + let actions = ResummonOtherActions() + let model: DroneDockShootingTaskViewModel + + init(enabled: Bool = true) throws { + read = DroneDockShootingTaskTestService(result: .success(try ResummonData.snapshot())) + let boundScope = scope + model = DroneDockShootingTaskViewModel(context: boundScope.value, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: read, startService: actions, + commandService: actions, resummonService: enabled ? write : nil, currentContext: { boundScope.value }) + } +} + +/// 用于模拟请求前后的景区身份切换。 +@MainActor +private final class ResummonScope { + var scenicID = 128 + var value: DroneDockHomeContext { DroneDockShootingTaskTestData.context(scenicID: scenicID) } +} + +/// 支持挂起和错误注入的重启服务,无网络传输能力。 +@MainActor +private final class ResummonWriteService: DroneDockResummonServing { + var result: Result = .success(ResummonData.receipt()) + var onRequest: (() -> Void)? + var suspend = false + private(set) var requests: [Int] = [] + private var continuation: CheckedContinuation? + + /// 记录同一任务并返回当前合成回执。 + func resummon(taskID: Int) async throws -> DroneDockShootResponse { + requests.append(taskID) + onRequest?() + if suspend { return try await withCheckedThrowingContinuation { continuation = $0 } } + return try result.get() + } + + /// 结束挂起请求,允许测试取消和迟到回执。 + func finish() { continuation?.resume(with: result); continuation = nil } +} + +/// 用于验证开拍、指令与重启互斥的隔离替身。 +@MainActor +private final class ResummonOtherActions: DroneDockStartShooting, DroneDockCommandSending { + private(set) var startCount = 0 + private(set) var commandCount = 0 + + /// 返回合成开拍受理,不改变读取快照。 + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + startCount += 1 + return try JSONDecoder().decode(DroneDockStartShootResponse.self, from: Data(#"{"order_flight_task_id":501,"plane_id":58}"#.utf8)) + } + + /// 记录安全指令,不向设备发送请求。 + func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { + commandCount += 1 + throw APIError.serverCode(100099, "测试指令未启用") + } +} + +/// 合成状态明确标记模拟来源,订单任务 ID 与航线任务 ID 使用不同值。 +private enum ResummonData { + /// 构造失败或后续阶段快照,供验证受理回执不会覆盖真实状态。 + static func snapshot(phase: String = "failed", status: Int = 40, + plane: [String: Any] = ["id": 58, "online_status": 1, "work_status": 1]) throws -> DroneDockShootingResponse { + try DroneDockShootingTaskTestData.response(changes: [ + "order_flight_task": ["id": 501, "status": status], "task": ["id": 501, "status": status], + "current_plane": plane, + "execute_gate": ["can_execute": phase == "arrived_pending_start", "primary_action": "start_shoot"], + "ui": ["phase": phase, "title": "模拟阶段", "message": "本地模拟,无真实设备指令", + "commands": [["command": "flighttask_pause"]]]]) + } + + /// 顶层 task_id 是航线任务,不应误判为订单任务 ID 不一致。 + static func receipt() -> DroneDockShootResponse { + DroneDockShootResponse(dataJSON: #"{"order_flight_task":{"id":501},"task_id":9001,"source":"local_mock"}"#) + } +} diff --git a/suixinkanTests/DroneDockShootingTaskViewTests.swift b/suixinkanTests/DroneDockShootingTaskViewTests.swift index 4df2d16..8655dc9 100644 --- a/suixinkanTests/DroneDockShootingTaskViewTests.swift +++ b/suixinkanTests/DroneDockShootingTaskViewTests.swift @@ -42,7 +42,7 @@ final class DroneDockShootingTaskViewTests: XCTestCase { XCTAssertTrue(texts.contains("航线任务未关联")) XCTAssertTrue(texts.contains("测试任务需要等待服务端准备完成")) XCTAssertTrue(texts.contains("空闲 · 电量93%")) - XCTAssertTrue(texts.contains("图传暂未接入")) + XCTAssertTrue(texts.contains("当前调试已停用实时图传")) let values = ["battery": "93%", "temperature": "—", "wind": "0m/s", "rain": "—", "signal": "—", "satellite": "32颗"] for (key, value) in values { diff --git a/朱工-实时图传与重新召唤接口确认.md b/朱工-实时图传与重新召唤接口确认.md new file mode 100644 index 0000000..baf5909 --- /dev/null +++ b/朱工-实时图传与重新召唤接口确认.md @@ -0,0 +1,59 @@ +# 拍摄任务页:实时图传与重新召唤接口确认 + +日期:2026-10-30 + +适用范围:随心瞰商家版 iOS,类型 25 多点位航拍订单。 + +朱工,App 已完成拍摄任务页图传请求、状态展示及失败后重新召唤的客户端代码和本地模拟验证;真实图传播放仍需补齐协议。下面是现有文档已明确的约定,以及需要补充的字段与规则,可直接在原接口文档中更新。 + +**当前仍处于禁飞调试阶段。客户端只使用不联网的 Mock 和本地演示视频,不真实调用 `live` 或 `shoot`,也不创建真实待飞任务。本地模拟通过不代表后端受理、设备执行或真实图传成功。** + +## 1. 任务 ID 与调用方式 + +所有请求均使用张工 `tasks/create` 返回的订单飞行任务 ID,即 `order_flight_task.id`。不能把 `shoot` 响应中的实际航线任务 `task_id` / `wayline_task_id` 当作后续接口的 `id`。 + +| 用途 | 请求 | 客户端处理 | +| --- | --- | --- | +| 读取图传信息 | `GET /api/app/airport/live?id=501` | 当前文档要求任务已锁定 `airport_sn`,后端按任务找到飞机。 | +| 失败后重新召唤 | `POST /api/app/airport/shoot`,Body:`{"id":501,"restart":true}` | 按同一订单飞行任务预接,不再调用 `tasks/create`,不传 `plane_id` 或覆盖航线;`restart=true` 的具体规则请按第 3 节确认。 | +| 回查任务状态 | `GET /api/app/airport/shooting?id=501&live_battery=0` | 受理后读取同一任务,不把 POST 受理回执直接当作已到达,也不自动重复召唤。 | + +以上 ID 为示意值,不是本次真实联调任务。 + +## 2. 实时图传:请补齐可播放合同 + +当前 `live` 响应示例只有 `order_flight_task_id`、`airport`、`drone`、`task`、`airport_sn`、`metrics`,还没有可用于播放器建立连接的参数。请补充: + +| 需要确认 | 请提供的内容 | +| --- | --- | +| 播放技术 | 实际协议、服务厂商;若需 RTC SDK,请给 iOS SDK 名称、版本及接入文档。若是可直接播放的流,请说明协议。由后端实际实现决定,App 不预设。 | +| 连接参数 | 成功响应中全部播放参数的字段名、类型、是否可空、用途。若方案需要应用标识、房间/频道、用户标识、订阅流标识、Token 或播放 URL,请按实际方案给出,不能只返回空对象。 | +| 任务与画面对应 | 如何确认收到的是当前任务锁定飞机的画面;任务换机、重召唤后,原连接是否失效,是否需要重新获取参数。 | +| 有效期与重连 | 凭证/URL 有效期、刷新方法;断线、切后台、返回前台和重复进入页面时如何重连;是否需要主动关闭会话。 | +| 设备影响 | `GET live` 是只读已有流,还是会启动设备推流?停止、续期及重连是否会给设备下指令?请明确哪些操作具备设备副作用。 | +| 不可用状态 | 任务未锁定飞机、设备离线、暂未出流、凭证过期、无权限时的 HTTP 状态、业务码、提示文案,以及客户端是否可重试。 | + +请提供至少一份**完整、脱敏的成功 JSON**和一份**不可播放/拒绝 JSON**,包含实际统一响应包。字段结构、枚举、有效期保留;真实 Token、密钥、签名及可用设备凭证替换为占位值。播放参数的字段名应由正式合同明确,客户端不会把猜测字段当作真实协议。 + +禁飞期间,如需验证真实播放器连接,请提供明确不会操作设备的独立模拟服务或录制样例,并说明隔离方式。未确认前,App 继续使用本地文件模拟,不通过测试环境或自行增加 `dry_run` 参数尝试真实图传。 + +## 3. 重新召唤:请确认 `restart=true` 的业务规则 + +现有文档列出了 `restart`,但尚未说明失败后重启的完整语义。请确认: + +1. **适用状态与权限:**哪些任务状态、航线失败码允许重新召唤?取消任务、主动返航中断、返航中、离线、低电量是否允许?`shooting` 能否明确返回“允许重新召唤”及不可用原因,并说明字段位置和值?现有 `execute_gate.can_execute` 描述的是开始拍摄,App 不将其当成重召唤许可。 +2. **任务与飞机:**是否始终复用原 `order_flight_task.id`?是否新建实际航线任务并更新 `wayline_task_id/task_uuid`?原飞机锁定如何处理,哪些情况下重新派机?不传 `plane_id/air_line_id` 是否足够? +3. **状态、素材与次数:**重启会重置哪些失败/执行字段?原素材是否保留?拍摄次数何时扣减,如何保证同一订单飞行任务不会因重启重复扣次?已经成功计次的任务是否禁止重启? +4. **受理与设备到达:**`shoot` 返回成功代表排队、已下发还是设备已确认?后续 `shooting` 如何表示正在重新召唤、前往点位、已到达、再次失败?请给对应状态和 UI 字段示例。 +5. **重复请求与结果未知:**同一任务重复提交 `restart=true` 时后端如何防重?请求超时后应查询哪些字段判断“已受理”或“明确未执行”?何种拒绝可由用户重试,何种情况必须等待?若需要幂等标识,请给字段及生成/复用规则。 + +请补充**重召唤成功、明确拒绝**的完整脱敏响应,以及成功后的 `shooting` 状态示例。未明确结果前,客户端保持禁止重复提交,不通过重新创建任务规避失败。 + +## 4. 客户端交付边界 + +- 按现有文档接入请求参数、响应解析和任务身份校验;页面保留最近一次任务数据,避免请求时闪回空态。 +- 重新召唤使用同一任务,验证重复点击、业务拒绝、超时和离页后的迟到回执;禁飞期间仅在显式本地模拟入口开放。 +- 图传区域支持加载、不可用、失败及本地演示画面;本地视频始终标明模拟来源。收到真实播放合同前,不显示“真实图传已连接”。 +- 原有禁飞拦截继续生效。后续补齐协议后可完成真实播放器适配;真实设备联调须等禁飞限制明确解除并取得授权。 + +本文件只记录接口确认事项,不作为真实飞行或图传联调通过的验收记录。 diff --git a/机巢工作台页面接口对接记录.md b/机巢工作台页面接口对接记录.md index 1c5ded3..8c74887 100644 --- a/机巢工作台页面接口对接记录.md +++ b/机巢工作台页面接口对接记录.md @@ -2,7 +2,7 @@ > 更新日期: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` 已实现纯本地模拟(见 7.6.3),真实控制保持禁用;图传尚未接入;2026-10-30 已完成真实成片上传、保存及回查,见 9.4。 +> 核对范围:当前工作区。准备页使用张工 `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),真实控制保持禁用;图传请求及状态已预接(本地模拟,真实播放协议待朱工补齐,见 7.6.4);2026-10-30 已完成真实成片上传、保存及回查,见 9.4。 > 用途:记录每个页面实际调用的接口、提供人、调用时机、请求参数和返回 JSON,供 iOS 与后端持续联调。 ## 1. 阅读说明 @@ -25,7 +25,7 @@ ## 2. 页面与接口总览 -当前机巢模块已实现 **17 个业务接口及 1 个通用 STS 接口**(其中 `start-shoot`、`command` 仅启用纯本地模拟)。游客交付确认新增 `orders/confirm-code`,并复用 `orders/detail` 和 `tasks`,见 9.5。拍摄任务页复用已实现的 `shooting` API;它由任务页读取,准备页不直接调用。`shooting` 已取得类型 25 的真实响应;`tasks/create → shoot` 对任务 6 业务成功,但随后回查显示航线执行失败、禁止拍摄。任务页成功导航仍有网络替身测试覆盖;成片保存及 STS 上传已于 2026-10-30 完成真实联调,游客确认仍待真实联调。独立订单页复用首页已使用的 `orders`。 +当前机巢模块已实现 **18 个业务接口及 1 个通用 STS 接口**(其中 `start-shoot`、`command`、`shoot` 的重召唤和 `live` 仅启用纯本地模拟;`live` 的真实播放协议待补齐)。游客交付确认新增 `orders/confirm-code`,并复用 `orders/detail` 和 `tasks`,见 9.5。拍摄任务页复用已实现的 `shooting` API;它由任务页读取,准备页不直接调用。`shooting` 已取得类型 25 的真实响应;`tasks/create → shoot` 对任务 6 业务成功,但随后回查显示航线执行失败、禁止拍摄。任务页成功导航仍有网络替身测试覆盖;成片保存及 STS 上传已于 2026-10-30 完成真实联调,游客确认仍待真实联调。独立订单页复用首页已使用的 `orders`。 | 页面/区域 | 提供人 | 方法与完整路径 | 当前状态 | | --- | --- | --- | --- | @@ -45,6 +45,8 @@ | 拍摄任务页:任务摘要、六项读数与阶段状态 | 朱工 | `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/app/airport/live?id=原任务ID` | 已接请求和状态;本地模拟视频有明确来源标记,真实播放合同待补,禁飞期间不启用真实开流,见 7.6.4 | +| 拍摄任务页:失败后重新召唤 | 朱工 | `POST /api/app/airport/shoot`,`id/restart=true` | 已实现同任务纯内存模拟、受理后单次回查和防重;真实入口禁用,见 7.6.4 | | 订单素材库:整单摘要与点位标签 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/orders/detail` | 已接入 | | 订单素材库:任务、原素材与点位筛选 | 张工 | `GET /api/yf-handset-app/photog/multi-plane/tasks` | 已接入,不分页 | | 订单素材库:下载所选素材并保存相册 | 张工提供素材地址,客户端下载及保存 | `GET materials[].file_url` | 直接下载已就绪原素材;无需新增业务接口,见 8.3 | @@ -1256,6 +1258,18 @@ HTTP 200,完整业务响应: 详细场景、模拟器截图与完整回执见 [安全控制模拟记录](docs/9.9.1/safety-command-mock-2026-10-30/README.md)。当前仅验证客户端请求合同与交互;尚无后端真实指令受理或设备执行证据。 +### 7.6.4 实时图传与失败重召唤(2026-10-30,仅本地模拟) + +用户再次明确当前禁止飞行。真实任务页不注入 `live` 或重召唤服务;Debug 传输层仍阻断所有真实设备操作,无放行开关。本轮不请求真实 `live/shoot`,不创建真实待飞任务。 + +- 图传:`GET /api/app/airport/live?id=901`。解析文档已知任务、机场和读数字段,严格核对原订单飞行任务 ID。文档尚无播放协议、URL 或 RTC 凭证,只有已知 JSON 时显示“暂未提供图传播放参数”;不猜字段、不将接口响应当作真实连接成功。 +- 图传演示使用独立注入的随包 MP4,画面固定标注“本地模拟画面 · 未连接无人机”。离页或后台释放播放器并作废迟到响应;无定时轮询。模拟入口 `--dock-live-mock`,`--dock-live-result=success/missing-parameters/business-failure/timeout`。 +- 失败后重新召唤:只发送 `POST /api/app/airport/shoot`,Body `{"id":901,"restart":true}`。始终使用原订单任务,不调用 `tasks/create`,不覆盖飞机或航线。受理后只读同一任务 `shooting` 一次,继续保留旧状态直至新快照到达。 +- 连点只发一次;明确业务拒绝可手动再试;超时、取消或身份不一致导致结果未知时只允许状态回查。受理后仍返回旧失败快照不会重新解锁召唤。正式后端重启权限尚待确认,不能把开拍 `execute_gate.can_execute` 当作重召唤许可。 +- 重召唤模拟入口 `--dock-resummon-mock`,`--dock-resummon-result=success/business-failure/timeout`。模拟任务固定为 `901`,会话不联网,未知请求在本机失败。 + +完整模拟响应、验证结果与截图见 [本地验证记录](docs/9.9.1/live-resummon-mock-2026-10-30/README.md)。可直接转给后端的确认清单见 [朱工-实时图传与重新召唤接口确认.md](朱工-实时图传与重新召唤接口确认.md)。模拟结果不代表后端或无人机执行成功。 + ### 7.7 “确认并召唤”:朱工 shoot,复用已创建任务 API:[DroneDockShootAPI.swift](suixinkan/Features/DroneDock/API/DroneDockShootAPI.swift) @@ -1703,7 +1717,7 @@ UI 验证:确认页 5 项与共用交付流程 8 项回归全部通过,导 | 页面/功能 | 当前实现状态 | 文档中的后续候选接口与提供人 | 返回 JSON 记录 | | --- | --- | --- | --- | | 历史演示订单页 `DroneShootingOrdersViewController` | 仅演示流程继续使用本地数据;正式首页“查看全部”已进入真实 `DroneDockOrdersViewController` | 正式页张工 `GET /orders` 已接入,见 4.4 | 演示数据不能作为接口实测证据 | -| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台或导航栏/中间刷新各只读一次,无下拉刷新或定时轮询;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;`/airport/start-shoot` 已实现纯本地模拟、真实入口禁用;`/airport/command` 已实现纯本地模拟、真实入口禁用;图传 `/airport/live` 尚未接入,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;开始拍摄模拟回执见 7.6.2;尚无真实开始拍摄或控制成功记录 | +| 拍摄任务页 `DroneDockShootingTaskViewController` | 顶部和底部固定,中间按状态组合且无滚动;进入、可见时返回前台或导航栏/中间刷新各只读一次,无下拉刷新或定时轮询;明确完成态可查看订单素材 | 朱工 `/airport/shooting` 已接入;`/airport/start-shoot` 已实现纯本地模拟、真实入口禁用;`/airport/command` 已实现纯本地模拟、真实入口禁用;图传 `/airport/live` 已预接请求及本地播放,待补真实播放合同;失败重召唤 `shoot restart=true` 已完成本地模拟,当前不另调 `/airport/status` | 类型 25 真实读取成功见 7.6;开始拍摄模拟回执见 7.6.2;尚无真实开始拍摄或控制成功记录 | | 历史素材演示/下载 `DroneMaterialsViewController`、`DroneMaterialPreviewViewController` | 仅演示流程保留;正式入口已切换真实素材库,正式下载与保存相册见 8.3 | 张工返回有效原素材 URL,由客户端直接下载;历史演示仍不代表真实下载 | 正式页面响应见第 8 节 | | 历史交付演示 `DroneDeliveryUploadViewController`、`DroneDeliveryReviewViewController` | 仅演示流程保留;正式上传使用第 9 节新共用页,正式游客确认使用 9.5 新页 | 张工 `POST /orders/confirm-code`、`GET /orders/detail` 已实现 | 正式上传记录见第 9 节;游客确认暂无真实扫码回执,模拟结果见 9.5 | | 收款页“线下收款” | 跳转既有 `OfflineCollectionRegistrationViewController` | 复用原通用线下收款模块,不属于本次机巢类型 25 专用接口接入 | 本文未审计该旧模块 JSON,不将它记为新接口已打通 |