feat: 完善机巢任务实时状态、双路图传与继续查看入口
This commit is contained in:
@@ -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