feat: 完善机巢任务实时状态、双路图传与继续查看入口
This commit is contained in:
@@ -213,7 +213,11 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
let materialStatus: Int?
|
||||
/// 已有成片的有效任务数。
|
||||
let filmCount: Int?
|
||||
/// 后端是否允许新增待飞任务。
|
||||
/// orders 选定的执行中订单飞行任务 ID;详情和旧摘要未提供时为空。
|
||||
let activeTaskID: Int?
|
||||
/// orders 返回的执行中状态,当前合同有任务时为 20,不作为任务页阶段。
|
||||
let activeTaskStatus: Int?
|
||||
/// 后端是否允许新增待飞任务;有执行中任务时优先查看该任务。
|
||||
let canCreateTask: Bool?
|
||||
/// 后端是否允许上传成片。
|
||||
let canUploadFilm: Bool?
|
||||
@@ -230,6 +234,7 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
case touristPhoneMask = "user_phone", packageName = "project_name"
|
||||
case shotTotal = "shoot_count", shotUsed = "shot_count", shotRemain = "remaining_count"
|
||||
case shootStatus = "shoot_status", orderStatus = "order_status", materialStatus = "material_status"
|
||||
case activeTaskID = "active_task_id", activeTaskStatus = "active_task_status"
|
||||
case filmCount = "film_count", canCreateTask = "can_create_task", canUploadFilm = "can_upload_film"
|
||||
case canConfirm = "can_confirm", confirmStatus = "confirm_status", confirmedAt = "confirmed_at"
|
||||
}
|
||||
@@ -263,6 +268,11 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
shootStatus = try container.decodeIfPresent(String.self, forKey: .shootStatus)
|
||||
orderStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .orderStatus)?.value
|
||||
materialStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .materialStatus)?.value
|
||||
activeTaskID = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .activeTaskID)?.value
|
||||
activeTaskStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .activeTaskStatus)?.value
|
||||
if let activeTaskID, activeTaskID <= 0 {
|
||||
throw DecodingError.dataCorruptedError(forKey: .activeTaskID, in: container, debugDescription: "进行中任务 ID 必须为正整数")
|
||||
}
|
||||
canCreateTask = try container.decodeIfPresent(Bool.self, forKey: .canCreateTask)
|
||||
canUploadFilm = try container.decodeIfPresent(Bool.self, forKey: .canUploadFilm)
|
||||
canConfirm = try container.decodeIfPresent(Bool.self, forKey: .canConfirm)
|
||||
@@ -312,8 +322,9 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
/// 邀请游客确认须拍满套餐次数,且后端明确允许发起确认。
|
||||
var canInviteVisitorConfirmation: Bool { hasCompletedShootingQuota && canConfirm == true }
|
||||
|
||||
/// 依据后端权限提供入口标识;邀请确认额外要求成功拍满套餐次数。
|
||||
/// 后端选定的执行中任务优先于新增拍摄;无任务时沿用交付和次数规则。
|
||||
var primaryAction: String? {
|
||||
if activeTaskID != nil { return "view_task" }
|
||||
if canCreateTask == true { return "start_shoot" }
|
||||
if canInviteVisitorConfirmation { return "confirm_delivery" }
|
||||
if canUploadFilm == true { return "view_materials" }
|
||||
@@ -323,6 +334,7 @@ struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
/// 与后端权限对应的按钮文案。
|
||||
var actionTitle: String? {
|
||||
switch primaryAction {
|
||||
case "view_task": return "继续查看任务"
|
||||
case "start_shoot": return "开始拍摄"
|
||||
case "confirm_delivery": return "邀请确认"
|
||||
case "view_materials": return "查看素材"
|
||||
|
||||
@@ -21,6 +21,33 @@ struct DroneDockVolcLiveConfiguration: Equatable, Sendable, CustomDebugStringCon
|
||||
guard let stream = response.play, stream.available == true else {
|
||||
throw DroneDockLiveConnectionError("图传尚未提供可用的视频流")
|
||||
}
|
||||
return try parse(stream, response: response, now: now)
|
||||
}
|
||||
|
||||
/// 解析两路参数,机巢排在首位;一路缺失或参数无效不影响另一路播放。
|
||||
static func parseSources(_ response: DroneDockLiveResponse, now: Date) throws -> [Self] {
|
||||
guard response.playable == true else { return [try parse(response, now: now)] }
|
||||
var values: [Self] = []
|
||||
var lastError: Error?
|
||||
for role in ["airport", "drone"] {
|
||||
let explicit = role == "airport" ? response.airportStream : response.droneStream
|
||||
let stream = explicit?.available != nil ? explicit : (response.play?.role == role ? response.play : nil)
|
||||
guard let stream, stream.available == true else { continue }
|
||||
do {
|
||||
guard stream.role == role else { throw DroneDockLiveConnectionError("图传来源与设备角色不一致") }
|
||||
values.append(try parse(stream, response: response, now: now))
|
||||
} catch { lastError = error }
|
||||
}
|
||||
guard !values.isEmpty else { throw lastError ?? DroneDockLiveConnectionError("图传尚未提供可用的视频流") }
|
||||
if values.count == 2 {
|
||||
guard values[0].appID == values[1].appID, values[0].roomID != values[1].roomID else {
|
||||
throw DroneDockLiveConnectionError("机巢与无人机图传需使用同一应用下的不同房间,请联系后台确认")
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
private static func parse(_ stream: DroneDockLiveStream, response: DroneDockLiveResponse, now: Date) throws -> Self {
|
||||
guard stream.urlType == "volc" else {
|
||||
throw DroneDockLiveConnectionError("暂不支持当前图传类型,请联系后台确认使用火山图传")
|
||||
}
|
||||
@@ -79,6 +106,25 @@ struct DroneDockLiveConnectionError: Error, LocalizedError, Equatable, Sendable
|
||||
/// 播放器明确回调;只有首帧到达才算已显示真实画面。
|
||||
enum DroneDockLivePlaybackEvent: Equatable, Sendable {
|
||||
case firstFrame
|
||||
/// 实际有画面的来源切换;nil 表示两路当前均无视频,继续等待推流。
|
||||
case sourceChanged(String?)
|
||||
case failed(String)
|
||||
case expired
|
||||
}
|
||||
|
||||
/// 双路选流只使用视频就绪/中断事件;HTTP 的 available 不代表首帧已经到达。
|
||||
struct DroneDockLiveSourceSelection {
|
||||
private(set) var readyRoles: Set<String> = []
|
||||
/// 无人机有视频时优先;无人机停流立即退回仍有画面的机巢。
|
||||
var selectedRole: String? {
|
||||
if readyRoles.contains("drone") { return "drone" }
|
||||
if readyRoles.contains("airport") { return "airport" }
|
||||
return nil
|
||||
}
|
||||
|
||||
/// 重复回调幂等,未知来源不会参与展示。
|
||||
mutating func setReady(_ ready: Bool, role: String) {
|
||||
guard ["airport", "drone"].contains(role) else { return }
|
||||
if ready { readyRoles.insert(role) } else { readyRoles.remove(role) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,11 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
let playable: Bool?
|
||||
let unavailableMessage: String?
|
||||
let play: DroneDockLiveStream?
|
||||
/// 两路独立接收参数;是否真正有画面由 RTC 视频事件判断。
|
||||
let airportStream: DroneDockLiveStream?
|
||||
let droneStream: DroneDockLiveStream?
|
||||
/// 后端建议的缺流重查间隔,缺失时按 30 秒处理。
|
||||
let refreshHintMS: Int?
|
||||
/// 随接口返回的展示读数,不触发额外实时采集。
|
||||
let metrics: [DroneDockHomeMetric]
|
||||
/// 脱敏回执,不包含 RTC 连接串或 Token。
|
||||
@@ -24,6 +29,7 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
/// live 文档中的已知字段映射。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case orderFlightTaskID = "order_flight_task_id", airport, drone, task
|
||||
case protocolInfo = "protocol"
|
||||
case airportSN = "airport_sn", metrics
|
||||
case planeID = "plane_id", playable, play, unavailableMessage = "unavailable_message"
|
||||
}
|
||||
@@ -40,6 +46,13 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
|
||||
playable = try container.decodeIfPresent(Bool.self, forKey: .playable)
|
||||
unavailableMessage = try container.decodeIfPresent(String.self, forKey: .unavailableMessage)
|
||||
play = try container.decodeIfPresent(DroneDockLiveStream.self, forKey: .play)
|
||||
airportStream = try? container.decodeIfPresent(DroneDockLiveStream.self, forKey: .airport)
|
||||
droneStream = try? container.decodeIfPresent(DroneDockLiveStream.self, forKey: .drone)
|
||||
let protocolInfo = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .protocolInfo)
|
||||
if case .object(let fields) = protocolInfo, case .number(let milliseconds) = fields["refresh_hint_ms"],
|
||||
milliseconds.isFinite, milliseconds > 0, milliseconds < 3_600_000 {
|
||||
refreshHintMS = NSDecimalNumber(decimal: milliseconds).intValue
|
||||
} else { refreshHintMS = nil }
|
||||
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
|
||||
let raw = try DroneDockHomeJSONValue(from: decoder)
|
||||
let encoder = JSONEncoder()
|
||||
|
||||
@@ -7,22 +7,23 @@ enum DroneDockSnapshotAcceptance {
|
||||
|
||||
/// 先解析业务码再解析 data,兼容订阅失败时 data=[]。
|
||||
enum DroneDockShootingSocketMessage {
|
||||
case opened
|
||||
case subscribed(taskID: Int, hasSnapshot: Bool)
|
||||
case snapshot(DroneDockShootingResponse)
|
||||
case rejected(code: Int, message: String)
|
||||
case unrelated
|
||||
|
||||
/// WebSocket 成功码为 0,不使用 HTTP 的 100000 Envelope。
|
||||
/// 按新版协议解析 100000 成功包,欢迎帧仅用于触发 310,不代表订阅成功。
|
||||
static func decode(_ data: Data) throws -> Self {
|
||||
// 服务端建连先发 Opened。它不代表 310 订阅成功,也不能取消订阅超时或 HTTP 兜底。
|
||||
if String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) == "Opened" {
|
||||
return .unrelated
|
||||
return .opened
|
||||
}
|
||||
let json = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)
|
||||
if json as? String == "Opened" { return .unrelated }
|
||||
if json as? String == "Opened" { return .opened }
|
||||
guard let root = json as? [String: Any],
|
||||
let code = root["code"] as? Int else { throw APIError.invalidResponse }
|
||||
if code != 0 {
|
||||
if code != 100000 {
|
||||
return .rejected(code: code, message: root["msg"] as? String ?? "任务订阅失败")
|
||||
}
|
||||
guard let body = root["data"] as? [String: Any] else { throw APIError.invalidResponse }
|
||||
|
||||
@@ -10,6 +10,8 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
|
||||
case ready
|
||||
/// 服务端明确正在拍摄。
|
||||
case shooting
|
||||
/// 录制已结束,素材仍在下载、上传或渲染,尚未就绪。
|
||||
case postShootUploading
|
||||
/// 服务端明确已暂停。
|
||||
case paused
|
||||
/// 服务端明确正在返航。
|
||||
|
||||
@@ -31,6 +31,7 @@ final class DroneDockShootingRealtimeSession {
|
||||
private var active = false
|
||||
private var generation = 0
|
||||
private var retryAttempt = 0
|
||||
private var subscriptionSent = false
|
||||
private var subscribed = false
|
||||
private var lastSnapshotAt: TimeInterval?
|
||||
private var latestSnapshot: DroneDockShootingResponse?
|
||||
@@ -101,11 +102,6 @@ final class DroneDockShootingRealtimeSession {
|
||||
}
|
||||
let transport = self.makeTransport()
|
||||
self.transport = transport
|
||||
let request = DroneDockShootingSocketMessage.subscribe(taskID: self.taskID, token: ticket.socketToken)
|
||||
self.log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(request.utf8))])
|
||||
try await transport.send(request)
|
||||
guard self.accepts(current) else { return }
|
||||
self.startHeartbeat(generation: current, transport: transport)
|
||||
// 不让无限 receive 循环强持有协调器或页面。
|
||||
self.connectionTask = Task { @MainActor [weak self] in
|
||||
do {
|
||||
@@ -113,7 +109,8 @@ final class DroneDockShootingRealtimeSession {
|
||||
let data = try await transport.receive()
|
||||
guard let self, self.accepts(current) else { return }
|
||||
self.log("response.received", fields: ["body": DroneDockDiagnostics.payload(data)])
|
||||
try self.handle(DroneDockShootingSocketMessage.decode(data))
|
||||
try await self.handle(DroneDockShootingSocketMessage.decode(data),
|
||||
generation: current, transport: transport, token: ticket.socketToken)
|
||||
}
|
||||
} catch {
|
||||
guard let self, self.accepts(current) else { return }
|
||||
@@ -128,9 +125,21 @@ final class DroneDockShootingRealtimeSession {
|
||||
}
|
||||
}
|
||||
|
||||
private func handle(_ message: DroneDockShootingSocketMessage) throws {
|
||||
private func handle(_ message: DroneDockShootingSocketMessage, generation current: Int,
|
||||
transport: any DroneDockShootingSocketTransport, token: String) async throws {
|
||||
switch message {
|
||||
case .opened:
|
||||
// 必须先等应用层 Opened,再发文本帧;重复欢迎消息不能重复订阅或延长首包期限。
|
||||
guard !subscriptionSent else { return }
|
||||
let request = DroneDockShootingSocketMessage.subscribe(taskID: taskID, token: token)
|
||||
try await transport.send(request)
|
||||
guard accepts(current) else { return }
|
||||
subscriptionSent = true
|
||||
// 记录实际完成本地发送的 310;服务端是否接受仍以 ack 和完整快照为准。
|
||||
log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(request.utf8))])
|
||||
startHeartbeat(generation: current, transport: transport)
|
||||
case .subscribed(let id, let hasSnapshot):
|
||||
guard subscriptionSent else { throw APIError.decodeFailed("订阅回执先于 310 发送") }
|
||||
guard id == taskID else { throw APIError.decodeFailed("订阅回执任务不一致") }
|
||||
subscribed = true
|
||||
if !hasSnapshot { update(.fallback("任务缓存尚未就绪,正在通过接口更新")) }
|
||||
@@ -229,11 +238,13 @@ final class DroneDockShootingRealtimeSession {
|
||||
deadlineTask?.cancel(); deadlineTask = nil
|
||||
heartbeatTask?.cancel(); heartbeatTask = nil
|
||||
pongDeadlineTask?.cancel(); pongDeadlineTask = nil
|
||||
if unsubscribe, transport != nil {
|
||||
let unsubscribeTaskID = unsubscribe && subscriptionSent ? taskID : nil
|
||||
if unsubscribeTaskID != nil, transport != nil {
|
||||
log("request.started", fields: ["body": DroneDockDiagnostics.payload(Data(DroneDockShootingSocketMessage.unsubscribe(taskID: taskID).utf8))])
|
||||
}
|
||||
transport?.close(unsubscribing: unsubscribe ? taskID : nil)
|
||||
transport?.close(unsubscribing: unsubscribeTaskID)
|
||||
transport = nil
|
||||
subscriptionSent = false
|
||||
subscribed = false
|
||||
latestSnapshot = nil
|
||||
lastSnapshotAt = nil
|
||||
|
||||
@@ -10,13 +10,24 @@ final class DroneDockLiveViewModel {
|
||||
private(set) var response: DroneDockLiveResponse?
|
||||
/// 图传区域当前可展示状态。
|
||||
private(set) var state: DroneDockLiveState
|
||||
/// 请求期间阻止重复获取,不安排定时轮询。
|
||||
/// 请求期间阻止重复获取,缺少流参数或凭证临期时由页面安排重查。
|
||||
private(set) var isLoading = false
|
||||
/// 仅显式正式入口允许解析设备 RTC;本地模拟即使收到参数也不连接设备。
|
||||
let allowsDevicePlayback: Bool
|
||||
/// 每次进入页面或回前台仅从空闲态自动加载,状态刷新不重复启动图传。
|
||||
var loadsAutomatically: Bool { canLoad && state == .idle }
|
||||
private(set) var rtcConfiguration: DroneDockVolcLiveConfiguration?
|
||||
/// 同一会话的机巢与无人机配置,可增补或续期而不重启正在播放的一路。
|
||||
private(set) var rtcConfigurations: [DroneDockVolcLiveConfiguration] = []
|
||||
private(set) var activeRole: String?
|
||||
|
||||
/// 只在缺一路参数或凭证临期时请求 live;普通状态刷新不触发推流请求。
|
||||
var nextParameterRefreshDelay: TimeInterval? {
|
||||
guard allowsDevicePlayback, !identityInvalidated, !rtcConfigurations.isEmpty else { return nil }
|
||||
let expiryDelay = rtcConfigurations.map { $0.expiresAt.timeIntervalSince(now()) - 30 }.min() ?? 30
|
||||
let discoveryDelay = rtcConfigurations.count < 2 ? Double(min(max(response?.refreshHintMS ?? 30_000, 5_000), 60_000)) / 1000 : .infinity
|
||||
return max(5, min(expiryDelay, discoveryDelay))
|
||||
}
|
||||
private(set) var playbackSessionID: UUID?
|
||||
|
||||
private let service: (any DroneDockLiveServing)?
|
||||
@@ -73,7 +84,7 @@ final class DroneDockLiveViewModel {
|
||||
case .unavailable(let reason), .failed(let reason): return reason
|
||||
case .localPreview: return "仅播放本地样片,未连接无人机"
|
||||
case .connecting: return "正在等待视频画面"
|
||||
case .playing: return rtcConfiguration?.role == "airport" ? "机巢摄像头" : "无人机摄像头"
|
||||
case .playing: return (activeRole ?? rtcConfiguration?.role) == "airport" ? "机巢摄像头" : "无人机摄像头"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +105,7 @@ final class DroneDockLiveViewModel {
|
||||
|
||||
/// 发起一次图传请求,拒绝重复点击、迟到响应、身份不符及远程模拟视频来源。
|
||||
@MainActor
|
||||
func refresh(onRequestStarted: (@MainActor () -> Void)? = nil) async {
|
||||
func refresh(keepingPlayback: Bool = false, onRequestStarted: (@MainActor () -> Void)? = nil) async {
|
||||
guard canLoad, let service else { return }
|
||||
generation &+= 1
|
||||
let requestGeneration = generation
|
||||
@@ -113,20 +124,31 @@ final class DroneDockLiveViewModel {
|
||||
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 {
|
||||
clearPlayback()
|
||||
throw APIError.decodeFailed("图传回执与当前拍摄任务不一致")
|
||||
}
|
||||
let previousResponse = response
|
||||
let sameDevice = previousResponse?.planeID == value.planeID && previousResponse?.airportSN == value.airportSN
|
||||
if previousResponse != nil && !sameDevice { clearPlayback() }
|
||||
response = value
|
||||
if allowsDevicePlayback {
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
do {
|
||||
rtcConfiguration = try DroneDockVolcLiveConfiguration.parse(value, now: now())
|
||||
playbackSessionID = UUID()
|
||||
state = .connecting
|
||||
DroneDockDiagnostics.event("live.parameters_valid", taskID: taskID, fields: ["provider": "volc", "playback_session": playbackSessionID?.uuidString ?? ""])
|
||||
let configurations = try DroneDockVolcLiveConfiguration.parseSources(value, now: now())
|
||||
let canKeepSession = keepingPlayback && playbackSessionID != nil
|
||||
&& sameDevice
|
||||
&& rtcConfigurations.first?.appID == configurations.first?.appID
|
||||
rtcConfigurations = configurations
|
||||
rtcConfiguration = configurations.first
|
||||
if !canKeepSession {
|
||||
activeRole = nil
|
||||
playbackSessionID = UUID()
|
||||
state = .connecting
|
||||
}
|
||||
} catch {
|
||||
state = .unavailable(error.localizedDescription)
|
||||
DroneDockDiagnostics.event("live.parameters_rejected", taskID: taskID, fields: ["reason": error.localizedDescription])
|
||||
if !keepingPlayback || rtcConfigurations.isEmpty {
|
||||
clearPlayback()
|
||||
state = .unavailable(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -145,12 +167,16 @@ final class DroneDockLiveViewModel {
|
||||
}
|
||||
} catch is CancellationError {
|
||||
guard generation == requestGeneration else { return }
|
||||
state = .idle
|
||||
if rtcConfigurations.isEmpty { state = .idle }
|
||||
} catch {
|
||||
guard accepts(requestGeneration) else { return }
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
state = .failed(error.localizedDescription)
|
||||
let accessDenied: Bool
|
||||
if case APIError.serverCode(let code, _) = error { accessDenied = code == 100098 || code == 100099 }
|
||||
else { accessDenied = false }
|
||||
if !keepingPlayback || rtcConfigurations.isEmpty || accessDenied {
|
||||
clearPlayback()
|
||||
state = .failed(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,8 +187,7 @@ final class DroneDockLiveViewModel {
|
||||
generation &+= 1
|
||||
isLoading = false
|
||||
response = nil
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
clearPlayback()
|
||||
state = service == nil ? .restricted : .idle
|
||||
}
|
||||
|
||||
@@ -179,18 +204,28 @@ final class DroneDockLiveViewModel {
|
||||
DroneDockDiagnostics.event("live.playback_event", taskID: taskID,
|
||||
fields: ["playback_session": sessionID.uuidString, "result": String(describing: event)])
|
||||
switch event {
|
||||
case .firstFrame: state = .playing
|
||||
case .firstFrame:
|
||||
activeRole = rtcConfiguration?.role
|
||||
state = .playing
|
||||
case .sourceChanged(let role):
|
||||
activeRole = role
|
||||
state = role == nil ? .connecting : .playing
|
||||
case .failed(let message):
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
clearPlayback()
|
||||
state = .failed(message)
|
||||
case .expired:
|
||||
rtcConfiguration = nil
|
||||
playbackSessionID = nil
|
||||
clearPlayback()
|
||||
state = .unavailable("图传凭证即将或已经过期,请重新获取")
|
||||
}
|
||||
}
|
||||
|
||||
private func clearPlayback() {
|
||||
rtcConfiguration = nil
|
||||
rtcConfigurations = []
|
||||
activeRole = nil
|
||||
playbackSessionID = nil
|
||||
}
|
||||
|
||||
/// 只接受当前页面与当前身份下的结果,身份变化后不允许重新请求旧任务。
|
||||
@MainActor
|
||||
private func accepts(_ requestGeneration: Int) -> Bool {
|
||||
|
||||
@@ -88,6 +88,13 @@ final class DroneDockShootingTaskViewModel {
|
||||
await refreshSnapshot(allowWhileStarting: false)
|
||||
}
|
||||
|
||||
/// 操作提交前仅作废在途读取,保留快照和操作防重锁;迟到的旧读取不能覆盖操作回查。
|
||||
@MainActor
|
||||
func invalidatePendingRefresh() {
|
||||
generation &+= 1
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
/// 后端建议间隔限制为 2~30 秒;缺失或无效时默认 5 秒,从上次请求结束后计时。
|
||||
var pollIntervalNanoseconds: UInt64 {
|
||||
let hint = response?.planeStatus?.pollHintMS ?? 5_000
|
||||
@@ -109,7 +116,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
let requestGeneration = generation
|
||||
let revisionAtRequest = snapshotRevision
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
// 已失败的旧快照须等有效新响应再恢复操作,避免每次重查先短暂放开。
|
||||
defer {
|
||||
if generation == requestGeneration {
|
||||
isLoading = false
|
||||
@@ -137,7 +144,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
}
|
||||
// 迟到 HTTP 失败不能覆盖请求期间已收到的有效实时状态。
|
||||
guard snapshotRevision == revisionAtRequest else { return }
|
||||
errorMessage = error is CancellationError ? nil : error.localizedDescription
|
||||
if !(error is CancellationError) { errorMessage = error.localizedDescription }
|
||||
DroneDockDiagnostics.event("shooting.refresh_failed", taskID: taskID, fields: [
|
||||
"retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error)
|
||||
])
|
||||
@@ -167,7 +174,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
"state_version": value.stateVersion as Any? ?? NSNull(),
|
||||
"plane_id": value.currentPlane?.id as Any? ?? NSNull()
|
||||
])
|
||||
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
|
||||
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .postShootUploading, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
|
||||
awaitingResummonSnapshot = false
|
||||
}
|
||||
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
|
||||
@@ -218,7 +225,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。
|
||||
var canStartShooting: Bool {
|
||||
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
||||
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& !hasSubmittedStart && !startOutcomeUnknown
|
||||
&& !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty
|
||||
&& resolvedDisplayPhase().0 == .ready
|
||||
@@ -238,6 +245,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
return
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
invalidatePendingRefresh()
|
||||
let planeID = response?.currentPlane?.id
|
||||
startGeneration &+= 1
|
||||
let requestGeneration = startGeneration
|
||||
@@ -308,7 +316,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
|
||||
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
|
||||
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
||||
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot
|
||||
&& !pendingAcceptedCommands.contains(command)
|
||||
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
|
||||
@@ -328,6 +336,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
return
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
invalidatePendingRefresh()
|
||||
commandGeneration &+= 1
|
||||
let requestGeneration = commandGeneration
|
||||
isSendingCommand = true
|
||||
@@ -387,7 +396,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
/// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。
|
||||
var canResummon: Bool {
|
||||
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
||||
&& readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
||||
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
|
||||
&& !hasSubmittedResummon && pendingAcceptedCommands.isEmpty
|
||||
&& resolvedDisplayPhase().0 == .failed
|
||||
@@ -407,6 +416,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
return
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
invalidatePendingRefresh()
|
||||
resummonGeneration &+= 1
|
||||
let requestGeneration = resummonGeneration
|
||||
isResummoning = true
|
||||
@@ -493,6 +503,9 @@ final class DroneDockShootingTaskViewModel {
|
||||
if isLoading { return "正在获取任务状态" }
|
||||
}
|
||||
if resolvedDisplayPhase().0 == .failed { return "任务执行失败" }
|
||||
if resolvedDisplayPhase().0 == .postShootUploading {
|
||||
return usable(response?.ui?.title) ?? "拍摄完毕上传中"
|
||||
}
|
||||
return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel)
|
||||
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
|
||||
}
|
||||
@@ -512,6 +525,9 @@ final class DroneDockShootingTaskViewModel {
|
||||
if let startErrorMessage { return startErrorMessage }
|
||||
if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" }
|
||||
}
|
||||
if resolvedDisplayPhase().0 == .postShootUploading {
|
||||
return usable(response?.ui?.message) ?? "录制已结束,素材正在处理,请稍候。"
|
||||
}
|
||||
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
|
||||
}
|
||||
|
||||
@@ -564,7 +580,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
}
|
||||
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
|
||||
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
|
||||
isActionEnabled: enabled && readAccessError == nil && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
|
||||
isActionEnabled: enabled && readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
|
||||
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil)
|
||||
}
|
||||
|
||||
@@ -678,6 +694,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
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,
|
||||
"paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
|
||||
]
|
||||
let rawPhase = usable(response.ui?.phase)
|
||||
@@ -686,7 +703,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
if phase == .failed { return (.failed, false) }
|
||||
if statuses.contains(30) {
|
||||
if phase == .returning { return (.returning, false) }
|
||||
if let phase, [.navigating, .ready, .shooting, .paused].contains(phase) { return (.unknown, true) }
|
||||
if let phase, [.navigating, .ready, .shooting, .postShootUploading, .paused].contains(phase) { return (.unknown, true) }
|
||||
return (.completed, false)
|
||||
}
|
||||
if phase == .completed {
|
||||
@@ -722,6 +739,7 @@ final class DroneDockShootingTaskViewModel {
|
||||
case .navigating: return "无人机正在前往拍摄点"
|
||||
case .ready: return "无人机已到达"
|
||||
case .shooting: return "正在拍摄"
|
||||
case .postShootUploading: return "拍摄完毕上传中"
|
||||
case .paused: return "拍摄已暂停"
|
||||
case .returning: return "无人机正在返航"
|
||||
case .failed: return "任务执行失败"
|
||||
|
||||
@@ -9,6 +9,7 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
private let preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)?
|
||||
private let materialsControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)?
|
||||
private let confirmationControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private let taskControllerFactory: (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private var refreshTask: Task<Void, Never>?
|
||||
private var loadMoreTask: Task<Void, Never>?
|
||||
private var isRefreshing = false
|
||||
@@ -36,12 +37,14 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
init(viewModel: DroneDockHomeViewModel, paymentControllerFactory: (() -> UIViewController)? = nil,
|
||||
preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
|
||||
materialsControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
|
||||
confirmationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
|
||||
confirmationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
|
||||
taskControllerFactory: ((Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
|
||||
self.viewModel = viewModel
|
||||
self.paymentControllerFactory = paymentControllerFactory
|
||||
self.preparationControllerFactory = preparationControllerFactory
|
||||
self.materialsControllerFactory = materialsControllerFactory
|
||||
self.confirmationControllerFactory = confirmationControllerFactory ?? DroneDockConfirmationEntry.makeController
|
||||
self.taskControllerFactory = taskControllerFactory ?? DroneDockShootingTaskEntry.makeController
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
@@ -299,7 +302,8 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
private func openAllOrders() {
|
||||
let controller = DroneDockOrdersViewController(
|
||||
viewModel: viewModel.makeOrdersViewModel(), preparationControllerFactory: preparationFactory,
|
||||
materialsControllerFactory: materialsFactory, confirmationControllerFactory: confirmationControllerFactory)
|
||||
materialsControllerFactory: materialsFactory, confirmationControllerFactory: confirmationControllerFactory,
|
||||
taskControllerFactory: taskControllerFactory)
|
||||
navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
|
||||
@@ -340,6 +344,12 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
|
||||
private func openPrimaryAction(orderID: String) {
|
||||
guard !isRefreshing, let order = viewModel.orders.first(where: { $0.orderID == orderID }) else { return }
|
||||
if let taskID = order.activeTaskID {
|
||||
guard let navigationController, navigationController.topViewController === self,
|
||||
presentedViewController == nil else { return }
|
||||
navigationController.pushViewController(taskControllerFactory(taskID, order, viewModel.context), animated: true)
|
||||
return
|
||||
}
|
||||
if order.primaryAction == "confirm_delivery" {
|
||||
openConfirmation(order: order)
|
||||
return
|
||||
|
||||
@@ -10,6 +10,7 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
private let materialsControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
|
||||
private let confirmationControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private let taskControllerFactory: (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private let countLabel = DroneDockStyle.label(size: 17, weight: .semibold)
|
||||
private let descriptionLabel = DroneDockStyle.label("分配给我的全部订单,含已完成订单", size: 12, color: DroneDockStyle.secondary)
|
||||
private let filterView = DroneShootingOrderFilterView()
|
||||
@@ -29,12 +30,14 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
preparationControllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController,
|
||||
materialsControllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController,
|
||||
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil,
|
||||
confirmationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
|
||||
confirmationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
|
||||
taskControllerFactory: ((Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
|
||||
self.viewModel = viewModel
|
||||
self.preparationControllerFactory = preparationControllerFactory
|
||||
self.materialsControllerFactory = materialsControllerFactory
|
||||
self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController
|
||||
self.confirmationControllerFactory = confirmationControllerFactory ?? DroneDockConfirmationEntry.makeController
|
||||
self.taskControllerFactory = taskControllerFactory ?? DroneDockShootingTaskEntry.makeController
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
@@ -117,7 +120,7 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
if let order = self.viewModel.orders.first(where: { $0.orderID == id }) {
|
||||
cell.accessibilityIdentifier = "drone.orders.order.\(id)"
|
||||
cell.cardView.apply(homeOrder: order)
|
||||
cell.cardView.onShootingTap = { [weak self] in self?.openPreparation(orderID: id) }
|
||||
cell.cardView.onShootingTap = { [weak self] in self?.openShooting(orderID: id) }
|
||||
cell.cardView.onMaterialsTap = { [weak self] in self?.openMaterials(orderID: id) }
|
||||
cell.cardView.onDeliveryTap = { [weak self] in self?.openDelivery(orderID: id) }
|
||||
cell.cardView.onConfirmationTap = { [weak self] in self?.openConfirmation(orderID: id) }
|
||||
@@ -194,8 +197,15 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
}
|
||||
}
|
||||
|
||||
private func openPreparation(orderID: String) {
|
||||
/// 优先继续查看服务端选定的既有任务,无任务时才进入拍摄准备。
|
||||
private func openShooting(orderID: String) {
|
||||
guard operation == nil, let order = viewModel.orders.first(where: { $0.orderID == orderID }) else { return }
|
||||
if let taskID = order.activeTaskID {
|
||||
guard let navigationController, navigationController.topViewController === self,
|
||||
presentedViewController == nil else { return }
|
||||
navigationController.pushViewController(taskControllerFactory(taskID, order, viewModel.context), animated: true)
|
||||
return
|
||||
}
|
||||
guard order.primaryAction == "start_shoot" else {
|
||||
showUnavailable(order.actionTitle ?? "拍摄订单")
|
||||
return
|
||||
|
||||
@@ -32,6 +32,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
private var commandTask: Task<Void, Never>?
|
||||
private var resummonTask: Task<Void, Never>?
|
||||
private var liveTask: Task<Void, Never>?
|
||||
private var liveParameterTask: Task<Void, Never>?
|
||||
private let liveParameterDelay: @Sendable (TimeInterval) async throws -> Void
|
||||
private var liveGeneration = 0
|
||||
private var requestGeneration = 0
|
||||
private var isPageVisible = false
|
||||
@@ -49,7 +51,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
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) }) {
|
||||
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)) }) {
|
||||
self.viewModel = viewModel
|
||||
self.feedPlaceholder = livePlayer.map { DroneDockTaskLiveView(rtcPlayer: $0) } ?? DroneDockTaskLiveView()
|
||||
self.realtimeSession = realtimeSession
|
||||
@@ -58,6 +61,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
currentContext: { DroneDockHomeViewController.currentContext() })
|
||||
self.simulationRecordsProvider = simulationRecordsProvider
|
||||
self.shootingPollDelay = shootingPollDelay
|
||||
self.liveParameterDelay = liveParameterDelay
|
||||
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
|
||||
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
|
||||
context: context, order: order,
|
||||
@@ -87,6 +91,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
commandTask?.cancel()
|
||||
resummonTask?.cancel()
|
||||
liveTask?.cancel()
|
||||
liveParameterTask?.cancel()
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
@@ -188,18 +193,20 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
taskTitleLabel.font = .systemFont(ofSize: compact ? 16 : 17, weight: .semibold)
|
||||
}
|
||||
|
||||
/// 模拟服务明确注入时才允许开始;真实入口仍只提供读取、详情和已有素材。
|
||||
/// 绑定页面操作与主线程播放回调;飞控仍受构建策略、服务注入及任务门禁约束。
|
||||
override func bindActions() {
|
||||
statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() }
|
||||
statusView.onDetails = { [weak self] in self?.showStatusDetails() }
|
||||
safetyView.onCommand = { [weak self] command in self?.safetyCommandTriggered(command) }
|
||||
feedPlaceholder.onRequest = { [weak self] in self?.refreshLiveIfVisible() }
|
||||
feedPlaceholder.onPlaybackEvent = { [weak self] event, sessionID in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.isPageVisible, self.isApplicationActive else { return }
|
||||
self.liveViewModel.receivePlaybackEvent(event, sessionID: sessionID)
|
||||
self.applySnapshot()
|
||||
guard let self, self.isPageVisible, self.isApplicationActive else { return }
|
||||
self.liveViewModel.receivePlaybackEvent(event, sessionID: sessionID)
|
||||
if self.liveViewModel.playbackSessionID == nil {
|
||||
self.liveParameterTask?.cancel()
|
||||
self.liveParameterTask = nil
|
||||
}
|
||||
self.applySnapshot()
|
||||
}
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
|
||||
name: UIApplication.willResignActiveNotification, object: nil)
|
||||
@@ -228,7 +235,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
|
||||
private func applySnapshot() {
|
||||
guard isViewLoaded else { return }
|
||||
let loading = isRequesting || viewModel.isLoading || isStartingAction || viewModel.isStartingShooting
|
||||
let loading = (viewModel.response == nil && (isRequesting || viewModel.isLoading))
|
||||
|| isStartingAction || viewModel.isStartingShooting
|
||||
|| isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning
|
||||
feedPlaceholder.apply(liveViewModel)
|
||||
feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive)
|
||||
@@ -252,7 +260,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
private func primaryActionTriggered() {
|
||||
logEvent("action.primary", fields: ["action": String(describing: viewModel.presentation.action),
|
||||
"enabled": viewModel.presentation.isActionEnabled])
|
||||
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
|
||||
guard isPageVisible, isApplicationActive,
|
||||
!isStartingAction, !viewModel.isStartingShooting,
|
||||
!isSendingSafetyAction, !viewModel.isSendingCommand,
|
||||
!isResummoningAction, !viewModel.isResummoning else { return }
|
||||
@@ -347,6 +355,16 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
pollTask = nil
|
||||
}
|
||||
|
||||
/// 用户操作优先于后台读取;不停止 Socket,也不解除任何已提交操作的防重锁。
|
||||
private func cancelPendingReadForAction() {
|
||||
cancelScheduledPoll()
|
||||
requestGeneration &+= 1
|
||||
refreshTask?.cancel()
|
||||
refreshTask = nil
|
||||
isRequesting = false
|
||||
viewModel.invalidatePendingRefresh()
|
||||
}
|
||||
|
||||
private func cancelRefresh() {
|
||||
wasRealtimeLive = false
|
||||
realtimeSession?.stop()
|
||||
@@ -401,8 +419,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
|
||||
private func startShootingIfAllowed() {
|
||||
guard !isStartingAction, !isSendingSafetyAction, !isResummoningAction, viewModel.canStartShooting else { return }
|
||||
cancelScheduledPoll()
|
||||
requestGeneration &+= 1
|
||||
cancelPendingReadForAction()
|
||||
let generation = requestGeneration
|
||||
isStartingAction = true
|
||||
applySnapshot()
|
||||
@@ -427,9 +444,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
private func resummonIfAllowed() {
|
||||
guard allowsControlActions, isPageVisible, isApplicationActive,
|
||||
!isResummoningAction, !isStartingAction, !isSendingSafetyAction,
|
||||
!isRequesting, viewModel.canResummon else { return }
|
||||
cancelScheduledPoll()
|
||||
requestGeneration &+= 1
|
||||
viewModel.canResummon else { return }
|
||||
cancelPendingReadForAction()
|
||||
let generation = requestGeneration
|
||||
isResummoningAction = true
|
||||
applySnapshot()
|
||||
@@ -456,25 +472,47 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
}
|
||||
|
||||
/// 可见且活跃时自动开启一次;失败可手动重试,不随 shooting/Socket 刷新重复请求。
|
||||
private func refreshLiveIfVisible(automatically: Bool = false) {
|
||||
private func refreshLiveIfVisible(automatically: Bool = false, keepingPlayback: Bool = false) {
|
||||
guard !automatically || liveViewModel.loadsAutomatically else { return }
|
||||
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
|
||||
liveParameterTask?.cancel()
|
||||
liveParameterTask = nil
|
||||
logEvent("live.request", fields: ["automatic": automatically])
|
||||
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() }
|
||||
await self.liveViewModel.refresh(keepingPlayback: keepingPlayback) { [weak self] in self?.applySnapshot() }
|
||||
guard self.liveGeneration == generation, self.isPageVisible, self.isApplicationActive,
|
||||
!Task.isCancelled else { return }
|
||||
self.liveTask = nil
|
||||
self.applySnapshot()
|
||||
self.scheduleLiveParameterRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
/// 缺少第二路或凭证临期才重新取参数;补流/续期保留健康房间,不随 shooting 轮询。
|
||||
private func scheduleLiveParameterRefresh() {
|
||||
liveParameterTask?.cancel()
|
||||
liveParameterTask = nil
|
||||
guard isPageVisible, isApplicationActive, let interval = liveViewModel.nextParameterRefreshDelay else { return }
|
||||
let generation = liveGeneration
|
||||
let delay = liveParameterDelay
|
||||
liveParameterTask = Task { @MainActor [weak self] in
|
||||
do { try await delay(interval) } catch { return }
|
||||
guard let self, !Task.isCancelled, self.liveGeneration == generation,
|
||||
self.isPageVisible, self.isApplicationActive,
|
||||
self.liveViewModel.nextParameterRefreshDelay != nil else { return }
|
||||
self.liveParameterTask = nil
|
||||
self.refreshLiveIfVisible(keepingPlayback: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 离页或进入后台立即释放播放器,使旧图传响应无法恢复播放。
|
||||
private func stopLive() {
|
||||
liveGeneration &+= 1
|
||||
liveParameterTask?.cancel()
|
||||
liveParameterTask = nil
|
||||
liveTask?.cancel()
|
||||
liveTask = nil
|
||||
liveViewModel.invalidate()
|
||||
@@ -487,7 +525,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)])
|
||||
guard allowsControlActions, isPageVisible, isApplicationActive,
|
||||
presentedViewController == nil, !isSendingSafetyAction, !isStartingAction,
|
||||
!isResummoningAction, !isRequesting, viewModel.canSendCommand(command) else { return }
|
||||
!isResummoningAction, viewModel.canSendCommand(command) else { return }
|
||||
if command == .returnHome {
|
||||
let simulated = simulationRecordsProvider != nil
|
||||
let alert = UIAlertController(title: simulated ? "立即返航(本地模拟)" : "立即返航",
|
||||
@@ -507,10 +545,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
/// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。
|
||||
private func sendSafetyCommand(_ command: DroneDockSafetyCommand) {
|
||||
guard allowsControlActions, isPageVisible, isApplicationActive,
|
||||
!isSendingSafetyAction, !isStartingAction, !isResummoningAction, !isRequesting,
|
||||
!isSendingSafetyAction, !isStartingAction, !isResummoningAction,
|
||||
viewModel.canSendCommand(command) else { return }
|
||||
cancelScheduledPoll()
|
||||
requestGeneration &+= 1
|
||||
cancelPendingReadForAction()
|
||||
let generation = requestGeneration
|
||||
isSendingSafetyAction = true
|
||||
applySnapshot()
|
||||
|
||||
@@ -23,7 +23,8 @@ final class DroneDockTaskLiveView: UIView {
|
||||
private var isPlaybackActive = false
|
||||
private let rtcView = UIView()
|
||||
private let rtcPlayer: any DroneDockLivePlaying
|
||||
private var requestedRTC: DroneDockVolcLiveConfiguration?
|
||||
private var requestedRTC: [DroneDockVolcLiveConfiguration] = []
|
||||
private var activeRTC: [DroneDockVolcLiveConfiguration] = []
|
||||
private var requestedSessionID: UUID?
|
||||
private var activeSessionID: UUID?
|
||||
|
||||
@@ -69,7 +70,7 @@ final class DroneDockTaskLiveView: UIView {
|
||||
requestButton.isHidden = model.actionTitle == nil
|
||||
requestButton.isEnabled = model.canLoad
|
||||
requestedURL = model.playbackURL.flatMap { $0.isFileURL ? $0 : nil }
|
||||
requestedRTC = model.rtcConfiguration
|
||||
requestedRTC = model.rtcConfigurations
|
||||
requestedSessionID = model.playbackSessionID
|
||||
let hasLocalPreview = requestedURL != nil
|
||||
let isPlaying = model.state == .playing
|
||||
@@ -147,12 +148,13 @@ final class DroneDockTaskLiveView: UIView {
|
||||
releaseRTC()
|
||||
return
|
||||
}
|
||||
if let config = requestedRTC, let sessionID = requestedSessionID {
|
||||
if !requestedRTC.isEmpty, let sessionID = requestedSessionID {
|
||||
releasePlayer()
|
||||
guard activeSessionID != sessionID else { return }
|
||||
releaseRTC()
|
||||
guard activeSessionID != sessionID || activeRTC != requestedRTC else { return }
|
||||
if activeSessionID != sessionID { releaseRTC() }
|
||||
activeSessionID = sessionID
|
||||
rtcPlayer.start(config, in: rtcView) { [weak self] event in
|
||||
activeRTC = requestedRTC
|
||||
rtcPlayer.start(requestedRTC, in: rtcView) { [weak self] event in
|
||||
guard let self, self.activeSessionID == sessionID else { return }
|
||||
self.onPlaybackEvent?(event, sessionID)
|
||||
}
|
||||
@@ -177,6 +179,7 @@ final class DroneDockTaskLiveView: UIView {
|
||||
private func releaseRTC() {
|
||||
guard activeSessionID != nil else { return }
|
||||
activeSessionID = nil
|
||||
activeRTC = []
|
||||
rtcPlayer.stop()
|
||||
}
|
||||
|
||||
|
||||
@@ -246,6 +246,7 @@ 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 .paused: ("pause.circle.fill", DroneDockStyle.warning)
|
||||
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
|
||||
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
|
||||
|
||||
@@ -1,55 +1,130 @@
|
||||
import UIKit
|
||||
@preconcurrency import VolcEngineRTC
|
||||
|
||||
/// 可替换的图传播放器;测试注入内存替身,不初始化 RTC 或连接设备。
|
||||
/// 可替换的双路图传播放器;测试注入内存替身,不初始化 RTC 或连接设备。
|
||||
@MainActor
|
||||
protocol DroneDockLivePlaying: AnyObject {
|
||||
func start(_ configuration: DroneDockVolcLiveConfiguration, in view: UIView,
|
||||
/// 同一播放会话可增补或更新凭证,不重建未变化的房间。
|
||||
func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView,
|
||||
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void)
|
||||
/// 只关闭本机订阅,不向设备发送停止推流指令。
|
||||
func stop()
|
||||
}
|
||||
|
||||
/// 火山 RTC 视频接收端:不采集、不发布、不订阅音频,也不发送设备控制消息。
|
||||
/// 一个 RTC 引擎接收两个房间,机巢先接入,无人机有帧后覆盖,停流后恢复机巢。
|
||||
@MainActor
|
||||
final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
|
||||
private var engine: ByteRTCEngine?
|
||||
private var room: ByteRTCRoom?
|
||||
private var delegate: DroneDockVolcDelegate?
|
||||
private weak var renderView: UIView?
|
||||
private var onEvent: (@MainActor (DroneDockLivePlaybackEvent) -> Void)?
|
||||
private var streamID: String?
|
||||
private weak var container: UIView?
|
||||
private var sources: [String: DroneDockVolcSource] = [:]
|
||||
private var configurations: [DroneDockVolcLiveConfiguration] = []
|
||||
private var selection = DroneDockLiveSourceSelection()
|
||||
private var displayedRole: String?
|
||||
private var allowsDroneConnection = false
|
||||
private var failedRoles: Set<String> = []
|
||||
private var generation = UUID()
|
||||
private var timeoutTask: Task<Void, Never>?
|
||||
private var expiryTask: Task<Void, Never>?
|
||||
private var onEvent: (@MainActor (DroneDockLivePlaybackEvent) -> Void)?
|
||||
|
||||
/// 加入凭证指定的房间,等待已发布的主视频流;不调用业务 live 接口。
|
||||
func start(_ configuration: DroneDockVolcLiveConfiguration, in view: UIView,
|
||||
/// 加入只收视频的房间;同一来源只更新 Token,避免后台重查导致画面闪断。
|
||||
func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView,
|
||||
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) {
|
||||
stop()
|
||||
guard !DeviceCommandDebugPolicy.blocksLiveRequests else {
|
||||
onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return
|
||||
stop(); onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return
|
||||
}
|
||||
guard configuration.expiresAt.timeIntervalSinceNow > 5 else { onEvent(.expired); return }
|
||||
guard let first = configurations.first else { stop(); return }
|
||||
if container !== view || self.configurations.first?.appID != first.appID { stop() }
|
||||
self.onEvent = onEvent
|
||||
renderView = view
|
||||
let generation = generation
|
||||
let delegate = DroneDockVolcDelegate { [weak self] event in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.generation == generation else { return }
|
||||
self.receive(event, roomID: configuration.roomID)
|
||||
self.container = view
|
||||
self.configurations = configurations
|
||||
if engine == nil {
|
||||
let generation = generation
|
||||
let delegate = DroneDockVolcDelegate { [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 {
|
||||
stop(); onEvent(.failed("图传播放器初始化失败")); return
|
||||
}
|
||||
self.engine = engine
|
||||
}
|
||||
for role in Array(sources.keys) {
|
||||
guard let source = sources[role] else { continue }
|
||||
let replacement = configurations.first { $0.role == role }
|
||||
if replacement?.roomID != source.configuration.roomID || replacement?.userID != source.configuration.userID {
|
||||
removeSource(role)
|
||||
}
|
||||
}
|
||||
self.delegate = delegate
|
||||
let config = ByteRTCEngineConfig()
|
||||
config.appID = configuration.appID
|
||||
guard let engine = ByteRTCEngine.createRTCEngine(config, delegate: delegate) else {
|
||||
onEvent(.failed("图传播放器初始化失败")); stop(); return
|
||||
if let airport = configurations.first(where: { $0.role == "airport" }) { connect(airport) }
|
||||
else { allowsDroneConnection = true }
|
||||
connectDroneIfAllowed()
|
||||
if sources.isEmpty {
|
||||
stop(); onEvent(.failed("无法加入图传房间,请重试")); return
|
||||
}
|
||||
self.engine = engine
|
||||
guard let room = engine.createRTCRoom(configuration.roomID) else {
|
||||
onEvent(.failed("无法创建图传接收会话")); stop(); return
|
||||
displaySelectedSource()
|
||||
}
|
||||
|
||||
/// 离页释放两路订阅及同一个引擎,迟到回调由会话及房间身份拦截。
|
||||
func stop() {
|
||||
generation = UUID()
|
||||
onEvent = nil
|
||||
for role in Array(sources.keys) { removeSource(role) }
|
||||
engine?.delegate = nil
|
||||
if engine != nil { ByteRTCEngine.destroyRTCEngine() }
|
||||
engine = nil
|
||||
delegate = nil
|
||||
container = nil
|
||||
configurations = []
|
||||
selection = DroneDockLiveSourceSelection()
|
||||
displayedRole = nil
|
||||
allowsDroneConnection = false
|
||||
failedRoles = []
|
||||
}
|
||||
|
||||
private func connect(_ configuration: DroneDockVolcLiveConfiguration) {
|
||||
let role = configuration.role
|
||||
guard configuration.expiresAt.timeIntervalSinceNow > 5 else {
|
||||
removeSource(role)
|
||||
failedRoles.insert(role)
|
||||
if role == "airport" { allowsDroneConnection = true }
|
||||
return
|
||||
}
|
||||
self.room = room
|
||||
if let source = sources[role] {
|
||||
guard source.configuration != configuration else { return }
|
||||
guard source.room.updateToken(configuration.token) == 0 else {
|
||||
removeSource(role)
|
||||
connect(configuration)
|
||||
return
|
||||
}
|
||||
source.configuration = configuration
|
||||
scheduleExpiry(source)
|
||||
return
|
||||
}
|
||||
guard let container, let room = engine?.createRTCRoom(configuration.roomID) else {
|
||||
failedRoles.insert(role)
|
||||
if role == "airport" { allowsDroneConnection = true }
|
||||
return
|
||||
}
|
||||
let view = UIView(frame: container.bounds)
|
||||
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
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)
|
||||
sources[role] = source
|
||||
room.setRTCRoomDelegate(delegate)
|
||||
let roomConfig = ByteRTCRoomConfig()
|
||||
roomConfig.isPublishAudio = false
|
||||
@@ -58,122 +133,186 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying {
|
||||
roomConfig.isAutoSubscribeVideo = false
|
||||
let user = ByteRTCUserInfo()
|
||||
user.userId = configuration.userID
|
||||
DroneDockDiagnostics.event("rtc.join_requested", fields: ["engine_session": generation.uuidString])
|
||||
let result = room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: roomConfig)
|
||||
DroneDockDiagnostics.event("rtc.join_returned", fields: ["engine_session": generation.uuidString, "code": result])
|
||||
guard result == 0 else {
|
||||
onEvent(.failed("图传进房失败(\(result))")); stop(); return
|
||||
removeSource(role)
|
||||
failedRoles.insert(role)
|
||||
if role == "airport" { allowsDroneConnection = true }
|
||||
return
|
||||
}
|
||||
timeoutTask = Task { @MainActor [weak self] in
|
||||
// 机巢无首帧时不能无限等待,仍尝试无人机;已连房间继续等待发布事件。
|
||||
source.timeoutTask = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(for: .seconds(20))
|
||||
guard !Task.isCancelled, let self, self.generation == generation else { return }
|
||||
self.onEvent?(.failed("暂未收到图传画面,请重试"))
|
||||
guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
|
||||
self.sourceFailed(role)
|
||||
}
|
||||
expiryTask = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(for: .seconds(max(1, configuration.expiresAt.timeIntervalSinceNow - 5)))
|
||||
guard !Task.isCancelled, let self, self.generation == generation else { return }
|
||||
self.onEvent?(.expired)
|
||||
scheduleExpiry(source)
|
||||
}
|
||||
|
||||
private func connectDroneIfAllowed() {
|
||||
guard allowsDroneConnection, let drone = configurations.first(where: { $0.role == "drone" }) else { return }
|
||||
connect(drone)
|
||||
}
|
||||
|
||||
private func scheduleExpiry(_ source: DroneDockVolcSource) {
|
||||
source.expiryTask?.cancel()
|
||||
let role = source.configuration.role, sourceID = source.id, generation = generation
|
||||
let delay = max(1, source.configuration.expiresAt.timeIntervalSinceNow)
|
||||
source.expiryTask = Task { @MainActor [weak self] in
|
||||
try? await Task.sleep(for: .seconds(delay))
|
||||
guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return }
|
||||
self.removeSource(role)
|
||||
self.displaySelectedSource()
|
||||
}
|
||||
}
|
||||
|
||||
/// 销毁房间会退出订阅;只结束本机 RTC 连接,不调用设备停止推流接口。
|
||||
func stop() {
|
||||
generation = UUID()
|
||||
timeoutTask?.cancel(); timeoutTask = nil
|
||||
expiryTask?.cancel(); expiryTask = nil
|
||||
onEvent = nil
|
||||
if let streamID { engine?.setRemoteVideoCanvas(streamID, withCanvas: nil) }
|
||||
room?.setRTCRoomDelegate(nil)
|
||||
room?.destroy()
|
||||
room = nil
|
||||
engine?.delegate = nil
|
||||
if engine != nil { ByteRTCEngine.destroyRTCEngine() }
|
||||
engine = nil
|
||||
delegate = nil
|
||||
streamID = nil
|
||||
renderView = nil
|
||||
private func removeSource(_ role: String) {
|
||||
selection.setReady(false, role: role)
|
||||
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)
|
||||
source.room.destroy()
|
||||
source.view.removeFromSuperview()
|
||||
}
|
||||
|
||||
private func receive(_ event: DroneDockVolcEvent, roomID: String) {
|
||||
// 不把 SDK 回调对象、房间 ID、用户 ID 或 extraInfo 原样写入日志。
|
||||
DroneDockDiagnostics.event("rtc.callback", fields: ["engine_session": generation.uuidString, "result": event.diagnosticValue])
|
||||
private func receive(_ event: DroneDockVolcEvent) {
|
||||
switch event {
|
||||
case .published(let id, let sourceRoom, let index, let published):
|
||||
guard sourceRoom == roomID, index == 0 else { return }
|
||||
case .published(let id, let roomID, let index, let published):
|
||||
guard index == 0, let source = source(in: roomID) else { return }
|
||||
if !published {
|
||||
if streamID == id { onEvent?(.failed("图传已停止,请重新连接")) }
|
||||
guard source.streamID == id else { return }
|
||||
engine?.setRemoteVideoCanvas(id, withCanvas: nil)
|
||||
source.room.subscribeStreamVideo(id, subscribe: false)
|
||||
source.streamID = nil
|
||||
markReady(false, source: source)
|
||||
return
|
||||
}
|
||||
guard streamID == nil, let renderView else { return }
|
||||
streamID = id
|
||||
guard source.streamID == nil else { return }
|
||||
source.streamID = id
|
||||
let canvas = ByteRTCVideoCanvas()
|
||||
canvas.view = renderView
|
||||
canvas.view = source.view
|
||||
canvas.renderMode = .fit
|
||||
let renderResult = engine?.setRemoteVideoCanvas(id, withCanvas: canvas)
|
||||
let subscribeResult = room?.subscribeStreamVideo(id, subscribe: true)
|
||||
DroneDockDiagnostics.event("rtc.subscribe_returned", fields: ["engine_session": generation.uuidString,
|
||||
"render_code": renderResult as Any? ?? NSNull(), "subscribe_code": subscribeResult as Any? ?? NSNull()])
|
||||
if renderResult != 0 || subscribeResult != 0 { onEvent?(.failed("图传订阅失败,请重试")) }
|
||||
case .frame(let id):
|
||||
guard streamID == id else { return }
|
||||
timeoutTask?.cancel(); timeoutTask = nil
|
||||
onEvent?(.firstFrame)
|
||||
case .failed(let code): onEvent?(.failed("图传连接失败(\(code)),请重试"))
|
||||
case .expired: onEvent?(.expired)
|
||||
case .roomState: break
|
||||
let render = engine?.setRemoteVideoCanvas(id, withCanvas: canvas)
|
||||
let subscribe = source.room.subscribeStreamVideo(id, subscribe: true)
|
||||
if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role) }
|
||||
case .frame(let id, let roomID):
|
||||
guard let source = source(in: roomID), source.streamID == id else { return }
|
||||
markReady(true, source: source)
|
||||
case .videoState(let id, let roomID, let state):
|
||||
guard let source = source(in: roomID), source.streamID == id else { return }
|
||||
switch state {
|
||||
case .decoding: markReady(true, source: source)
|
||||
case .stopped, .frozen, .failed: markReady(false, source: source)
|
||||
default: break
|
||||
}
|
||||
case .roomFailed(let roomID):
|
||||
guard let source = source(in: roomID) else { return }
|
||||
sourceFailed(source.configuration.role)
|
||||
case .connectionLost:
|
||||
for source in sources.values { selection.setReady(false, role: source.configuration.role) }
|
||||
displaySelectedSource()
|
||||
case .failed(let code):
|
||||
let callback = onEvent
|
||||
stop()
|
||||
callback?(.failed("图传连接失败(\(code)),请重试"))
|
||||
}
|
||||
}
|
||||
|
||||
private func source(in roomID: String) -> DroneDockVolcSource? {
|
||||
sources.values.first { $0.configuration.roomID == roomID }
|
||||
}
|
||||
|
||||
private func markReady(_ ready: Bool, source: DroneDockVolcSource) {
|
||||
selection.setReady(ready, role: source.configuration.role)
|
||||
if ready {
|
||||
failedRoles.remove(source.configuration.role)
|
||||
source.timeoutTask?.cancel(); source.timeoutTask = nil
|
||||
}
|
||||
displaySelectedSource()
|
||||
if source.configuration.role == "airport" {
|
||||
allowsDroneConnection = true
|
||||
connectDroneIfAllowed()
|
||||
}
|
||||
}
|
||||
|
||||
private func sourceFailed(_ role: String) {
|
||||
failedRoles.insert(role)
|
||||
selection.setReady(false, role: role)
|
||||
if role == "airport" { allowsDroneConnection = true; connectDroneIfAllowed() }
|
||||
displaySelectedSource()
|
||||
if selection.selectedRole == nil, Set(configurations.map(\.role)).isSubset(of: failedRoles) {
|
||||
let callback = onEvent
|
||||
stop()
|
||||
callback?(.failed("暂未收到可用的图传画面,请重试"))
|
||||
}
|
||||
}
|
||||
|
||||
private func displaySelectedSource() {
|
||||
let role = selection.selectedRole
|
||||
for source in sources.values { source.view.isHidden = source.configuration.role != role }
|
||||
if let role, let view = sources[role]?.view { container?.bringSubviewToFront(view) }
|
||||
guard displayedRole != role else { return }
|
||||
displayedRole = role
|
||||
onEvent?(.sourceChanged(role))
|
||||
}
|
||||
}
|
||||
|
||||
/// 将 SDK 工作线程的回调转换为可发送的值,不跨线程传递 UIKit 或 SDK 对象。
|
||||
/// 每路独立持有房间、画布及超时;引擎由外层统一管理,避免销毁另一条流。
|
||||
@MainActor
|
||||
private final class DroneDockVolcSource {
|
||||
let id: UUID
|
||||
var configuration: DroneDockVolcLiveConfiguration
|
||||
let room: ByteRTCRoom
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// SDK 工作线程只转交值类型事件;事件带房间和流身份以隔离两路回调。
|
||||
private enum DroneDockVolcEvent: Sendable {
|
||||
case published(String, String, Int, Bool)
|
||||
case frame(String)
|
||||
case frame(String, String)
|
||||
case videoState(String, String, ByteRTCRemoteVideoState)
|
||||
case roomFailed(String)
|
||||
case connectionLost
|
||||
case failed(Int)
|
||||
case expired
|
||||
case roomState(Int)
|
||||
|
||||
/// 仅输出事件种类及错误码,不含 SDK 身份和凭证。
|
||||
var diagnosticValue: String {
|
||||
switch self {
|
||||
case .published(_, _, let index, let published): return "published(index=\(index),published=\(published))"
|
||||
case .frame: return "first_frame"
|
||||
case .failed(let code): return "failed(code=\(code))"
|
||||
case .expired: return "expired"
|
||||
case .roomState(let code): return "room_state(code=\(code))"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SDK 回调桥接;所有 UI 与引擎操作由上层切回主 Actor 后执行。
|
||||
/// SDK 回调桥接,不采集音视频,不处理设备控制消息。
|
||||
private 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) {
|
||||
func rtcRoom(_ rtcRoom: ByteRTCRoom, onUserPublishStreamVideo streamId: String, info: ByteRTCStreamInfo, isPublish: Bool) {
|
||||
emit(.published(streamId, info.roomId, info.streamIndex, isPublish))
|
||||
}
|
||||
|
||||
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String,
|
||||
state: Int, extraInfo: String) {
|
||||
emit(.roomState(state))
|
||||
if state != 0 { emit(.failed(state)) }
|
||||
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String, state: Int, extraInfo: String) {
|
||||
if state != 0 { emit(.roomFailed(roomId)) }
|
||||
}
|
||||
|
||||
func rtcEngine(_ engine: ByteRTCEngine, onFirstRemoteVideoFrameRendered streamId: String,
|
||||
func rtcEngine(_ engine: ByteRTCEngine, onFirstRemoteVideoFrameDecoded streamId: String,
|
||||
info: ByteRTCStreamInfo, withFrameInfo frameInfo: ByteRTCVideoFrameInfo) {
|
||||
emit(.frame(streamId))
|
||||
// 未展示的画布也能解码,不能依赖被隐藏视图的 rendered 回调判断首帧。
|
||||
emit(.frame(streamId, info.roomId))
|
||||
}
|
||||
|
||||
func rtcEngine(_ engine: ByteRTCEngine, onError errorCode: ByteRTCErrorCode) {
|
||||
emit(.failed(errorCode.rawValue))
|
||||
func rtcEngine(_ engine: ByteRTCEngine, onRemoteVideoStateChanged streamId: String, info: ByteRTCStreamInfo,
|
||||
withVideoState state: ByteRTCRemoteVideoState, withVideoStateReason reason: ByteRTCRemoteVideoStateChangeReason) {
|
||||
emit(.videoState(streamId, info.roomId, state))
|
||||
}
|
||||
|
||||
func rtcEngine(_ engine: ByteRTCEngine, onError errorCode: ByteRTCErrorCode) { emit(.failed(errorCode.rawValue)) }
|
||||
func rtcEngine(_ engine: ByteRTCEngine, onConnectionStateChanged state: ByteRTCConnectionState) {
|
||||
if state == .reconnecting || state == .failed { emit(.failed(state.rawValue)) }
|
||||
if state == .reconnecting { emit(.connectionLost) }
|
||||
if state == .failed { emit(.failed(state.rawValue)) }
|
||||
}
|
||||
|
||||
func onTokenWillExpire(_ rtcRoom: ByteRTCRoom) { emit(.expired) }
|
||||
func onSubscribePrivilegeTokenWillExpire(_ rtcRoom: ByteRTCRoom) { emit(.expired) }
|
||||
}
|
||||
|
||||
@@ -312,13 +312,13 @@ final class DroneShootingOrderCardView: UIView {
|
||||
}
|
||||
|
||||
private func applyRemoteActions(order: DroneDockHomeOrder, identifier: String) {
|
||||
let canShoot = order.canCreateTask == true
|
||||
let canShoot = order.activeTaskID != nil || order.canCreateTask == true
|
||||
let canConfirm = order.canInviteVisitorConfirmation
|
||||
let canDeliver = order.canUploadFilm == true
|
||||
primaryButton.isHidden = !canShoot && !canConfirm && !canDeliver
|
||||
primaryButton.isEnabled = !primaryButton.isHidden
|
||||
primaryButton.backgroundColor = DroneDockStyle.primary
|
||||
primaryButton.setTitle(canShoot ? "开始拍摄" : canConfirm ? "邀请确认" : "交付成片", for: .normal)
|
||||
primaryButton.setTitle(canShoot ? order.actionTitle : canConfirm ? "邀请确认" : "交付成片", for: .normal)
|
||||
primaryButton.accessibilityIdentifier = identifier + ".primary"
|
||||
secondaryButton.isHidden = !canDeliver || (!canShoot && !canConfirm)
|
||||
secondaryButton.isEnabled = !secondaryButton.isHidden
|
||||
@@ -413,7 +413,7 @@ final class DroneShootingOrderCardView: UIView {
|
||||
@objc private func primaryTapped() {
|
||||
if let order = displayedHomeOrder {
|
||||
guard !primaryButton.isHidden, primaryButton.isEnabled else { return }
|
||||
if order.canCreateTask == true { onShootingTap?() }
|
||||
if order.activeTaskID != nil || order.canCreateTask == true { onShootingTap?() }
|
||||
else if order.canInviteVisitorConfirmation { onConfirmationTap?() }
|
||||
else if order.canUploadFilm == true { onDeliveryTap?() }
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user