feat: 完善机巢图传、拍摄阶段与任务交互

- 完善双路 RTC 接收、首帧切换及拍摄结束后的本地播放释放
- 对齐无人机状态枚举与正常拍完返航标记,新增到达后本地倒计时
- 补充准备页电量与前往回执,进入任务时移除准备页路由
- 对齐拍摄中和拍摄完成原型布局,移除详情按钮
- 补充隔离测试、接口记录与项目约定

验证:最近 157 项相关模拟器隔离测试通过,Release 无签名编译通过;未调用真实飞控或图传。
This commit is contained in:
2026-11-03 16:43:23 +08:00
parent 0ed0077ec4
commit 54210925f0
33 changed files with 3242 additions and 205 deletions
@@ -22,7 +22,7 @@ enum DeviceCommandDebugPolicy {
/// 页面与本地拦截共用的说明,不将未发送的请求表述为服务端执行失败。
static let blockedMessage = "当前禁止真实设备指令,请使用本地模拟调试"
/// 在日志和传输之前阻断操作请求;允许的状态读取关闭实时设备采集。
/// 在日志和传输之前阻断操作请求;Release 准备页可读实时电量,其余状态读取关闭实时采集。
static func prepare(_ request: URLRequest, isLocalSimulation: Bool) throws -> URLRequest {
guard !isLocalSimulation, let url = request.url else { return request }
let path = "/" + url.path.split(separator: "/").joined(separator: "/")
@@ -43,6 +43,10 @@ enum DeviceCommandDebugPolicy {
guard request.httpMethod == "GET", readablePaths.contains(path) else {
throw DeviceCommandDebugBlockedError()
}
#if !DEBUG
// 2026-11-03 用户要求准备页获取电量;保留调用方的 live_battery,任务页仍强制读缓存。
if path == "/api/app/airport/plane-status" { return request }
#endif
let liveKey: String
switch path {
case "/api/app/airport/plane-status", "/api/app/airport/shooting": liveKey = "live_battery"
@@ -70,13 +70,13 @@ struct DroneDockHomeAirport: Decodable, Equatable, Sendable {
let snNumber: String?
/// 后端设备所属景区 ID。
let scenicAreaID: Int?
/// 原始在线状态;尚未取得完整枚举约定。
/// 飞机表在线标记:1 在线,其他已提供整数为离线;忙闲以 workStatus 为准。
let onlineStatus: Int?
/// 原始工作状态;不据此决定设备可否执行任务。
let workStatus: Int?
/// 后端工作状态展示文案。
let workStatusLabel: String?
/// 原始接单配置;不等同于本次起飞许可。
/// 接单配置:1 可接单、2 暂停接单;不等同于本次起飞许可。
let isReceiveOrder: Int?
/// 任务类型原始值;当前样本为 null,暂不假定其枚举或值类型。
let taskType: DroneDockHomeJSONValue?
@@ -1,6 +1,6 @@
import Foundation
/// shoot 业务成功后的原始 data 回执,不假设或构造飞机、任务及飞行阶段字段。
/// 保留 shoot 原始 data,并读取明确的同任务前往回执;不补造飞机或飞行阶段字段。
struct DroneDockShootResponse: Decodable, Equatable, Sendable {
/// 完整 data JSON;nil 表示统一客户端未提供 data,不补造 null 或空对象。
let dataJSON: String?
@@ -15,6 +15,30 @@ struct DroneDockShootResponse: Decodable, Equatable, Sendable {
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
dataJSON = String(decoding: try encoder.encode(DroneDockShootJSONSnapshot(value: raw)), as: UTF8.self)
}
/// 只认同一订单任务明确受理的前往阶段,用于进页过渡;回执不代表已经起飞或到达。
func confirmsTravel(taskID: Int, orderNumber: String?, scenicID: Int) -> Bool {
guard taskID > 0, scenicID > 0, let orderNumber, !orderNumber.isEmpty, let dataJSON,
let receipt = try? JSONDecoder().decode(DroneDockSummonProgressReceipt.self, from: Data(dataJSON.utf8)),
receipt.accepted == true, receipt.ui?.phase == "going_to_spot",
receipt.orderFlightTask?.id == taskID,
receipt.orderFlightTask?.orderNumber == orderNumber,
receipt.orderFlightTask?.scenicID == scenicID else { return false }
return receipt.orderFlightTaskID == nil || receipt.orderFlightTaskID == taskID
}
}
/// 首次召唤的已约定阶段和任务身份,仅支持显示前往中的过渡,不据此开放任何操作。
private struct DroneDockSummonProgressReceipt: Decodable {
let accepted: Bool?
let ui: DroneDockShootingUI?
let orderFlightTaskID: Int?
let orderFlightTask: DroneDockResummonReceiptIdentity.TaskIdentity?
/// 顶层 task_id 是航线任务,不参与订单任务匹配。
private enum CodingKeys: String, CodingKey {
case accepted, ui, orderFlightTaskID = "order_flight_task_id", orderFlightTask = "order_flight_task"
}
}
/// 重新召唤回执中可核对的订单任务身份;顶层 task_id 属于实际航线任务,不作订单任务 ID 使用。
@@ -16,6 +16,8 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
let metricsUpdatedAt: String?
/// 设备缓存过期时保留数值,但标为非实时读数。
let metricsStale: Bool?
/// 后端确认本批次正常拍完并开始返航;缺失表示旧合同,不能从工作态忙闲推断。
let shootCompleteReturning: Bool?
/// 后端若明确提供订单号则保留,不由请求上下文伪造响应身份。
let orderNumber: String?
/// 实测返回的订单飞行任务身份;存在时必须与请求上下文核对。
@@ -48,6 +50,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
case orderFlightTaskID = "order_flight_task_id", stateVersion = "state_version"
case executionBatch = "execution_batch", snapshotKind = "snapshot_kind"
case stateUpdatedAt = "state_updated_at", metricsUpdatedAt = "metrics_updated_at", metricsStale = "metrics_stale"
case shootCompleteReturning = "shoot_complete_returning"
case orderNumber = "order_number", orderFlightTask = "order_flight_task", task
case scenic, scenicSpot = "scenic_spot", airLine = "air_line"
case header, currentPlane = "current_plane", executeGate = "execute_gate", ui
@@ -64,6 +67,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
stateUpdatedAt = try container.decodeIfPresent(String.self, forKey: .stateUpdatedAt)
metricsUpdatedAt = try container.decodeIfPresent(String.self, forKey: .metricsUpdatedAt)
metricsStale = try container.decodeIfPresent(Bool.self, forKey: .metricsStale)
shootCompleteReturning = try container.decodeIfPresent(Bool.self, forKey: .shootCompleteReturning)
orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber)
orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask)
task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task)
@@ -91,22 +95,25 @@ struct DroneDockShootingTaskIdentity: Decodable, Equatable, Sendable {
let orderNumber: String?
/// 任务所属景区。
let scenicID: Int?
/// 后端原始任务状态,不与订单状态混用。
/// 订单飞行任务状态:10 待执行、20 执行中、30 成功、40 失败、50 取消、60 待确认。
let status: Int?
/// 服务端任务状态文案。
let statusLabel: String?
/// 实测航线任务状态,与订单飞行任务状态分别保留。
/// 航线状态独立保留:29/39/49/91 失败,90 取消,24/30/40 为录制后的素材处理。
let waylineStatus: Int?
/// 服务端航线状态文案;执行失败优先于笼统的订单任务执行中。
let waylineStatusLabel: String?
/// 服务端实际记录的任务结果原因,空值不视为具体失败说明。
let resultMessage: String?
/// 任务结果原因码;return_home 表示手动返航中断,不能展示正常拍完提示。
let resultCode: String?
/// 已确认嵌套任务字段映射。
private enum CodingKeys: String, CodingKey {
case id, orderNumber = "order_number", scenicID = "scenic_id", status, statusLabel = "status_label"
case waylineStatus = "wayline_status", waylineStatusLabel = "wayline_status_label"
case resultMessage = "result_message"
case resultCode = "result_code"
}
}
@@ -169,7 +176,7 @@ struct DroneDockShootingPlane: Decodable, Equatable, Sendable {
let id: Int?
/// 当前设备序列号。
let snNumber: String?
/// 服务端连接状态;实测 2 为离线,不从电量推导连接状态。
/// 飞机表在线标记:1 在线,0/2 等非 1 为离线;不覆盖明确的机巢工作态。
let onlineStatus: Int?
/// 文档工作状态:0 离线、1 空闲、2 拍摄中;不据此推断返航完成。
let workStatus: Int?
@@ -213,15 +220,28 @@ struct DroneDockShootingUI: Decodable, Equatable, Sendable {
let title: String?
/// 服务端阶段说明,不由 GET 请求成功拼造飞行进度。
let message: String?
/// 拍摄环节子阶段,shoot_done_returning 表示正常拍完后开始返航。
let waylineStage: String?
/// 页面层的正常拍完返航标记,和顶层字段共同保留。
let shootCompleteReturning: Bool?
/// 服务端实际提供的安全指令;缺失时保持未知,不据阶段文案自行补齐。
let commands: [DroneDockShootingCommand]?
/// 保留既有展示构造方式,新增动作列表默认为未知。
init(phase: String?, title: String?, message: String?, commands: [DroneDockShootingCommand]? = nil) {
init(phase: String?, title: String?, message: String?, commands: [DroneDockShootingCommand]? = nil,
waylineStage: String? = nil, shootCompleteReturning: Bool? = nil) {
self.phase = phase
self.title = title
self.message = message
self.commands = commands
self.waylineStage = waylineStage
self.shootCompleteReturning = shootCompleteReturning
}
/// 保留现有页面字段,并映射新增返航标记的原始命名。
private enum CodingKeys: String, CodingKey {
case phase, title, message, commands
case waylineStage = "wayline_stage", shootCompleteReturning = "shoot_complete_returning"
}
}
@@ -12,6 +12,8 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
case shooting
/// 录制已结束,素材仍在下载、上传或渲染,尚未就绪。
case postShootUploading
/// 录制已结束,但素材上传或渲染失败;可查看素材,不代表可重新召唤。
case postShootUploadFailed
/// 服务端明确已暂停。
case paused
/// 服务端明确正在返航。
@@ -62,10 +64,13 @@ struct DroneDockTaskPresentation: Equatable, Sendable {
let isActionEnabled: Bool
/// 主动作下方的真实设备限制说明,未提供时不展示。
let actionNote: String?
/// 已到达阶段的本地展示倒计时;零秒不表示后端已经开始拍摄。
let countdownSeconds: Int?
/// 创建状态展示;动作提示默认为空,既有非失败状态保持原布局。
init(phase: DroneDockTaskDisplayPhase, title: String, message: String, deviceStatus: String,
action: DroneDockTaskDisplayAction, actionTitle: String?, isActionEnabled: Bool, actionNote: String? = nil) {
action: DroneDockTaskDisplayAction, actionTitle: String?, isActionEnabled: Bool, actionNote: String? = nil,
countdownSeconds: Int? = nil) {
self.phase = phase
self.title = title
self.message = message
@@ -74,5 +79,6 @@ struct DroneDockTaskPresentation: Equatable, Sendable {
self.actionTitle = actionTitle
self.isActionEnabled = isActionEnabled
self.actionNote = actionNote
self.countdownSeconds = countdownSeconds
}
}
@@ -99,7 +99,7 @@ final class DroneDockLiveViewModel {
case .failed, .unavailable: return "重试"
case .localPreview: return "重新加载模拟图传"
case .connecting: return nil
case .playing: return "刷新图传"
case .playing: return nil
}
}
@@ -137,8 +137,14 @@ final class DroneDockLiveViewModel {
let canKeepSession = keepingPlayback && playbackSessionID != nil
&& sameDevice
&& rtcConfigurations.first?.appID == configurations.first?.appID
rtcConfigurations = configurations
rtcConfiguration = configurations.first
rtcConfigurations = configurations.map { incoming in
// live 每次可能生成新 user_id;补流时保留尚未临期的原入房身份,避免销毁健康房间。
guard canKeepSession, let previous = rtcConfigurations.first(where: { $0.role == incoming.role }),
previous.appID == incoming.appID, previous.roomID == incoming.roomID,
previous.userID != incoming.userID, previous.expiresAt.timeIntervalSince(now()) > 30 else { return incoming }
return previous
}
rtcConfiguration = rtcConfigurations.first
if !canKeepSession {
activeRole = nil
playbackSessionID = UUID()
@@ -430,15 +430,17 @@ final class DroneDockPreparationViewModel {
guard let selectedRoute else { return "\(selectedSpot.name) · 未选航线" }
return "\(selectedSpot.name) · \(selectedRoute.name)"
}
/// 优先展示服务端推荐无人机的完整文案,不自行重选列表中的另一架。
/// 展示后端推荐设备,状态文案缺少电量时补充电量字段,不重选设备或把未知电量当零。
var deviceStatusText: String {
guard let planeStatus else { return "状态待确认" }
guard let recommendation = planeStatus.recommend else {
return planeStatus.planes.isEmpty ? "暂无无人机" : "状态待确认"
}
if let text = DroneDockHomeMetric.usableText(recommendation.statusText) { return text }
let state = DroneDockHomeMetric.usableText(recommendation.workStatusLabel) ?? "状态待确认"
let battery = DroneDockHomeMetric.usableText(recommendation.batteryLabel)
let state = DroneDockHomeMetric.usableText(recommendation.statusText)
?? DroneDockHomeMetric.usableText(recommendation.workStatusLabel) ?? "状态待确认"
let percent = recommendation.batteryPercent.flatMap { (0...100).contains($0) ? $0 : nil }
let battery = DroneDockHomeMetric.usableText(recommendation.batteryLabel) ?? percent.map { "电量 \($0)%" }
if state.contains("%") || state.contains("%") || battery.map({ state.contains($0) }) == true { return state }
return battery.map { "\(state) · \($0)" } ?? state
}
/// 状态颜色只映射文档定义的工作状态,未知值不展示为空闲。
@@ -50,6 +50,8 @@ final class DroneDockShootingTaskViewModel {
private let commandService: (any DroneDockCommandSending)?
private let resummonService: (any DroneDockResummonServing)?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private let countdownNow: @Sendable () -> ContinuousClock.Instant
private var arrivalCountdownDeadlines: [String: ContinuousClock.Instant] = [:]
/// 无权限或登录失效后停止自动读取,旧数据仅用于展示。
private(set) var readAccessError: String?
private var snapshotRevision = 0
@@ -62,6 +64,8 @@ final class DroneDockShootingTaskViewModel {
private var resummonGeneration = 0
private var didSendResummon = false
private var awaitingResummonSnapshot = false
// 仅在首份完整快照返回之前使用同一任务的 going_to_spot 回执,不补造设备状态。
private var hasInitialTravelReceipt: Bool
// 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。
private var pendingAcceptedCommands: Set<DroneDockSafetyCommand> = []
@@ -71,6 +75,8 @@ final class DroneDockShootingTaskViewModel {
startService: (any DroneDockStartShooting)? = nil,
commandService: (any DroneDockCommandSending)? = nil,
resummonService: (any DroneDockResummonServing)? = nil,
initialSummonReceipt: DroneDockShootResponse? = nil,
countdownNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now },
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.taskID = taskID
@@ -80,6 +86,9 @@ final class DroneDockShootingTaskViewModel {
self.commandService = commandService
self.resummonService = resummonService
self.currentContext = currentContext
self.countdownNow = countdownNow
self.hasInitialTravelReceipt = context.canLoad && initialSummonReceipt?.confirmsTravel(
taskID: taskID, orderNumber: order.orderNumber, scenicID: context.scenicID) == true
}
/// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。
@@ -166,6 +175,10 @@ final class DroneDockShootingTaskViewModel {
}
}
response = value
if resolvedDisplayPhase().0 == .ready, arrivalCountdownDeadlines[recordingExecutionID] == nil {
arrivalCountdownDeadlines[recordingExecutionID] = countdownNow().advanced(by: .seconds(30))
}
hasInitialTravelReceipt = false
errorMessage = nil
snapshotRevision &+= 1
DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [
@@ -174,7 +187,7 @@ final class DroneDockShootingTaskViewModel {
"state_version": value.stateVersion as Any? ?? NSNull(),
"plane_id": value.currentPlane?.id as Any? ?? NSNull()
])
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .postShootUploading, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
awaitingResummonSnapshot = false
}
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
@@ -206,6 +219,8 @@ final class DroneDockShootingTaskViewModel {
generation &+= 1
isLoading = false
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
if identityInvalidated || !preservingSnapshot { hasInitialTravelReceipt = false }
if identityInvalidated || !preservingSnapshot { arrivalCountdownDeadlines.removeAll() }
if identityInvalidated {
response = nil
startResponse = nil
@@ -316,6 +331,7 @@ final class DroneDockShootingTaskViewModel {
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isTaskAwaitingConfirmation
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot
&& !pendingAcceptedCommands.contains(command)
@@ -396,6 +412,7 @@ final class DroneDockShootingTaskViewModel {
/// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。
var canResummon: Bool {
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isTaskAwaitingConfirmation
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
&& !hasSubmittedResummon && pendingAcceptedCommands.isEmpty
@@ -496,43 +513,102 @@ final class DroneDockShootingTaskViewModel {
usable(response?.currentPlane?.statusText) ?? usable(response?.currentPlane?.workStatusLabel) ?? "—"
}
/// 使用服务端阶段标题或任务状态,不从 GET 成功推导到达或拍摄完成。
/// 录制完成与素材就绪分别保留;只由可信阶段触发完成提示,不修改后端任务状态。
var isRecordingFinished: Bool {
let phase = resolvedDisplayPhase().0
return [.postShootUploading, .postShootUploadFailed, .completed].contains(phase)
|| (phase == .failed && hasMediaProcessingFailure)
}
/// 只有录制正常结束或素材就绪才弹出完成提示,素材处理失败只展示失败状态。
var shouldPresentRecordingCompletion: Bool {
[.postShootUploading, .completed].contains(resolvedDisplayPhase().0)
}
/// 正常拍完后的返航说明仅取本批次可信完成阶段,上传/渲染或显式清标记后不沿用。
var isShootCompleteReturning: Bool {
guard resolvedDisplayPhase().0 == .postShootUploading else { return false }
let waylines = [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus].compactMap { $0 }
guard !waylines.contains(where: { [30, 40, 50].contains($0) }) else { return false }
let flags = [response?.shootCompleteReturning, response?.ui?.shootCompleteReturning].compactMap { $0 }
if flags.contains(false) { return false }
if flags.contains(true) || response?.ui?.waylineStage == "shoot_done_returning" { return true }
// 旧回包仍保留明确的设备返航文案;新合同不再依赖只有忙闲的 work_status。
guard response?.ui?.waylineStage == nil else { return false }
return ["返航中", "正在返航"].contains(usable(response?.currentPlane?.workStatusLabel) ?? "")
}
/// 完成提示按当前任务的执行批次去重,旧快照仍由统一版本校验拒绝。
var recordingExecutionID: String {
"\(taskID):\(response?.executionBatch ?? 0)"
}
/// App 首次确认本批次到达后显示 30 秒本地倒计时;到零仍等待后端阶段,不触发控制或状态读取。
var countdownRemainingSeconds: Int? {
guard !identityInvalidated, readAccessError == nil, resolvedDisplayPhase().0 == .ready,
let deadline = arrivalCountdownDeadlines[recordingExecutionID] else { return nil }
let remaining = countdownNow().duration(to: deadline)
guard remaining > .zero else { return 0 }
let parts = remaining.components
return Int(min(30, parts.seconds + (parts.attoseconds > 0 ? 1 : 0)))
}
/// 根据可信阶段使用产品标题,其余保留服务端标题,不从 GET 成功推导到达或拍摄完成。
var statusTitle: String {
if response == nil {
if errorMessage != nil { return "任务状态读取失败" }
if hasInitialTravelReceipt { return "无人机正在赶来" }
if isLoading { return "正在获取任务状态" }
}
if resolvedDisplayPhase().0 == .navigating { return "无人机正在赶来" }
if resolvedDisplayPhase().0 == .shooting { return "无人机正在拍摄中" }
if resolvedDisplayPhase().0 == .failed { return "任务执行失败" }
if resolvedDisplayPhase().0 == .postShootUploadFailed { return mediaFailureTitle }
if isTaskAwaitingConfirmation { return "任务待确认" }
if resolvedDisplayPhase().0 == .postShootUploading {
return usable(response?.ui?.title) ?? "拍摄完毕上传中"
return "拍摄已完成"
}
return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel)
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
}
/// 保留服务端阶段说明;操作结果未知时优先提示核对,不伪装为设备已执行。
/// 拍摄阶段使用产品提示,其余保留服务端说明;操作结果未知时优先提示核对。
var statusMessage: String {
if response == nil {
if let errorMessage { return errorMessage }
if hasInitialTravelReceipt { return "召唤已受理,正在等待设备到达确认,请留在拍摄点。" }
if isLoading { return "正在读取当前拍摄任务" }
}
if let resummonErrorMessage { return resummonErrorMessage }
if awaitingResummonSnapshot { return "重新召唤请求已受理,请刷新核对任务状态" }
if let commandErrorMessage { return commandErrorMessage }
if resolvedDisplayPhase().0 == .failed { return failureMessage }
if resolvedDisplayPhase().0 == .postShootUploadFailed { return mediaFailureMessage }
if isTaskAwaitingConfirmation { return usable(response?.ui?.message) ?? "任务结果待确认,请刷新核对状态。" }
if startOutcomeUnknown, let startErrorMessage { return startErrorMessage }
if resolvedDisplayPhase().0 == .ready {
if let startErrorMessage { return startErrorMessage }
if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" }
}
if resolvedDisplayPhase().0 == .postShootUploading {
return usable(response?.ui?.message) ?? "录制已结束,素材正在处理,请稍候。"
let waylines = [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus]
let note: String
if isShootCompleteReturning { note = "无人机正在返航,请留意现场。" }
else if waylines.contains(30) { note = "素材上传中,可在素材库查看进度。" }
else if waylines.contains(40) { note = "素材渲染中,可在素材库查看进度。" }
else { note = "素材处理中,可在素材库查看进度。" }
return "本次拍摄已结束,可前往查看素材。\n" + note
}
if resolvedDisplayPhase().0 == .shooting { return "请关注现场及实时画面。\n请勿关闭本页或息屏。" }
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
}
/// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。
var presentation: DroneDockTaskPresentation {
if response == nil, hasInitialTravelReceipt, errorMessage == nil, !identityInvalidated {
return DroneDockTaskPresentation(phase: .navigating, title: statusTitle, message: statusMessage,
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
}
if response == nil, isLoading {
return DroneDockTaskPresentation(phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
@@ -548,6 +624,10 @@ final class DroneDockShootingTaskViewModel {
let actionTitle: String?
let enabled: Bool
switch phase {
case .shooting:
action = .none
actionTitle = "拍摄中"
enabled = false
case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown || resummonOutcomeUnknown:
action = .refresh
actionTitle = "刷新状态"
@@ -561,7 +641,7 @@ final class DroneDockShootingTaskViewModel {
action = .resume
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄"
enabled = false
case .completed:
case .completed, .postShootUploading, .postShootUploadFailed:
action = .materials
actionTitle = "查看素材"
enabled = true
@@ -581,7 +661,8 @@ final class DroneDockShootingTaskViewModel {
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil)
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil,
countdownSeconds: countdownRemainingSeconds)
}
/// 后端六项展示读数,不解析文案反推设备状态或数值单位。
@@ -683,27 +764,34 @@ final class DroneDockShootingTaskViewModel {
&& scenicIDs.allSatisfy { $0 == context.scenicID }
}
/// 只认识显式阶段和已确认任务状态;91 为真实航线执行失败,不把订单状态 20 当作正在拍摄。
/// 按任务终态、明确 UI 阶段与航线失败判断,不把机巢忙闲或订单执行中当作拍摄进度。
private func resolvedDisplayPhase() -> (DroneDockTaskDisplayPhase, Bool) {
guard let response else { return (.unknown, false) }
let tasks = [response.task, response.orderFlightTask].compactMap { $0 }
let statuses = Set(tasks.compactMap(\.status))
if tasks.contains(where: { $0.waylineStatus == 91 }) || statuses.contains(40) { return (.failed, false) }
if statuses.contains(50) { return (.blocked, false) }
let waylines = Set(tasks.compactMap(\.waylineStatus))
let rawPhase = usable(response.ui?.phase)
if statuses.contains(50) || waylines.contains(90) || statuses.contains(60) { return (.blocked, false) }
if tasks.contains(where: { $0.resultCode == "return_home" }) { return (.failed, false) }
if !waylines.isDisjoint(with: [29, 39, 49, 91]) || statuses.contains(40) {
let isMediaFailure = rawPhase == "post_shoot_upload_failed"
|| (hasMediaProcessingFailure && rawPhase != "failed_restartable")
return (isMediaFailure ? .postShootUploadFailed : .failed, false)
}
if statuses.count > 1 { return (.unknown, true) }
let known: [String: DroneDockTaskDisplayPhase] = [
"going_to_spot": .navigating, "failed_restartable": .failed, "waiting_summon": .blocked,
"navigating": .navigating, "arrived_pending_start": .ready, "shooting": .shooting,
"post_shoot_uploading": .postShootUploading,
"post_shoot_upload_failed": .postShootUploadFailed,
"paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
]
let rawPhase = usable(response.ui?.phase)
let phase = rawPhase.flatMap { known[$0] }
if rawPhase != nil && phase == nil { return (.unknown, false) }
if phase == .failed { return (.failed, false) }
if statuses.contains(30) {
if phase == .returning { return (.returning, false) }
if let phase, [.navigating, .ready, .shooting, .postShootUploading, .paused].contains(phase) { return (.unknown, true) }
if let phase, [.navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused].contains(phase) { return (.unknown, true) }
return (.completed, false)
}
if phase == .completed {
@@ -725,21 +813,28 @@ final class DroneDockShootingTaskViewModel {
if conflict { return "状态待确认" }
let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 }
if phase == .failed { return "任务执行失败" }
if phase == .postShootUploadFailed { return mediaFailureTitle }
if phase == .blocked, isTaskAwaitingConfirmation { return "任务待确认" }
if phase == .blocked, let cancelled = tasks.first(where: { $0.status == 50 }) {
return usable(cancelled.statusLabel) ?? "任务已取消"
}
if phase == .blocked, tasks.contains(where: { $0.waylineStatus == 90 }) { return "任务已取消" }
if phase == .blocked, response?.ui?.phase == "arrived_pending_start" { return "暂不可开始拍摄" }
if phase == .postShootUploading { return "拍摄已完成" }
if phase == .completed {
return usable(response?.ui?.phase == "completed" ? response?.ui?.title : nil)
?? tasks.first(where: { $0.status == 30 }).flatMap { usable($0.statusLabel) } ?? "拍摄已完成"
}
if phase == .unknown { return "状态待确认" }
if phase == .navigating { return "无人机正在赶来" }
if phase == .shooting { return "无人机正在拍摄中" }
if let title = usable(response?.ui?.title) { return title }
switch phase {
case .navigating: return "无人机正在前往拍摄点"
case .navigating: return "无人机正在赶来"
case .ready: return "无人机已到达"
case .shooting: return "正在拍摄"
case .postShootUploading: return "拍摄完毕上传中"
case .postShootUploading: return "拍摄已完成"
case .postShootUploadFailed: return mediaFailureTitle
case .paused: return "拍摄已暂停"
case .returning: return "无人机正在返航"
case .failed: return "任务执行失败"
@@ -756,20 +851,54 @@ final class DroneDockShootingTaskViewModel {
?? usable(response?.executeGate?.message) ?? usable(response?.ui?.message) ?? "暂未返回具体失败原因"
}
/// 39/49 表示录制后的素材处理失败,不能据此生成起飞或重召唤许可。
private var hasMediaProcessingFailure: Bool {
[response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus]
.compactMap { $0 }.contains { [39, 49].contains($0) }
}
private var isTaskAwaitingConfirmation: Bool {
response?.orderFlightTask?.status == 60 || response?.task?.status == 60
}
private var mediaFailureTitle: String {
if response?.ui?.phase == "post_shoot_upload_failed", let title = usable(response?.ui?.title) { return title }
return [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus].contains(49)
? "素材渲染失败" : "素材上传失败"
}
private var mediaFailureMessage: String {
usable(response?.orderFlightTask?.resultMessage) ?? usable(response?.task?.resultMessage)
?? usable(response?.ui?.message) ?? usable(response?.task?.waylineStatusLabel)
?? usable(response?.orderFlightTask?.waylineStatusLabel) ?? "素材处理失败,请前往素材库查看。"
}
/// 工作态优先;工作态缺失或未识别时才用飞机表在线标记保守兜底。
private var isResummonDeviceOffline: Bool {
switch response?.currentPlane?.workStatus {
case 0: return true
case 1, 2: return false
default:
if let online = response?.currentPlane?.onlineStatus { return online != 1 }
return usable(response?.currentPlane?.workStatusLabel) == "离线"
}
}
/// 明确离线或返航时保持禁用,不从普通空闲文案推导后端重试许可。
private var isResummonDeviceUnavailable: Bool {
let plane = response?.currentPlane
return response?.planeStatus?.connected == false || plane?.onlineStatus == 2 || plane?.workStatus == 0
|| ["离线", "返航中", "正在返航"].contains(usable(plane?.workStatusLabel) ?? "")
return response?.planeStatus?.connected == false || isResummonDeviceOffline || plane?.workStatus == 2
|| ["返航中", "正在返航"].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) == "离线" {
if isResummonDeviceOffline {
return "无人机离线,暂不可召唤"
}
if plane?.workStatus == 2 { return "无人机忙碌,暂不可召唤" }
if let status = usable(plane?.workStatusLabel), ["返航中", "正在返航"].contains(status) {
return "无人机返航中,暂不可召唤"
}
@@ -0,0 +1,86 @@
import SnapKit
import UIKit
/// 与任务原型一致的录制完成提示;只引导查看素材,不宣告上传成功或扣减次数。
@MainActor
final class DroneDockRecordingCompletionView: UIView {
/// 关闭提示并继续留在任务页。
var onLater: (() -> Void)?
/// 前往当前订单素材库。
var onViewMaterials: (() -> Void)?
/// 创建居中结果卡片,覆盖任务页但不触发生命周期或暂停只读状态更新。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
private func setupUI() {
backgroundColor = .black.withAlphaComponent(0.5)
accessibilityViewIsModal = true
accessibilityIdentifier = "drone.task.recordingCompletion"
let card = UIView()
card.backgroundColor = .white
card.layer.cornerRadius = 14
addSubview(card)
let symbol = UIImageView(image: UIImage(systemName: "checkmark.circle.fill"))
symbol.tintColor = DroneDockStyle.success
symbol.contentMode = .scaleAspectFit
let title = DroneDockStyle.label(size: 20, weight: .semibold)
title.text = "拍摄已完成"
title.textAlignment = .center
let message = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
message.text = "本次拍摄已完成,\n可前往订单素材库查看上传进度和素材。"
message.numberOfLines = 0
message.textAlignment = .center
let later = button("稍后再去", primary: false, action: #selector(laterTapped))
let materials = button("去查看", primary: true, action: #selector(materialsTapped))
later.accessibilityIdentifier = "drone.task.recordingCompletion.later"
materials.accessibilityIdentifier = "drone.task.recordingCompletion.materials"
let actions = UIStackView(arrangedSubviews: [later, materials])
actions.spacing = 10
actions.distribution = .fillEqually
[symbol, title, message, actions].forEach { card.addSubview($0) }
card.snp.makeConstraints { make in
make.center.equalToSuperview()
make.width.equalTo(320).priority(.high)
make.leading.greaterThanOrEqualToSuperview().offset(24)
make.trailing.lessThanOrEqualToSuperview().offset(-24)
}
symbol.snp.makeConstraints { make in
make.top.equalToSuperview().offset(24)
make.centerX.equalToSuperview()
make.size.equalTo(50)
}
title.snp.makeConstraints { make in
make.top.equalTo(symbol.snp.bottom).offset(16)
make.leading.trailing.equalToSuperview().inset(20)
}
message.snp.makeConstraints { make in
make.top.equalTo(title.snp.bottom).offset(12)
make.leading.trailing.equalToSuperview().inset(20)
}
actions.snp.makeConstraints { make in
make.top.equalTo(message.snp.bottom).offset(24)
make.leading.trailing.bottom.equalToSuperview().inset(16)
make.height.equalTo(46)
}
}
private func button(_ title: String, primary: Bool, action: Selector) -> UIButton {
let button = UIButton(type: .system)
button.setTitle(title, for: .normal)
button.setTitleColor(primary ? .white : DroneDockStyle.text, for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
button.backgroundColor = primary ? DroneDockStyle.primary : UIColor(hex: 0xEEF0F6)
button.layer.cornerRadius = 7
button.addTarget(self, action: action, for: .touchUpInside)
return button
}
@objc private func laterTapped() { onLater?() }
@objc private func materialsTapped() { onViewMaterials?() }
}
@@ -36,7 +36,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
self.viewModel = viewModel
self.simulationRecordsProvider = simulationRecordsProvider
self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context)
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context,
coverURL: viewModel.selectedSpot?.displayCoverURL,
initialSummonReceipt: viewModel.shootResponse)
}
self.planeStatusPollDelay = planeStatusPollDelay
super.init(nibName: nil, bundle: nil)
@@ -222,7 +224,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
present(alert, animated: true)
}
/// 成功后自动导航一次;失败的已结束任务只在用户明确点击时查看原任务。
/// 进入任务时替换有前驱的准备页,返回直达工作台;独立调试根页保留原返回入口。
@discardableResult
private func openShootingTask(automatically: Bool) -> Bool {
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
@@ -232,7 +234,12 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
DroneDockDiagnostics.event("navigation.open_task", taskID: taskID)
automaticallyOpenedTaskID = taskID
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
navigationController.pushViewController(controller, animated: true)
let stack = navigationController.viewControllers
if stack.count > 1 {
navigationController.setViewControllers(Array(stack.dropLast()) + [controller], animated: true)
} else {
navigationController.pushViewController(controller, animated: true)
}
return true
}
@@ -6,6 +6,13 @@ enum DroneDockShootingTaskEntry {
/// 使用已有任务读取状态;Release 注入已授权的真实控制,Debug 保持只读。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
makeController(taskID: taskID, order: order, context: context, coverURL: nil)
}
/// 准备页携带封面及召唤回执;其它入口不推断前往阶段,等 shooting 返回。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext, coverURL: URL?,
initialSummonReceipt: DroneDockShootResponse? = nil) -> UIViewController {
let client = NetworkServices.shared.apiClient
let realtime = DroneDockShootingRealtimeSession(taskID: taskID,
ticketService: DroneDockSocketTokenAPI(client: client),
@@ -22,7 +29,8 @@ enum DroneDockShootingTaskEntry {
startService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockStartShootAPI(client: client),
commandService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockCommandAPI(client: client),
resummonService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockShootAPI(client: client),
initialSummonReceipt: initialSummonReceipt,
currentContext: { DroneDockHomeViewController.currentContext() }
), liveViewModel: live, realtimeSession: realtime)
), liveViewModel: live, coverURL: coverURL, realtimeSession: realtime)
}
}
@@ -43,17 +43,27 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var isSendingSafetyAction = false
private var isResummoningAction = false
private var wasRealtimeLive = false
private let coverURL: URL?
private var finishedExecutions: Set<String> = []
private var displayedCompletionIDs: Set<String> = []
private var completionNotice: DroneDockRecordingCompletionView?
private let countdownDelay: @Sendable () async throws -> Void
private var countdownTask: Task<Void, Never>?
private var countdownGeneration = 0
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
livePlayer: (any DroneDockLivePlaying)? = nil,
coverURL: URL? = nil,
realtimeSession: DroneDockShootingRealtimeSession? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil,
shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) },
liveParameterDelay: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) }) {
liveParameterDelay: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) },
countdownDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(1)) }) {
self.viewModel = viewModel
self.coverURL = coverURL
self.feedPlaceholder = livePlayer.map { DroneDockTaskLiveView(rtcPlayer: $0) } ?? DroneDockTaskLiveView()
self.realtimeSession = realtimeSession
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
@@ -62,6 +72,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
self.simulationRecordsProvider = simulationRecordsProvider
self.shootingPollDelay = shootingPollDelay
self.liveParameterDelay = liveParameterDelay
self.countdownDelay = countdownDelay
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
@@ -92,6 +103,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
resummonTask?.cancel()
liveTask?.cancel()
liveParameterTask?.cancel()
countdownTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
@@ -228,6 +240,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
dismissCompletionNotice()
logEvent("page.disappeared")
cancelRefresh()
stopLive()
@@ -235,26 +248,103 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func applySnapshot() {
guard isViewLoaded else { return }
if viewModel.isRecordingFinished { finishedExecutions.insert(viewModel.recordingExecutionID) }
let recordingFinished = finishedExecutions.contains(viewModel.recordingExecutionID)
if !viewModel.shouldPresentRecordingCompletion { dismissCompletionNotice() }
if recordingFinished, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil {
stopLive()
}
feedPlaceholder.showRecordingCover(recordingFinished, url: coverURL)
let loading = (viewModel.response == nil && (isRequesting || viewModel.isLoading))
|| isStartingAction || viewModel.isStartingShooting
|| isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning
feedPlaceholder.apply(liveViewModel)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive)
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !recordingFinished)
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle + (viewModel.response?.metricsStale == true ? " · 读数已过期" : "")
let telemetry = viewModel.telemetry
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric", preservingStaleValues: true)
let value = loading && viewModel.response == nil ? DroneDockTaskPresentation(
let presentation = viewModel.presentation
let value = loading && viewModel.response == nil && presentation.phase != .navigating ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : presentation
statusView.apply(value, isRefreshing: loading)
updateArrivalCountdown()
safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil,
isInteractive: isPageVisible && isApplicationActive && !loading)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading }
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
presentCompletionNoticeIfNeeded()
refreshLiveIfVisible(automatically: true)
}
/// 倒计时只更新独立秒数标签;网络读取、飞控及后端阶段仍由原有流程驱动。
private func updateArrivalCountdown() {
let seconds = viewModel.countdownRemainingSeconds
statusView.updateCountdown(seconds: seconds)
guard isPageVisible, isApplicationActive, let seconds, seconds > 0 else {
stopArrivalCountdown()
return
}
guard countdownTask == nil else { return }
countdownGeneration += 1
let generation = countdownGeneration
let delay = countdownDelay
countdownTask = Task { @MainActor [weak self] in
while !Task.isCancelled {
do { try await delay() } catch { return }
guard let self, !Task.isCancelled, self.countdownGeneration == generation,
self.isPageVisible, self.isApplicationActive else { return }
let remaining = self.viewModel.countdownRemainingSeconds
self.statusView.updateCountdown(seconds: remaining)
if remaining == nil || remaining == 0 {
self.countdownTask = nil
return
}
}
}
}
private func stopArrivalCountdown() {
countdownGeneration += 1
countdownTask?.cancel()
countdownTask = nil
}
private func presentCompletionNoticeIfNeeded() {
let id = viewModel.recordingExecutionID
guard viewModel.shouldPresentRecordingCompletion, isPageVisible, isApplicationActive, view.window != nil,
presentedViewController == nil, completionNotice == nil, !displayedCompletionIDs.contains(id) else { return }
displayedCompletionIDs.insert(id)
let notice = DroneDockRecordingCompletionView()
completionNotice = notice
notice.onLater = { [weak self] in self?.dismissCompletionNotice() }
notice.onViewMaterials = { [weak self] in
guard let self, self.isPageVisible, self.isApplicationActive,
self.viewModel.recordingExecutionID == id else { return }
self.dismissCompletionNotice()
self.openMaterials()
}
let container = navigationController?.view ?? view!
container.addSubview(notice)
notice.snp.makeConstraints { $0.edges.equalToSuperview() }
UIAccessibility.post(notification: .screenChanged, argument: notice)
}
private func dismissCompletionNotice() {
completionNotice?.removeFromSuperview()
completionNotice = nil
}
private func openMaterials() {
guard isPageVisible, isApplicationActive, presentedViewController == nil,
viewModel.presentation.action == .materials, viewModel.presentation.isActionEnabled,
let navigationController, navigationController.topViewController === self else { return }
dismissCompletionNotice()
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
}
private func primaryActionTriggered() {
@@ -274,8 +364,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
case .retry:
resummonIfAllowed()
case .materials:
guard let navigationController, navigationController.topViewController === self else { return }
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
openMaterials()
case .resume, .none:
break
}
@@ -366,6 +455,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
private func cancelRefresh() {
stopArrivalCountdown()
wasRealtimeLive = false
realtimeSession?.stop()
cancelScheduledPoll()
@@ -473,6 +563,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 可见且活跃时自动开启一次;失败可手动重试,不随 shooting/Socket 刷新重复请求。
private func refreshLiveIfVisible(automatically: Bool = false, keepingPlayback: Bool = false) {
guard viewModel.response != nil, viewModel.readAccessError == nil,
!finishedExecutions.contains(viewModel.recordingExecutionID), !viewModel.isRecordingFinished else { return }
guard !automatically || liveViewModel.loadsAutomatically else { return }
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
liveParameterTask?.cancel()
@@ -0,0 +1,133 @@
import SnapKit
import UIKit
/// 拍摄完成区域:左侧完成图标、右侧状态说明以及整行素材入口。
@MainActor
final class DroneDockTaskCompletedView: UIView {
/// 用户点击已允许的素材入口时通知任务页面。
var onViewMaterials: (() -> Void)?
/// 与任务固定区域共享紧凑布局指标,操作区域始终至少 44 点高。
private(set) var usesCompactLayout = false
private let content = UIView()
private let iconBackground = UIView()
private let icon = UIImageView(image: UIImage(systemName: "checkmark.circle.fill"))
private let titleLabel = DroneDockStyle.label(size: 20, weight: .semibold)
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
private let materialsButton = UIButton(type: .system)
private var messageHeight: Constraint?
private var titleHeight: Constraint?
private var buttonHeight: Constraint?
/// 创建不包含设备摘要或次级详情按钮的完成面板。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 仅展示已确认的完成文案,素材入口继续服从任务门禁与页面刷新状态。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool) {
titleLabel.text = presentation.title
messageLabel.text = presentation.message
var configuration = materialsButton.configuration
configuration?.title = presentation.actionTitle
materialsButton.isEnabled = presentation.action == .materials && presentation.isActionEnabled && !isRefreshing
configuration?.baseBackgroundColor = DroneDockStyle.primary.withAlphaComponent(materialsButton.isEnabled ? 1 : 0.35)
materialsButton.configuration = configuration
setNeedsLayout()
}
/// 仅当前可见面板提供通用任务访问标识,防止状态切换后匹配到隐藏控件。
func setIdentifiersActive(_ active: Bool) {
titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil
messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil
materialsButton.accessibilityIdentifier = active ? "drone.task.remote.primary" : nil
}
/// 固定区域变小时收紧说明行数与间距,不改变整页布局或缩小点击区域。
override func layoutSubviews() {
usesCompactLayout = bounds.height < 190
let extreme = bounds.height < 120
titleLabel.font = .systemFont(ofSize: extreme ? 17 : 20, weight: .semibold)
messageLabel.font = .systemFont(ofSize: usesCompactLayout ? 13 : 14)
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
let width = max(1, bounds.width - 84)
let measured = messageLabel.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height
let title = ceil(titleLabel.font.lineHeight)
let button: CGFloat = usesCompactLayout ? 44 : 50
let availableMessageHeight = max(0, bounds.height - 24 - title - 6 - 16 - button)
let body = min(ceil(measured), availableMessageHeight)
messageLabel.isHidden = body < messageLabel.font.lineHeight
messageHeight?.update(offset: messageLabel.isHidden ? 0 : body)
titleHeight?.update(offset: title)
buttonHeight?.update(offset: button)
super.layoutSubviews()
}
private func setupUI() {
accessibilityIdentifier = "drone.task.remote.completed"
addSubview(content)
[iconBackground, titleLabel, messageLabel, materialsButton].forEach(content.addSubview)
iconBackground.addSubview(icon)
iconBackground.backgroundColor = DroneDockStyle.success.withAlphaComponent(0.12)
iconBackground.layer.cornerRadius = 20
icon.contentMode = .scaleAspectFit
icon.tintColor = DroneDockStyle.success
titleLabel.accessibilityTraits = .header
titleLabel.numberOfLines = 1
titleLabel.lineBreakMode = .byTruncatingTail
messageLabel.lineBreakMode = .byTruncatingTail
var configuration = UIButton.Configuration.filled()
configuration.baseForegroundColor = .white
configuration.background.cornerRadius = 8
configuration.cornerStyle = .fixed
configuration.image = UIImage(systemName: "photo", withConfiguration: UIImage.SymbolConfiguration(pointSize: 15))
configuration.imagePadding = 8
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = .systemFont(ofSize: 15, weight: .semibold)
return result
}
materialsButton.configuration = configuration
materialsButton.addTarget(self, action: #selector(viewMaterials), for: .touchUpInside)
}
private func setupConstraints() {
content.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.centerY.equalToSuperview()
}
iconBackground.snp.makeConstraints { make in
make.top.leading.equalToSuperview()
make.size.equalTo(40)
}
icon.snp.makeConstraints { make in
make.center.equalToSuperview()
make.size.equalTo(22)
}
titleLabel.snp.makeConstraints { make in
make.top.trailing.equalToSuperview()
make.leading.equalTo(iconBackground.snp.trailing).offset(12)
titleHeight = make.height.equalTo(24).constraint
}
messageLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(6)
make.leading.trailing.equalTo(titleLabel)
messageHeight = make.height.equalTo(34).constraint
}
materialsButton.snp.makeConstraints { make in
make.top.equalTo(messageLabel.snp.bottom).offset(16)
make.leading.trailing.bottom.equalToSuperview()
buttonHeight = make.height.equalTo(50).constraint
}
}
@objc private func viewMaterials() {
guard !isHidden, materialsButton.isEnabled else { return }
onViewMaterials?()
}
}
@@ -1,4 +1,5 @@
import AVFoundation
import Kingfisher
import SnapKit
import UIKit
@@ -14,6 +15,8 @@ final class DroneDockTaskLiveView: UIView {
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 sourceBadge = UIStackView()
private let liveDot = UIView()
private let requestButton = UIButton(type: .system)
private let labels = UIStackView()
private var player: AVQueuePlayer?
@@ -22,6 +25,12 @@ final class DroneDockTaskLiveView: UIView {
private var activeURL: URL?
private var isPlaybackActive = false
private let rtcView = UIView()
private let coverView = UIImageView()
private let coverShade = UIView()
private let coverIcon = UIImageView(image: UIImage(systemName: "photo.on.rectangle.angled"))
private var labelsCenterY: Constraint?
private var isShowingCover = false
private var coverURL: URL?
private let rtcPlayer: any DroneDockLivePlaying
private var requestedRTC: [DroneDockVolcLiveConfiguration] = []
private var activeRTC: [DroneDockVolcLiveConfiguration] = []
@@ -64,6 +73,7 @@ final class DroneDockTaskLiveView: UIView {
/// 在明确时机应用模型;远程 URL 即使错误传入也不会创建播放器。
func apply(_ model: DroneDockLiveViewModel) {
guard !isShowingCover else { return }
titleLabel.text = model.title
messageLabel.text = model.message
requestButton.setTitle(model.actionTitle, for: .normal)
@@ -74,8 +84,9 @@ final class DroneDockTaskLiveView: UIView {
requestedSessionID = model.playbackSessionID
let hasLocalPreview = requestedURL != nil
let isPlaying = model.state == .playing
sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : (isPlaying ? model.message + " · 实时图传" : nil)
sourceLabel.isHidden = !hasLocalPreview && !isPlaying
sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : "实时图传"
sourceBadge.isHidden = !hasLocalPreview && !isPlaying
liveDot.isHidden = hasLocalPreview
titleLabel.isHidden = hasLocalPreview || isPlaying
messageLabel.isHidden = hasLocalPreview || isPlaying
accessibilityLabel = hasLocalPreview || isPlaying ? sourceLabel.text : "\(model.title),\(model.message)"
@@ -84,10 +95,32 @@ final class DroneDockTaskLiveView: UIView {
/// 页面离开或进入后台立即释放播放器;重新获取图传参数由控制器协调。
func setPlaybackActive(_ active: Bool) {
isPlaybackActive = active
isPlaybackActive = active && !isShowingCover
updatePlayback()
}
/// 录制结束后仅展示静态封面;隐藏实时标记和重试按钮,旧模型不能恢复播放。
func showRecordingCover(_ show: Bool, url: URL?) {
guard isShowingCover != show || coverURL != url else { return }
isShowingCover = show
coverURL = url
coverView.isHidden = !show
coverShade.isHidden = !show
coverIcon.isHidden = !show || url != nil
labelsCenterY?.update(offset: show ? 38 : -15)
guard show else { coverView.kf.cancelDownloadTask(); return }
setPlaybackActive(false)
coverView.contentMode = .scaleAspectFill
coverView.kf.setImage(with: url)
titleLabel.text = "拍摄已完成"
titleLabel.isHidden = false
messageLabel.text = "拍摄封面 · 实时图传已结束"
messageLabel.isHidden = false
sourceBadge.isHidden = true
requestButton.isHidden = true
accessibilityLabel = "拍摄已完成,拍摄封面,实时图传已结束"
}
private func setupUI() {
backgroundColor = UIColor(hex: 0x171B22)
clipsToBounds = true
@@ -95,6 +128,19 @@ final class DroneDockTaskLiveView: UIView {
layer.addSublayer(playerLayer)
rtcView.backgroundColor = .clear
addSubview(rtcView)
coverView.backgroundColor = UIColor(hex: 0x182A36)
coverView.tintColor = UIColor.white.withAlphaComponent(0.22)
coverView.clipsToBounds = true
coverView.isHidden = true
coverView.accessibilityIdentifier = "drone.task.remote.live.cover"
addSubview(coverView)
coverShade.backgroundColor = .black.withAlphaComponent(0.3)
coverShade.isHidden = true
addSubview(coverShade)
coverIcon.contentMode = .scaleAspectFit
coverIcon.tintColor = .white.withAlphaComponent(0.7)
coverIcon.isHidden = true
addSubview(coverIcon)
playerLayer.videoGravity = .resizeAspect
titleLabel.textAlignment = .center
messageLabel.textAlignment = .center
@@ -102,11 +148,16 @@ final class DroneDockTaskLiveView: UIView {
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
sourceBadge.axis = .horizontal
sourceBadge.alignment = .center
sourceBadge.spacing = 6
sourceBadge.isHidden = true
sourceBadge.accessibilityIdentifier = "drone.task.remote.live.badge"
liveDot.backgroundColor = DroneDockStyle.success
liveDot.layer.cornerRadius = 3
liveDot.accessibilityIdentifier = "drone.task.remote.live.dot"
sourceBadge.addArrangedSubview(liveDot)
sourceBadge.addArrangedSubview(sourceLabel)
requestButton.tintColor = .white
requestButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
requestButton.backgroundColor = UIColor.black.withAlphaComponent(0.45)
@@ -119,14 +170,21 @@ final class DroneDockTaskLiveView: UIView {
labels.addArrangedSubview(titleLabel)
labels.addArrangedSubview(messageLabel)
addSubview(labels)
addSubview(sourceLabel)
addSubview(sourceBadge)
addSubview(requestButton)
}
private func setupConstraints() {
rtcView.snp.makeConstraints { $0.edges.equalToSuperview() }
coverView.snp.makeConstraints { $0.edges.equalToSuperview() }
coverShade.snp.makeConstraints { $0.edges.equalToSuperview() }
coverIcon.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().offset(-28)
make.size.equalTo(42)
}
labels.snp.makeConstraints { make in
make.centerY.equalToSuperview().offset(-15)
labelsCenterY = make.centerY.equalToSuperview().offset(-15).constraint
make.leading.trailing.equalToSuperview().inset(20)
}
requestButton.snp.makeConstraints { make in
@@ -135,10 +193,10 @@ final class DroneDockTaskLiveView: UIView {
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)
liveDot.snp.makeConstraints { $0.size.equalTo(6).priority(999) }
sourceBadge.snp.makeConstraints { make in
make.top.leading.equalToSuperview().inset(12)
make.trailing.lessThanOrEqualToSuperview().inset(12)
}
}
@@ -0,0 +1,191 @@
import SnapKit
import UIKit
/// 拍摄中状态区域:对齐体验网页的蓝色视频提示和禁用状态按钮,不执行任何操作。
@MainActor
final class DroneDockTaskShootingView: UIView {
/// 当前内容采用的排版参考比例,不通过 transform 缩小整个视图。
private(set) var effectiveScale: CGFloat = 1
/// 固定区域较小时收紧图标、字号和间距。
private(set) var usesCompactLayout = false
private let content = UIView()
private let header = UIView()
private let iconBackground = UIView()
private let icon = UIImageView(image: UIImage(systemName: "video.fill"))
private let titleLabel = DroneDockStyle.label(size: 23, weight: .semibold, color: UIColor(hex: 0x101523))
private let messageLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0x6A79A0))
private let indicatorButton = UIButton(type: .system)
private var presentation: DroneDockTaskPresentation?
private var headerHeight: Constraint?
private var iconSize: Constraint?
private var textLeading: Constraint?
private var titleHeight: Constraint?
private var messageTop: Constraint?
private var messageHeight: Constraint?
private var indicatorTop: Constraint?
private var indicatorHeight: Constraint?
/// 建立纯展示的拍摄中面板,外部任务页决定固定区域大小。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 展示已确认的拍摄中文案,按钮始终仅作状态指示。
func apply(_ presentation: DroneDockTaskPresentation) {
self.presentation = presentation
titleLabel.text = presentation.title
messageLabel.text = presentation.message
indicatorButton.isEnabled = false
setNeedsLayout()
}
/// 仅可见状态面板提供通用访问标识,避免匹配到隐藏的标题或说明。
func setIdentifiersActive(_ active: Bool) {
titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil
messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil
}
/// 按可用高度调整内部排版,状态按钮始终保留至少 44 点高度。
override func layoutSubviews() {
updateContentLayout()
super.layoutSubviews()
}
private func setupUI() {
accessibilityIdentifier = "drone.task.remote.shooting"
backgroundColor = .white
addSubview(content)
content.addSubview(header)
content.addSubview(indicatorButton)
[iconBackground, titleLabel, messageLabel].forEach(header.addSubview)
iconBackground.addSubview(icon)
iconBackground.backgroundColor = UIColor(hex: 0xE2EDFF)
iconBackground.layer.cornerRadius = 20.5
icon.contentMode = .scaleAspectFit
icon.tintColor = UIColor(hex: 0x0671FF)
titleLabel.accessibilityTraits = .header
titleLabel.numberOfLines = 1
titleLabel.lineBreakMode = .byTruncatingTail
messageLabel.numberOfLines = 2
messageLabel.lineBreakMode = .byTruncatingTail
var configuration = UIButton.Configuration.filled()
configuration.title = "拍摄中"
configuration.image = UIImage(systemName: "camera")
configuration.imagePadding = 12
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 24, weight: .regular)
configuration.background.backgroundColor = UIColor(hex: 0xD7E7FF)
configuration.background.cornerRadius = 8
configuration.cornerStyle = .fixed
configuration.baseForegroundColor = UIColor(hex: 0x4D91FF)
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)
indicatorButton.configuration = configuration
indicatorButton.isEnabled = false
indicatorButton.accessibilityIdentifier = "drone.task.remote.shootingIndicator"
indicatorButton.configurationUpdateHandler = { button in
button.configuration?.background.backgroundColor = UIColor(hex: 0xD7E7FF)
button.configuration?.baseForegroundColor = UIColor(hex: 0x4D91FF)
button.configuration?.imageColorTransformer = UIConfigurationColorTransformer { _ in UIColor(hex: 0x4D91FF) }
}
}
private func setupConstraints() {
content.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(18)
make.centerY.equalToSuperview()
}
header.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
headerHeight = make.height.equalTo(81).constraint
}
iconBackground.snp.makeConstraints { make in
make.top.leading.equalToSuperview()
iconSize = make.size.equalTo(41).constraint
}
icon.snp.makeConstraints { make in
make.center.equalToSuperview()
make.size.equalTo(iconBackground.snp.width).multipliedBy(24.0 / 41.0)
}
titleLabel.snp.makeConstraints { make in
make.top.trailing.equalToSuperview()
textLeading = make.leading.equalTo(iconBackground.snp.trailing).offset(12).constraint
titleHeight = make.height.equalTo(30).constraint
}
messageLabel.snp.makeConstraints { make in
messageTop = make.top.equalTo(titleLabel.snp.bottom).offset(6).constraint
make.leading.trailing.equalTo(titleLabel)
messageHeight = make.height.equalTo(45).constraint
}
indicatorButton.snp.makeConstraints { make in
indicatorTop = make.top.equalTo(header.snp.bottom).offset(16).constraint
make.leading.trailing.bottom.equalToSuperview()
indicatorHeight = make.height.equalTo(50).constraint
}
}
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
usesCompactLayout = bounds.height < 190
let extreme = bounds.height < 120
let compact = usesCompactLayout
let diameter: CGFloat = extreme ? 24 : compact ? 32 : 41
let iconGap: CGFloat = extreme ? 8 : compact ? 10 : 12
let titleSize: CGFloat = extreme ? 17 : compact ? 20 : 23
let messageSize: CGFloat = compact ? 13 : 14
let title = max(ceil(UIFont.systemFont(ofSize: titleSize, weight: .semibold).lineHeight), compact ? 0 : 30)
let textGap: CGFloat = extreme ? 3 : compact ? 4 : 6
let actionGap: CGFloat = extreme ? 8 : compact ? 12 : 16
let actionHeight: CGFloat = compact ? 44 : 50
let inset: CGFloat = extreme ? 4 : 6
let textWidth = max(1, bounds.width - 36 - diameter - iconGap)
let available = max(1, bounds.height - inset * 2)
let paragraph = NSMutableParagraphStyle()
paragraph.minimumLineHeight = messageSize * 1.6
paragraph.maximumLineHeight = messageSize * 1.6
paragraph.lineBreakMode = .byTruncatingTail
titleLabel.font = .systemFont(ofSize: titleSize, weight: .semibold)
let messageFont = UIFont.systemFont(ofSize: messageSize)
messageLabel.font = messageFont
let attributes: [NSAttributedString.Key: Any] = [
.font: messageFont,
.foregroundColor: UIColor(hex: 0x6A79A0),
.paragraphStyle: paragraph
]
messageLabel.attributedText = NSAttributedString(string: presentation.message, attributes: attributes)
let measured = (presentation.message as NSString).boundingRect(
with: CGSize(width: textWidth, height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil).height
var lines = extreme || presentation.message.isEmpty ? 0 : 2
var body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines)))
while max(diameter, title + (lines > 0 ? textGap + body : 0)) + actionGap + actionHeight > available, lines > 0 {
lines -= 1
body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines)))
}
messageLabel.numberOfLines = max(1, lines)
messageLabel.isHidden = lines == 0
let header = max(diameter, title + (lines > 0 ? textGap + body : 0))
let natural = title + textGap + ceil(messageSize * 3.2) + actionGap + actionHeight
effectiveScale = min(1, max(0.8, available / max(1, natural)))
headerHeight?.update(offset: header)
iconSize?.update(offset: diameter)
iconBackground.layer.cornerRadius = diameter / 2
textLeading?.update(offset: iconGap)
titleHeight?.update(offset: title)
messageTop?.update(offset: lines > 0 ? textGap : 0)
messageHeight?.update(offset: body)
indicatorTop?.update(offset: actionGap)
indicatorHeight?.update(offset: actionHeight)
indicatorButton.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = .systemFont(ofSize: compact ? 16 : 18, weight: .semibold)
result.foregroundColor = UIColor(hex: 0x4D91FF)
return result
}
}
}
@@ -6,7 +6,7 @@ import UIKit
final class DroneDockTaskStatusView: UIView {
/// 当前状态的主操作,由页面协调执行,不在组件中调用接口。
var onPrimaryAction: (() -> Void)?
/// 展开完整状态说明,由页面提供详情展示。
/// 点击失败原因区域时展开完整说明,由页面协调展示。
var onDetails: (() -> Void)?
/// 当前内容采用的字号和间距参考比例,始终介于 0.8 与 1。
private(set) var effectiveScale: CGFloat = 1
@@ -18,12 +18,15 @@ final class DroneDockTaskStatusView: UIView {
private let iconView = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold)
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
private let countdownLabel = DroneDockStyle.label(size: 13, weight: .medium, color: DroneDockStyle.primary)
private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let actionRow = UIView()
private let primaryButton = UIButton(type: .system)
private let detailsButton = UIButton(type: .system)
private let failureView = DroneDockTaskFailureView()
private let completedView = DroneDockTaskCompletedView()
private let shootingView = DroneDockTaskShootingView()
private var presentation: DroneDockTaskPresentation?
private var countdownSeconds: Int?
private var contentTop: Constraint?
private var contentLeading: Constraint?
private var contentTrailing: Constraint?
@@ -33,7 +36,7 @@ final class DroneDockTaskStatusView: UIView {
private var messageHeight: Constraint?
private var deviceHeight: Constraint?
/// 创建稳定的标题、说明、设备摘要与操作槽,所有状态复用同一组视图。
/// 创建固定状态槽,完成、失败与进行中使用各自的内容布局。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
@@ -51,9 +54,30 @@ final class DroneDockTaskStatusView: UIView {
/// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。
func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false) {
self.presentation = presentation
updateCountdown(seconds: presentation.countdownSeconds)
let isFailure = presentation.phase == .failed
contentStack.isHidden = isFailure
let isCompleted = [.postShootUploading, .completed].contains(presentation.phase)
let isShooting = presentation.phase == .shooting
contentStack.isHidden = isFailure || isCompleted || isShooting
failureView.isHidden = !isFailure
completedView.isHidden = !isCompleted
shootingView.isHidden = !isShooting
completedView.setIdentifiersActive(isCompleted)
shootingView.setIdentifiersActive(isShooting)
titleLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusTitle"
messageLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusMessage"
if isShooting {
primaryButton.accessibilityIdentifier = nil
shootingView.apply(presentation)
setNeedsLayout()
return
}
if isCompleted {
primaryButton.accessibilityIdentifier = nil
completedView.apply(presentation, isRefreshing: isRefreshing)
setNeedsLayout()
return
}
if isFailure {
failureView.apply(presentation, isRefreshing: isRefreshing)
setNeedsLayout()
@@ -76,8 +100,33 @@ final class DroneDockTaskStatusView: UIView {
setNeedsLayout()
}
/// 只刷新已到达阶段的剩余秒数,不变更主操作、服务端阶段或执行任何回调。
func updateCountdown(seconds: Int?) {
let value = presentation?.phase == .ready ? seconds.map { max(0, $0) } : nil
guard value != countdownSeconds else { return }
let visibilityChanged = (value == nil) != (countdownSeconds == nil)
countdownSeconds = value
countdownLabel.text = value.map { "自动开拍倒计时:\($0) 秒" }
countdownLabel.isHidden = value == nil
if visibilityChanged { setNeedsLayout() }
}
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
override func layoutSubviews() {
if presentation?.phase == .shooting {
super.layoutSubviews()
shootingView.layoutIfNeeded()
effectiveScale = shootingView.effectiveScale
usesCompactLayout = shootingView.usesCompactLayout
return
}
if let phase = presentation?.phase, [.postShootUploading, .completed].contains(phase) {
super.layoutSubviews()
completedView.layoutIfNeeded()
effectiveScale = 1
usesCompactLayout = completedView.usesCompactLayout
return
}
if presentation?.phase == .failed {
super.layoutSubviews()
failureView.layoutIfNeeded()
@@ -91,6 +140,11 @@ final class DroneDockTaskStatusView: UIView {
private func setupUI() {
backgroundColor = .white
addSubview(shootingView)
shootingView.isHidden = true
addSubview(completedView)
completedView.isHidden = true
completedView.onViewMaterials = { [weak self] in self?.onPrimaryAction?() }
addSubview(failureView)
failureView.isHidden = true
failureView.onDetails = { [weak self] in self?.onDetails?() }
@@ -101,6 +155,7 @@ final class DroneDockTaskStatusView: UIView {
addSubview(contentStack)
contentStack.addArrangedSubview(titleRow)
contentStack.addArrangedSubview(messageLabel)
contentStack.addArrangedSubview(countdownLabel)
contentStack.addArrangedSubview(deviceLabel)
contentStack.addArrangedSubview(actionRow)
titleRow.addSubview(iconView)
@@ -113,28 +168,25 @@ final class DroneDockTaskStatusView: UIView {
messageLabel.numberOfLines = 3
messageLabel.lineBreakMode = .byTruncatingTail
messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage"
countdownLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .medium)
countdownLabel.numberOfLines = 1
countdownLabel.isHidden = true
countdownLabel.accessibilityIdentifier = "drone.task.remote.countdown"
deviceLabel.numberOfLines = 1
deviceLabel.lineBreakMode = .byTruncatingTail
deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus"
actionRow.addSubview(primaryButton)
actionRow.addSubview(detailsButton)
primaryButton.layer.cornerRadius = 9
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled)
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
detailsButton.setTitle("详情", for: .normal)
detailsButton.setTitleColor(DroneDockStyle.primary, for: .normal)
detailsButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
detailsButton.backgroundColor = DroneDockStyle.background
detailsButton.layer.cornerRadius = 9
detailsButton.accessibilityIdentifier = "drone.task.remote.details"
detailsButton.accessibilityLabel = "查看完整任务状态"
detailsButton.addTarget(self, action: #selector(detailsTapped), for: .touchUpInside)
}
private func setupConstraints() {
shootingView.snp.makeConstraints { $0.edges.equalToSuperview() }
completedView.snp.makeConstraints { $0.edges.equalToSuperview() }
failureView.snp.makeConstraints { make in make.edges.equalToSuperview() }
contentStack.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(12).constraint
@@ -151,23 +203,20 @@ final class DroneDockTaskStatusView: UIView {
make.trailing.centerY.equalToSuperview()
}
messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint }
countdownLabel.snp.makeConstraints { make in make.height.equalTo(ceil(countdownLabel.font.lineHeight)).priority(999) }
deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint }
actionRow.snp.makeConstraints { make in make.height.equalTo(44) }
detailsButton.snp.makeConstraints { make in
make.top.trailing.bottom.equalToSuperview()
make.width.equalTo(64)
}
primaryButton.snp.makeConstraints { make in
make.top.leading.bottom.equalToSuperview()
make.trailing.equalTo(detailsButton.snp.leading).offset(-8)
make.edges.equalToSuperview()
}
}
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let isExtreme = bounds.height < 120
let hasCountdown = countdownSeconds != nil
let horizontalInset: CGFloat = isExtreme ? 12 : 16
let verticalInset: CGFloat = isExtreme ? 6 : 12
let verticalInset: CGFloat = isExtreme ? (hasCountdown ? 4 : 6) : 12
let width = max(1, bounds.width - horizontalInset * 2)
let availableHeight = max(1, bounds.height - verticalInset * 2)
let message = DroneDockHomeMetric.usableText(presentation.message)
@@ -179,18 +228,20 @@ final class DroneDockTaskStatusView: UIView {
width: width - 46, lines: 2))
let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0
let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps
let countdownTextHeight = hasCountdown ? ceil(countdownLabel.font.lineHeight) : 0
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0) + (hasCountdown ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + countdownTextHeight + naturalDevice + 44 + naturalGaps
effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight)))
usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight
// 先收紧图标和间距;只有不足九成空间时才缩小文字。
let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9
titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold)
titleLabel.font = .systemFont(ofSize: isExtreme && hasCountdown ? 17 : max(17, 22 * fontScale), weight: .semibold)
messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale))
deviceLabel.font = .systemFont(ofSize: 12)
let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale
let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale)
let gap: CGFloat = isExtreme ? (hasCountdown ? 2 : 4)
: hasCountdown && usesCompactLayout ? 6 : max(4, 10 * effectiveScale)
let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale
titleLabel.numberOfLines = usesCompactLayout ? 1 : 2
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
@@ -204,8 +255,8 @@ final class DroneDockTaskStatusView: UIView {
width: width, lines: messageLineCount)
let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight)
var contentHeight: CGFloat {
titleHeight + bodyHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap
titleHeight + bodyHeight + countdownTextHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1) + (hasCountdown ? 1 : 0)) * gap
}
while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden {
messageLineCount -= 1
@@ -246,7 +297,8 @@ final class DroneDockTaskStatusView: UIView {
case .navigating: ("paperplane.fill", DroneDockStyle.primary)
case .ready: ("checkmark.circle.fill", DroneDockStyle.success)
case .shooting: ("video.fill", DroneDockStyle.primary)
case .postShootUploading: ("icloud.and.arrow.up", DroneDockStyle.primary)
case .postShootUploading: ("checkmark.circle.fill", DroneDockStyle.success)
case .postShootUploadFailed: ("exclamationmark.circle.fill", DroneDockStyle.warning)
case .paused: ("pause.circle.fill", DroneDockStyle.warning)
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
@@ -261,5 +313,4 @@ final class DroneDockTaskStatusView: UIView {
onPrimaryAction?()
}
@objc private func detailsTapped() { onDetails?() }
}
@@ -0,0 +1,99 @@
import UIKit
@preconcurrency import VolcEngineRTC
/// 接收端最小能力,隔离测试无需初始化 SDK 或使用真实凭证。
@MainActor
protocol DroneDockRTCReceivingEngine: AnyObject {
/// 创建一个独立接收房间并转交事件。
func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)?
/// 按 SDK 提供的流 ID 绑定或解绑画布。
func setVideoView(_ view: UIView?, streamID: String) -> Int
/// 销毁引擎及本地接收资源。
func destroy()
}
/// 单路只收视频的房间;不提供发布、采集或设备控制能力。
@MainActor
protocol DroneDockRTCReceivingRoom: AnyObject {
/// 使用与当前用户匹配的凭证入房。
func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int
/// 同用户凭证续期。
func updateToken(_ token: String) -> Int
/// 订阅或取消订阅远端视频。
func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int
/// 退出并销毁接收房间。
func destroy()
}
/// 火山 SDK 适配器;真实创建点再次拦截 Debug,测试不能通过注入绕开保护。
@MainActor
final class DroneDockVolcEngineAdapter: DroneDockRTCReceivingEngine {
private let engine: ByteRTCEngine
private let delegate: DroneDockVolcDelegate
private init(engine: ByteRTCEngine, delegate: DroneDockVolcDelegate) {
self.engine = engine
self.delegate = delegate
}
/// 仅在构建策略允许真实图传时构造 SDK。
static func make(appID: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)? {
guard !DeviceCommandDebugPolicy.blocksLiveRequests else { return nil }
let delegate = DroneDockVolcDelegate(emit: onEvent)
let config = ByteRTCEngineConfig()
config.appID = appID
guard let engine = ByteRTCEngine.createRTCEngine(config, delegate: delegate) else { return nil }
return DroneDockVolcEngineAdapter(engine: engine, delegate: delegate)
}
/// 每个房间独立保留回调桥接,避免弱引用导致事件丢失。
func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)? {
guard let room = engine.createRTCRoom(id) else { return nil }
return DroneDockVolcRoomAdapter(room: room, delegate: DroneDockVolcDelegate(emit: onEvent))
}
/// 画布只依赖发布回调的 streamID,不假定远端流索引为零。
func setVideoView(_ view: UIView?, streamID: String) -> Int {
let canvas = ByteRTCVideoCanvas()
canvas.view = view
canvas.renderMode = .fit
return Int(engine.setRemoteVideoCanvas(streamID, withCanvas: canvas))
}
/// 房间由接收器先释放,再销毁共享引擎。
func destroy() {
engine.delegate = nil
ByteRTCEngine.destroyRTCEngine()
}
}
/// 将只收视频的房间配置封装在 SDK 边界,所有回调由接收器切回主线程。
@MainActor
private final class DroneDockVolcRoomAdapter: DroneDockRTCReceivingRoom {
private let room: ByteRTCRoom
private let delegate: DroneDockVolcDelegate
init(room: ByteRTCRoom, delegate: DroneDockVolcDelegate) {
self.room = room
self.delegate = delegate
room.setRTCRoomDelegate(delegate)
}
func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int {
let config = ByteRTCRoomConfig()
config.isPublishAudio = false
config.isPublishVideo = false
config.isAutoSubscribeAudio = false
config.isAutoSubscribeVideo = false
let user = ByteRTCUserInfo()
user.userId = configuration.userID
return Int(room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: config))
}
func updateToken(_ token: String) -> Int { Int(room.updateToken(token)) }
func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int { Int(room.subscribeStreamVideo(streamID, subscribe: subscribe)) }
func destroy() {
room.setRTCRoomDelegate(nil)
room.destroy()
}
}
@@ -11,11 +11,37 @@ protocol DroneDockLivePlaying: AnyObject {
func stop()
}
/// 一个 RTC 引擎接收两个房间,机巢先接入,无人机有帧后覆盖,停流后恢复机巢。
/// 真实 SDK 入口始终执行编译期禁飞保护,没有运行时放行参数。
@MainActor
final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
private var engine: ByteRTCEngine?
private var delegate: DroneDockVolcDelegate?
private let receiver = DroneDockLiveReceiver(makeEngine: DroneDockVolcEngineAdapter.make)
/// Release 通过接收器播放;Debug 在创建 SDK 之前拒绝连接。
func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView,
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) {
guard !DeviceCommandDebugPolicy.blocksLiveRequests else {
stop(); onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return
}
receiver.start(configurations, in: view, onEvent: onEvent)
}
/// 释放本机播放资源,不发送任何设备控制请求。
func stop() { receiver.stop() }
}
/// 一个 RTC 引擎接收两个房间,机巢先接入,无人机有帧后覆盖,停流后恢复机巢。
@MainActor
final class DroneDockLiveReceiver: DroneDockLivePlaying {
private var engine: (any DroneDockRTCReceivingEngine)?
private let makeEngine: (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)?
private let firstFrameDelay: @Sendable () async throws -> Void
/// 生产环境注入带 Debug 保护的适配器;测试只注入内存接收端。
init(makeEngine: @escaping (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)?,
firstFrameDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(20)) }) {
self.makeEngine = makeEngine
self.firstFrameDelay = firstFrameDelay
}
private weak var container: UIView?
private var sources: [String: DroneDockVolcSource] = [:]
private var configurations: [DroneDockVolcLiveConfiguration] = []
@@ -29,9 +55,6 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
/// 加入只收视频的房间;同一来源只更新 Token,避免后台重查导致画面闪断。
func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView,
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) {
guard !DeviceCommandDebugPolicy.blocksLiveRequests else {
stop(); onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return
}
guard let first = configurations.first else { stop(); return }
if container !== view || self.configurations.first?.appID != first.appID { stop() }
self.onEvent = onEvent
@@ -39,16 +62,12 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
self.configurations = configurations
if engine == nil {
let generation = generation
let delegate = DroneDockVolcDelegate { [weak self] event in
guard let engine = makeEngine(first.appID, { [weak self] event in
Task { @MainActor [weak self] in
guard let self, self.generation == generation else { return }
self.receive(event)
}
}
self.delegate = delegate
let config = ByteRTCEngineConfig()
config.appID = first.appID
guard let engine = ByteRTCEngine.createRTCEngine(config, delegate: delegate) else {
}) else {
stop(); onEvent(.failed("图传播放器初始化失败")); return
}
self.engine = engine
@@ -74,10 +93,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
generation = UUID()
onEvent = nil
for role in Array(sources.keys) { removeSource(role) }
engine?.delegate = nil
if engine != nil { ByteRTCEngine.destroyRTCEngine() }
engine?.destroy()
engine = nil
delegate = nil
container = nil
configurations = []
selection = DroneDockLiveSourceSelection()
@@ -105,7 +122,15 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
scheduleExpiry(source)
return
}
guard let container, let room = engine?.createRTCRoom(configuration.roomID) else {
guard let container else { return }
let generation = generation
let sourceID = UUID()
guard let room = engine?.makeRoom(configuration.roomID, onEvent: { [weak self] event in
Task { @MainActor [weak self] in
guard let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
self.receive(event)
}
}) else {
failedRoles.insert(role)
if role == "airport" { allowsDroneConnection = true }
return
@@ -115,25 +140,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
view.backgroundColor = .black
view.isHidden = true
container.addSubview(view)
let generation = generation
let sourceID = UUID()
let delegate = DroneDockVolcDelegate { [weak self] event in
Task { @MainActor [weak self] in
guard let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
self.receive(event)
}
}
let source = DroneDockVolcSource(id: sourceID, configuration: configuration, room: room, view: view, delegate: delegate)
let source = DroneDockVolcSource(id: sourceID, configuration: configuration, room: room, view: view)
sources[role] = source
room.setRTCRoomDelegate(delegate)
let roomConfig = ByteRTCRoomConfig()
roomConfig.isPublishAudio = false
roomConfig.isPublishVideo = false
roomConfig.isAutoSubscribeAudio = false
roomConfig.isAutoSubscribeVideo = false
let user = ByteRTCUserInfo()
user.userId = configuration.userID
let result = room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: roomConfig)
let result = room.join(configuration)
guard result == 0 else {
removeSource(role)
failedRoles.insert(role)
@@ -141,10 +150,12 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
return
}
// 机巢无首帧时不能无限等待,仍尝试无人机;已连房间继续等待发布事件。
let delay = firstFrameDelay
source.timeoutTask = Task { @MainActor [weak self] in
try? await Task.sleep(for: .seconds(20))
do { try await delay() } catch { return }
guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
self.sourceFailed(role)
// 首帧等待超时只开放另一路;不能销毁仍在等待发布的房间或取消补取参数。
self.markReady(false, source: source)
}
scheduleExpiry(source)
}
@@ -163,6 +174,11 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
self.removeSource(role)
self.displaySelectedSource()
if self.sources.isEmpty {
let callback = self.onEvent
self.stop()
callback?(.expired)
}
}
}
@@ -171,32 +187,28 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
guard let source = sources.removeValue(forKey: role) else { return }
source.timeoutTask?.cancel()
source.expiryTask?.cancel()
if let streamID = source.streamID { engine?.setRemoteVideoCanvas(streamID, withCanvas: nil) }
source.room.setRTCRoomDelegate(nil)
if let streamID = source.streamID { _ = engine?.setVideoView(nil, streamID: streamID) }
source.room.destroy()
source.view.removeFromSuperview()
}
private func receive(_ event: DroneDockVolcEvent) {
switch event {
case .published(let id, let roomID, let index, let published):
guard index == 0, let source = source(in: roomID) else { return }
case .published(let id, let roomID, let published):
guard !id.isEmpty, let source = source(in: roomID) else { return }
if !published {
guard source.streamID == id else { return }
engine?.setRemoteVideoCanvas(id, withCanvas: nil)
source.room.subscribeStreamVideo(id, subscribe: false)
_ = engine?.setVideoView(nil, streamID: id)
_ = source.room.subscribeVideo(id, subscribe: false)
source.streamID = nil
markReady(false, source: source)
return
}
guard source.streamID == nil else { return }
source.streamID = id
let canvas = ByteRTCVideoCanvas()
canvas.view = source.view
canvas.renderMode = .fit
let render = engine?.setRemoteVideoCanvas(id, withCanvas: canvas)
let subscribe = source.room.subscribeStreamVideo(id, subscribe: true)
if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role) }
let render = engine?.setVideoView(source.view, streamID: id)
let subscribe = source.room.subscribeVideo(id, subscribe: true)
if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role, message: "图传订阅失败(\(render ?? -1)/\(subscribe)),请重试") }
case .frame(let id, let roomID):
guard let source = source(in: roomID), source.streamID == id else { return }
markReady(true, source: source)
@@ -207,9 +219,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
case .stopped, .frozen, .failed: markReady(false, source: source)
default: break
}
case .roomFailed(let roomID):
case .roomFailed(let roomID, let code):
guard let source = source(in: roomID) else { return }
sourceFailed(source.configuration.role)
sourceFailed(source.configuration.role, message: "图传入房失败(\(code)),请重试")
case .connectionLost:
for source in sources.values { selection.setReady(false, role: source.configuration.role) }
displaySelectedSource()
@@ -237,7 +249,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
}
}
private func sourceFailed(_ role: String) {
private func sourceFailed(_ role: String, message: String) {
failedRoles.insert(role)
selection.setReady(false, role: role)
if role == "airport" { allowsDroneConnection = true; connectDroneIfAllowed() }
@@ -245,7 +257,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
if selection.selectedRole == nil, Set(configurations.map(\.role)).isSubset(of: failedRoles) {
let callback = onEvent
stop()
callback?(.failed("暂未收到可用的图传画面,请重试"))
callback?(.failed(message))
}
}
@@ -264,39 +276,38 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
private final class DroneDockVolcSource {
let id: UUID
var configuration: DroneDockVolcLiveConfiguration
let room: ByteRTCRoom
let room: any DroneDockRTCReceivingRoom
let view: UIView
let delegate: DroneDockVolcDelegate
var streamID: String?
var timeoutTask: Task<Void, Never>?
var expiryTask: Task<Void, Never>?
init(id: UUID, configuration: DroneDockVolcLiveConfiguration, room: ByteRTCRoom, view: UIView, delegate: DroneDockVolcDelegate) {
self.id = id; self.configuration = configuration; self.room = room; self.view = view; self.delegate = delegate
init(id: UUID, configuration: DroneDockVolcLiveConfiguration, room: any DroneDockRTCReceivingRoom, view: UIView) {
self.id = id; self.configuration = configuration; self.room = room; self.view = view
}
}
/// SDK 工作线程只转交值类型事件;事件带房间和流身份以隔离两路回调。
private enum DroneDockVolcEvent: Sendable {
case published(String, String, Int, Bool)
enum DroneDockVolcEvent: Sendable {
case published(String, String, Bool)
case frame(String, String)
case videoState(String, String, ByteRTCRemoteVideoState)
case roomFailed(String)
case roomFailed(String, Int)
case connectionLost
case failed(Int)
}
/// SDK 回调桥接,不采集音视频,不处理设备控制消息。
private final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, ByteRTCRoomDelegate {
final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, ByteRTCRoomDelegate {
private let emit: @Sendable (DroneDockVolcEvent) -> Void
init(emit: @escaping @Sendable (DroneDockVolcEvent) -> Void) { self.emit = emit }
func rtcRoom(_ rtcRoom: ByteRTCRoom, onUserPublishStreamVideo streamId: String, info: ByteRTCStreamInfo, isPublish: Bool) {
emit(.published(streamId, info.roomId, info.streamIndex, isPublish))
emit(.published(streamId, info.roomId, isPublish))
}
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String, state: Int, extraInfo: String) {
if state != 0 { emit(.roomFailed(roomId)) }
if state != 0 { emit(.roomFailed(roomId, state)) }
}
func rtcEngine(_ engine: ByteRTCEngine, onFirstRemoteVideoFrameDecoded streamId: String,