feat(drone-dock): 接入火山实时图传并保留禁飞保护

This commit is contained in:
2026-11-02 11:01:02 +08:00
parent c1fd2d0859
commit b21a3b6cb6
204 changed files with 112972 additions and 3274 deletions
@@ -1,7 +1,9 @@
import Foundation
/// 禁飞期间的 Debug 请求边界;模拟器和测试环境均不能视为没有真实设备副作用。
/// 禁飞期间的请求边界;正式包仅允许用户手动图传,不允许创建或飞控。
enum DeviceCommandDebugPolicy {
/// 飞控与真实待飞任务在所有构建中关闭,不因打 Release 包而解除禁飞。
static let blocksFlightRequests = true
/// 所有 Debug 构建禁止真实设备操作,没有启动参数或设置开关可临时放行。
static var blocksLiveRequests: Bool {
#if DEBUG
@@ -16,13 +18,15 @@ enum DeviceCommandDebugPolicy {
/// 在日志和传输之前阻断操作请求;允许的状态读取关闭实时设备采集。
static func prepare(_ request: URLRequest, isLocalSimulation: Bool) throws -> URLRequest {
guard blocksLiveRequests, !isLocalSimulation, let url = request.url else { return request }
guard !isLocalSimulation, let url = request.url else { return request }
let path = "/" + url.path.split(separator: "/").joined(separator: "/")
// 创建虽不直接起飞,但会改变真实订单状态;禁飞调试使用本地待飞任务。
if path == "/api/yf-handset-app/photog/multi-plane/tasks/create" {
throw DeviceCommandDebugBlockedError()
}
guard path == "/api/app/airport" || path.hasPrefix("/api/app/airport/") else { return request }
// 2026-11-02 仅为用户后续手动图传测试提供 Release 入口;Debug 仍禁止开流。
if request.httpMethod == "GET", path == "/api/app/airport/live", !blocksLiveRequests { return request }
let readablePaths: Set<String> = [
"/api/app/airport/home", "/api/app/airport/plane-status",
"/api/app/airport/shooting", "/api/app/airport/status"
@@ -21,7 +21,8 @@ final class DroneDockLiveAPI: DroneDockLiveServing {
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID") }
let value: DroneDockLiveResponse = try await client.send(APIRequest(
method: .get, path: "/api/app/airport/live",
queryItems: [URLQueryItem(name: "id", value: String(taskID))]
queryItems: [URLQueryItem(name: "id", value: String(taskID))],
logsPayload: false
))
guard value.orderFlightTaskID == taskID, value.task?.id == nil || value.task?.id == taskID else {
throw APIError.decodeFailed("图传回执与当前拍摄任务不一致")
@@ -0,0 +1,84 @@
import Foundation
/// 经验证的火山接收端配置;只在内存传递,禁止写入日志或持久化。
struct DroneDockVolcLiveConfiguration: Equatable, Sendable, CustomDebugStringConvertible {
let appID: String
let roomID: String
let userID: String
let token: String
let expiresAt: Date
let role: String
/// 调试器描述中不暴露连接凭证。
var debugDescription: String { "DroneDockVolcLiveConfiguration(<redacted>)" }
/// 按 2026-11-02 已确认的 volc querystring 解析;不猜测其它厂商的字段。
static func parse(_ response: DroneDockLiveResponse, now: Date) throws -> Self {
guard response.playable == true else {
throw DroneDockLiveConnectionError(response.unavailableMessage.flatMap(DroneDockHomeMetric.usableText)
?? "图传暂不可用")
}
guard let stream = response.play, stream.available == true else {
throw DroneDockLiveConnectionError("图传尚未提供可用的视频流")
}
guard stream.urlType == "volc" else {
throw DroneDockLiveConnectionError("暂不支持当前图传类型,请联系后台确认使用火山图传")
}
guard let role = stream.role, ["drone", "airport"].contains(role),
(response.planeID ?? 0) > 0,
DroneDockHomeMetric.usableText(response.airportSN) != nil else {
throw DroneDockLiveConnectionError("图传设备信息不完整")
}
guard let query = stream.url, !query.isEmpty, query.utf8.count <= 32_768 else {
throw DroneDockLiveConnectionError("图传连接参数不完整")
}
var fields: [String: String] = [:]
// Token 中的 + 保留为 +;百分号只解码一次,避免把 %252B 错解为 +。
for item in query.split(separator: "&", omittingEmptySubsequences: false) {
let pair = item.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
guard pair.count == 2, let name = String(pair[0]).removingPercentEncoding,
let value = String(pair[1]).removingPercentEncoding,
!name.isEmpty, fields[name] == nil else {
throw DroneDockLiveConnectionError("图传连接参数格式错误")
}
fields[name] = value
}
func required(_ key: String) throws -> String {
guard let value = fields[key], !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
value.rangeOfCharacter(from: .controlCharacters) == nil else {
throw DroneDockLiveConnectionError("图传缺少必要连接参数")
}
return value
}
guard let expiry = stream.expiresAt, expiry > 0 else {
throw DroneDockLiveConnectionError("图传缺少凭证有效期")
}
var effectiveExpiry = expiry
if let value = fields["expire_time"] {
guard let parsed = Int(value), parsed > 0 else {
throw DroneDockLiveConnectionError("图传凭证有效期格式错误")
}
effectiveExpiry = min(expiry, parsed)
}
let expiresAt = Date(timeIntervalSince1970: TimeInterval(effectiveExpiry))
guard expiresAt.timeIntervalSince(now) > 5 else {
throw DroneDockLiveConnectionError("图传凭证已过期,请重新获取")
}
return try Self(appID: required("app_id"), roomID: required("room_id"),
userID: required("user_id"), token: required("token"), expiresAt: expiresAt, role: role)
}
}
/// 对用户只显示不含连接串的校验原因。
struct DroneDockLiveConnectionError: Error, LocalizedError, Equatable, Sendable {
let message: String
init(_ message: String) { self.message = message }
var errorDescription: String? { message }
}
/// 播放器明确回调;只有首帧到达才算已显示真实画面。
enum DroneDockLivePlaybackEvent: Equatable, Sendable {
case firstFrame
case failed(String)
case expired
}
@@ -1,6 +1,6 @@
import Foundation
/// live 文档已明确的任务与设备回执;当前合同没有可用于播放的字段。
/// 朱工 live 回执;任务身份与播放参数分别验证,凭证不进入展示 JSON。
struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
/// 后端回显的订单飞行任务 ID,不能用请求值补齐。
let orderFlightTaskID: Int
@@ -12,15 +12,20 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
let task: DroneDockShootingTaskIdentity?
/// 已锁定机场序列号,不用于客户端选择或重新绑定设备。
let airportSN: String?
let planeID: Int?
let playable: Bool?
let unavailableMessage: String?
let play: DroneDockLiveStream?
/// 随接口返回的展示读数,不触发额外实时采集。
let metrics: [DroneDockHomeMetric]
/// 完整回执,包含尚未建模字段,不解释成播放器配置。
/// 脱敏回执,不包含 RTC 连接串或 Token。
let dataJSON: String
/// live 文档中的已知字段映射。
private enum CodingKeys: String, CodingKey {
case orderFlightTaskID = "order_flight_task_id", airport, drone, task
case airportSN = "airport_sn", metrics
case planeID = "plane_id", playable, play, unavailableMessage = "unavailable_message"
}
/// 任务 ID 必须明确提供;未知字段及 null 留在完整 JSON 中供后续合同核对。
@@ -31,6 +36,10 @@ struct DroneDockLiveResponse: Decodable, Equatable, Sendable {
drone = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .drone)
task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task)
airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN)
planeID = try container.decodeIfPresent(Int.self, forKey: .planeID)
playable = try container.decodeIfPresent(Bool.self, forKey: .playable)
unavailableMessage = try container.decodeIfPresent(String.self, forKey: .unavailableMessage)
play = try container.decodeIfPresent(DroneDockLiveStream.self, forKey: .play)
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
let raw = try DroneDockHomeJSONValue(from: decoder)
let encoder = JSONEncoder()
@@ -47,7 +56,10 @@ private struct DroneDockLiveJSONSnapshot: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case .object(let value): try container.encode(value.mapValues { Self(value: $0) })
case .object(let value):
try container.encode(value.mapValuesWithKeys { key, value in
Self(value: ["url", "token"].contains(key.lowercased()) ? .string("<redacted>") : value)
})
case .array(let value): try container.encode(value.map { Self(value: $0) })
case .string(let value): try container.encode(value)
case .number(let value): try container.encode(value)
@@ -65,4 +77,29 @@ enum DroneDockLiveState: Equatable, Sendable {
case unavailable(String)
case failed(String)
case localPreview(URL)
case connecting
case playing
}
/// live 的首选流,按 url_type 选择已明确支持的播放器。
struct DroneDockLiveStream: Decodable, Equatable, Sendable {
let available: Bool?
let role: String?
let deviceSN: String?
let urlType: String?
let url: String?
let expiresAt: Int?
/// 后端播放字段映射。
private enum CodingKeys: String, CodingKey {
case available, role, url
case deviceSN = "device_sn", urlType = "url_type", expiresAt = "expire_ts"
}
}
/// 只用于递归脱敏 JSON,避免字典转换时丢失字段名。
private extension Dictionary where Key == String {
func mapValuesWithKeys<T>(_ transform: (String, Value) throws -> T) rethrows -> [String: T] {
try Dictionary<String, T>(uniqueKeysWithValues: map { (key, value) in (key, try transform(key, value)) })
}
}
@@ -1,32 +1,42 @@
import Foundation
/// 任务图传区域的单次请求与生命周期;正式入口不注入操作服务,模拟来源单独注入。
/// 任务图传的单次请求与生命周期;正式图传手动开启,模拟来源单独注入。
final class DroneDockLiveViewModel {
/// 当前图传所属的账号、景区与门店范围。
let context: DroneDockHomeContext
/// 固定订单飞行任务身份。
let taskID: Int
/// 最近一次通过身份核对的图传回执,不用作实时播放配置。
/// 最近一次通过身份核对的回执;播放配置还需通过独立的协议校验。
private(set) var response: DroneDockLiveResponse?
/// 图传区域当前可展示状态。
private(set) var state: DroneDockLiveState
/// 请求期间阻止重复获取,不安排定时轮询。
private(set) var isLoading = false
/// 仅显式正式入口允许解析设备 RTC;本地模拟即使收到参数也不连接设备。
let allowsDevicePlayback: Bool
/// 正式图传必须手动开启;演示入口可自动载入本地样片。
var loadsAutomatically: Bool { !allowsDevicePlayback }
private(set) var rtcConfiguration: DroneDockVolcLiveConfiguration?
private(set) var playbackSessionID: UUID?
private let service: (any DroneDockLiveServing)?
private let localPreviewURL: URL?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
private var identityInvalidated = false
private let now: @Sendable () -> Date
/// 本地素材仅供明确的模拟入口注入,后端 JSON 不能生成此 URL。
init(context: DroneDockHomeContext, taskID: Int, service: (any DroneDockLiveServing)? = nil,
localPreviewURL: URL? = nil,
localPreviewURL: URL? = nil, allowsDevicePlayback: Bool = false,
now: @escaping @Sendable () -> Date = { Date() },
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.taskID = taskID
self.service = service
self.localPreviewURL = localPreviewURL
self.allowsDevicePlayback = allowsDevicePlayback
self.now = now
self.currentContext = currentContext
state = service == nil ? .restricted : .idle
}
@@ -49,6 +59,8 @@ final class DroneDockLiveViewModel {
case .unavailable: return "图传暂不可用"
case .failed: return "图传加载失败"
case .localPreview: return "本地模拟画面"
case .connecting: return "正在连接图传"
case .playing: return "实时图传"
}
}
@@ -56,10 +68,12 @@ final class DroneDockLiveViewModel {
var message: String {
switch state {
case .restricted: return "禁飞调试期间不启动设备图传"
case .idle: return "按当前任务获取图传信息"
case .idle: return allowsDevicePlayback ? "点击开启当前任务的实时图传" : "按当前任务获取图传信息"
case .loading: return "请稍候"
case .unavailable(let reason), .failed(let reason): return reason
case .localPreview: return "仅播放本地样片,未连接无人机"
case .connecting: return "正在等待视频画面"
case .playing: return rtcConfiguration?.role == "airport" ? "机巢摄像头" : "无人机摄像头"
}
}
@@ -69,10 +83,12 @@ final class DroneDockLiveViewModel {
if isLoading { return "正在加载…" }
switch state {
case .restricted: return nil
case .idle: return localPreviewURL == nil ? "获取图传信息" : "查看模拟图传"
case .idle: return allowsDevicePlayback ? "开启实时图传" : (localPreviewURL == nil ? "获取图传信息" : "查看模拟图传")
case .loading: return "正在加载…"
case .failed, .unavailable: return "重试"
case .localPreview: return "重新加载模拟图传"
case .connecting: return "重新连接"
case .playing: return "刷新图传"
}
}
@@ -84,7 +100,7 @@ final class DroneDockLiveViewModel {
let requestGeneration = generation
guard accepts(requestGeneration) else { return }
isLoading = true
if playbackURL == nil { state = .loading }
if playbackURL == nil && rtcConfiguration == nil { state = .loading }
onRequestStarted?()
defer {
if generation == requestGeneration {
@@ -100,6 +116,18 @@ final class DroneDockLiveViewModel {
throw APIError.decodeFailed("图传回执与当前拍摄任务不一致")
}
response = value
if allowsDevicePlayback {
rtcConfiguration = nil
playbackSessionID = nil
do {
rtcConfiguration = try DroneDockVolcLiveConfiguration.parse(value, now: now())
playbackSessionID = UUID()
state = .connecting
} catch {
state = .unavailable(error.localizedDescription)
}
return
}
guard let airportSN = DroneDockHomeMetric.usableText(value.airportSN), !airportSN.isEmpty else {
state = .unavailable("当前任务尚未返回已锁定的机场信息")
return
@@ -118,6 +146,8 @@ final class DroneDockLiveViewModel {
state = .idle
} catch {
guard accepts(requestGeneration) else { return }
rtcConfiguration = nil
playbackSessionID = nil
state = .failed(error.localizedDescription)
}
}
@@ -128,9 +158,34 @@ final class DroneDockLiveViewModel {
generation &+= 1
isLoading = false
response = nil
rtcConfiguration = nil
playbackSessionID = nil
state = service == nil ? .restricted : .idle
}
/// 只接受当前播放器会话的事件;首帧之前不显示已连接,旧回调不能恢复画面。
@MainActor
func receivePlaybackEvent(_ event: DroneDockLivePlaybackEvent, sessionID: UUID) {
guard sessionID == playbackSessionID, rtcConfiguration != nil else { return }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
invalidate()
identityInvalidated = true
state = .failed("账号或景区已变化,请返回工作台重新进入")
return
}
switch event {
case .firstFrame: state = .playing
case .failed(let message):
rtcConfiguration = nil
playbackSessionID = nil
state = .failed(message)
case .expired:
rtcConfiguration = nil
playbackSessionID = nil
state = .unavailable("图传凭证即将或已经过期,请重新获取")
}
}
/// 只接受当前页面与当前身份下的结果,身份变化后不允许重新请求旧任务。
@MainActor
private func accepts(_ requestGeneration: Int) -> Bool {
@@ -24,6 +24,18 @@ final class DroneDockMaterialsViewModel {
private(set) var tasksErrorMessage: String?
/// 点位标签始终来自整单购买快照,不从当前任务推导。
var spots: [DroneDockMaterialSpot] { detail?.spots ?? [] }
/// 已完整读取的任务可进入状态与图传页,不因素材尚未上传而隐藏。
var canViewRecordedTasks: Bool {
detail != nil && !isLoading && !isLoadingTasks && detailErrorMessage == nil
&& tasksErrorMessage == nil && !tasks.isEmpty
}
/// 打开任务前重新核对账号和景区,并且只允许当前已加载订单中的任务。
@MainActor
func taskForViewing(id: Int) -> DroneDockMaterialTask? {
guard acceptsSelectionContext(), canViewRecordedTasks else { return nil }
return tasks.first { $0.id == id && $0.orderNumber == order.orderNumber }
}
/// 当前范围内已选择的就绪原素材,不包含独立交付成片。
private(set) var selectedMaterialIDs: Set<DroneDockMaterialSelectionID> = []
/// 只有完整读取成功且具备有效文件地址的原素材允许选择。
@@ -107,7 +107,7 @@ final class DroneDockShootingTaskViewModel {
return
}
do {
let value = try await service.shooting(taskID: taskID, liveBattery: true)
let value = try await service.shooting(taskID: taskID, liveBattery: false)
guard accepts(requestGeneration) else { return }
guard matchesIdentity(value) else {
response = nil
@@ -312,7 +312,7 @@ final class DroneDockHomeViewController: BaseViewController {
planeStatusService: DroneDockPlaneStatusAPI(client: NetworkServices.shared.apiClient),
taskCreationService: DroneDockTaskCreationAPI(client: NetworkServices.shared.apiClient),
shootService: DroneDockShootAPI(client: NetworkServices.shared.apiClient),
allowsTaskSubmission: !DeviceCommandDebugPolicy.blocksLiveRequests,
allowsTaskSubmission: !DeviceCommandDebugPolicy.blocksFlightRequests,
currentContext: { Self.currentContext() }
))
}
@@ -16,6 +16,8 @@ final class DroneDockMaterialsViewController: BaseViewController {
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
private let downloadSourceDescription: String?
private let downloadIsSimulated: Bool
private let taskControllerFactory: (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private var taskButton: UIBarButtonItem?
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
private enum Section: Hashable { case order, filters, summary, task(Int), media(Int), message }
@@ -43,12 +45,16 @@ final class DroneDockMaterialsViewController: BaseViewController {
mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil,
downloadViewModel: DroneDockMaterialDownloadViewModel? = nil,
downloadSourceDescription: String? = nil,
downloadIsSimulated: Bool = false) {
downloadIsSimulated: Bool = false,
taskControllerFactory: ((Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
self.viewModel = viewModel
self.downloadViewModel = downloadViewModel ?? DroneDockMaterialDownloadViewModel(
isContextValid: { [weak viewModel] in viewModel?.acceptsDownloadContext() == true })
self.downloadSourceDescription = downloadSourceDescription
self.downloadIsSimulated = downloadIsSimulated
self.taskControllerFactory = taskControllerFactory ?? { id, order, context in
DroneDockShootingTaskEntry.makeController(taskID: id, order: order, context: context)
}
self.thumbnailProvider = thumbnailProvider
self.mediaPreviewControllerFactory = mediaPreviewControllerFactory
self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController
@@ -67,7 +73,11 @@ final class DroneDockMaterialsViewController: BaseViewController {
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped))
refresh.accessibilityLabel = "刷新素材状态"
refresh.accessibilityIdentifier = "drone.materials.remote.refresh"
navigationItem.rightBarButtonItem = refresh
let tasks = UIBarButtonItem(title: "查看任务", style: .plain, target: self, action: #selector(viewTasksTapped))
tasks.accessibilityIdentifier = "drone.materials.remote.viewTasks"
tasks.isEnabled = false
taskButton = tasks
navigationItem.rightBarButtonItems = [refresh, tasks]
}
override func setupUI() {
@@ -257,6 +267,7 @@ final class DroneDockMaterialsViewController: BaseViewController {
private func applySnapshot(animated: Bool) {
guard dataSource != nil else { return }
taskButton?.isEnabled = operation == nil && !selectionLocked && viewModel.canViewRecordedTasks
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
if viewModel.detail != nil {
snapshot.appendSections([.order, .filters])
@@ -364,6 +375,7 @@ final class DroneDockMaterialsViewController: BaseViewController {
private func updateDownloadFooter() {
navigationItem.rightBarButtonItem?.isEnabled = !selectionLocked
taskButton?.isEnabled = operation == nil && !selectionLocked && viewModel.canViewRecordedTasks
let model = downloadViewModel
let identifier = "drone.materials.remote.download"
switch model.phase {
@@ -389,6 +401,31 @@ final class DroneDockMaterialsViewController: BaseViewController {
}
}
/// 从张工已返回的任务中选择并进入状态页,不创建新任务或调用召唤接口。
@objc private func viewTasksTapped() {
guard operation == nil, !selectionLocked, viewModel.canViewRecordedTasks,
viewModel.acceptsDownloadContext(), presentedViewController == nil else { return }
if let task = viewModel.tasks.first, viewModel.tasks.count == 1 {
openRecordedTask(id: task.id)
return
}
let sheet = UIAlertController(title: "选择拍摄任务", message: nil, preferredStyle: .actionSheet)
for task in viewModel.tasks {
let spot = task.spotName.isEmpty ? "拍摄任务" : task.spotName
let sequence = task.sequence.map { "第\($0)次拍摄" } ?? "拍摄记录"
let title = "\(spot) · \(sequence)" + (task.createdAt.map { " · \($0)" } ?? "")
sheet.addAction(UIAlertAction(title: title, style: .default) { [weak self] _ in self?.openRecordedTask(id: task.id) })
}
sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
present(sheet, animated: true)
}
private func openRecordedTask(id: Int) {
guard operation == nil, !selectionLocked, viewModel.taskForViewing(id: id) != nil,
navigationController?.topViewController === self else { return }
navigationController?.pushViewController(taskControllerFactory(id, viewModel.order, viewModel.context), animated: true)
}
private func previewFile(taskID: Int, fileID: Int) {
guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return }
preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材")
@@ -3,13 +3,19 @@ import UIKit
/// 组装真实拍摄任务页;构造时不发请求,页面出现后才读取同一任务。
@MainActor
enum DroneDockShootingTaskEntry {
/// 使用当前共享网络服务读取已创建、已召唤任务,不创建或控制无人机。
/// 使用已有任务读取状态,Release 可手动图传;不注入任务创建或飞控服务。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
let client = NetworkServices.shared.apiClient
let live = DroneDockLiveViewModel(
context: context, taskID: taskID,
service: DeviceCommandDebugPolicy.blocksLiveRequests ? nil : DroneDockLiveAPI(client: client),
allowsDevicePlayback: !DeviceCommandDebugPolicy.blocksLiveRequests,
currentContext: { DroneDockHomeViewController.currentContext() })
return DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
context: context, taskID: taskID, order: order,
service: DroneDockShootingAPI(client: NetworkServices.shared.apiClient),
currentContext: { DroneDockHomeViewController.currentContext() }
))
), liveViewModel: live)
}
}
@@ -1,7 +1,7 @@
import SnapKit
import UIKit
/// 拍摄任务页:真实入口只读,本地模拟入口可验证图传、重召唤、开拍与安全指令合同。
/// 拍摄任务页:正式入口读取状态并手动开启图传,飞控仅在隔离模拟入口注入。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
@@ -173,6 +173,13 @@ final class DroneDockShootingTaskViewController: BaseViewController {
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()
}
}
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
@@ -185,7 +192,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
isPageVisible = true
isApplicationActive = UIApplication.shared.applicationState == .active
refreshTaskIfVisible()
refreshLiveIfVisible()
refreshLiveIfVisible(automatically: true)
}
/// 离页立即取消未完成的读取,使迟到响应失效。
@@ -352,8 +359,9 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
}
/// 图传只读取一次,不轮询;正式入口没有图传服务,不能向设备发出开流请求。
private func refreshLiveIfVisible() {
/// 图传请求不轮询;正式入口仅响应用户点击,本地样片允许随页面加载。
private func refreshLiveIfVisible(automatically: Bool = false) {
guard !automatically || liveViewModel.loadsAutomatically else { return }
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
liveGeneration &+= 1
let generation = liveGeneration
@@ -446,7 +454,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
guard !isApplicationActive else { return }
isApplicationActive = true
refreshTaskIfVisible()
refreshLiveIfVisible()
refreshLiveIfVisible(automatically: true)
}
}
@@ -2,11 +2,13 @@ import AVFoundation
import SnapKit
import UIKit
/// 固定图传区域:展示接口状态或明确标记的本地样片,不自行发请求或读取远程视频。
/// 固定图传区域:渲染已验证的 RTC 会话或明确标记的本地样片。
@MainActor
final class DroneDockTaskLiveView: UIView {
/// 用户主动获取或重试图传信息,具体请求由控制器协调。
var onRequest: (() -> Void)?
/// 播放事件附带会话 ID,控制器据此丢弃离页或重连后的旧回调。
var onPlaybackEvent: ((DroneDockLivePlaybackEvent, UUID) -> Void)?
private let playerLayer = AVPlayerLayer()
private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: .white)
@@ -19,14 +21,28 @@ final class DroneDockTaskLiveView: UIView {
private var requestedURL: URL?
private var activeURL: URL?
private var isPlaybackActive = false
private let rtcView = UIView()
private let rtcPlayer: any DroneDockLivePlaying
private var requestedRTC: DroneDockVolcLiveConfiguration?
private var requestedSessionID: UUID?
private var activeSessionID: UUID?
/// 保留原任务页图传区域的访问标识,外部负责 16:9 约束。
override init(frame: CGRect) {
rtcPlayer = DroneDockVolcLivePlayer()
super.init(frame: frame)
setupUI()
setupConstraints()
}
/// 测试注入无网络播放器,覆盖首帧、失败和会话释放。
init(rtcPlayer: any DroneDockLivePlaying) {
self.rtcPlayer = rtcPlayer
super.init(frame: .zero)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -39,6 +55,12 @@ final class DroneDockTaskLiveView: UIView {
CATransaction.commit()
}
/// 移出窗口也释放播放资源,覆盖交互返回和容器移除。
override func didMoveToWindow() {
super.didMoveToWindow()
if window == nil { setPlaybackActive(false) }
}
/// 在明确时机应用模型;远程 URL 即使错误传入也不会创建播放器。
func apply(_ model: DroneDockLiveViewModel) {
titleLabel.text = model.title
@@ -47,12 +69,15 @@ final class DroneDockTaskLiveView: UIView {
requestButton.isHidden = model.actionTitle == nil
requestButton.isEnabled = model.canLoad
requestedURL = model.playbackURL.flatMap { $0.isFileURL ? $0 : nil }
requestedRTC = model.rtcConfiguration
requestedSessionID = model.playbackSessionID
let hasLocalPreview = requestedURL != nil
sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : nil
sourceLabel.isHidden = !hasLocalPreview
titleLabel.isHidden = hasLocalPreview
messageLabel.isHidden = hasLocalPreview
accessibilityLabel = hasLocalPreview ? sourceLabel.text : "\(model.title),\(model.message)"
let isPlaying = model.state == .playing
sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : (isPlaying ? model.message + " · 实时图传" : nil)
sourceLabel.isHidden = !hasLocalPreview && !isPlaying
titleLabel.isHidden = hasLocalPreview || isPlaying
messageLabel.isHidden = hasLocalPreview || isPlaying
accessibilityLabel = hasLocalPreview || isPlaying ? sourceLabel.text : "\(model.title),\(model.message)"
updatePlayback()
}
@@ -67,6 +92,8 @@ final class DroneDockTaskLiveView: UIView {
clipsToBounds = true
accessibilityIdentifier = "drone.task.remote.feedPlaceholder"
layer.addSublayer(playerLayer)
rtcView.backgroundColor = .clear
addSubview(rtcView)
playerLayer.videoGravity = .resizeAspect
titleLabel.textAlignment = .center
messageLabel.textAlignment = .center
@@ -96,6 +123,7 @@ final class DroneDockTaskLiveView: UIView {
}
private func setupConstraints() {
rtcView.snp.makeConstraints { $0.edges.equalToSuperview() }
labels.snp.makeConstraints { make in
make.centerY.equalToSuperview().offset(-15)
make.leading.trailing.equalToSuperview().inset(20)
@@ -114,7 +142,24 @@ final class DroneDockTaskLiveView: UIView {
}
private func updatePlayback() {
guard isPlaybackActive, let requestedURL, requestedURL.isFileURL else {
guard isPlaybackActive else {
releasePlayer()
releaseRTC()
return
}
if let config = requestedRTC, let sessionID = requestedSessionID {
releasePlayer()
guard activeSessionID != sessionID else { return }
releaseRTC()
activeSessionID = sessionID
rtcPlayer.start(config, in: rtcView) { [weak self] event in
guard let self, self.activeSessionID == sessionID else { return }
self.onPlaybackEvent?(event, sessionID)
}
return
}
releaseRTC()
guard let requestedURL, requestedURL.isFileURL else {
releasePlayer()
return
}
@@ -129,6 +174,12 @@ final class DroneDockTaskLiveView: UIView {
queue.play()
}
private func releaseRTC() {
guard activeSessionID != nil else { return }
activeSessionID = nil
rtcPlayer.stop()
}
private func releasePlayer() {
player?.pause()
looper?.disableLooping()
@@ -0,0 +1,159 @@
import UIKit
@preconcurrency import VolcEngineRTC
/// 可替换的图传播放器;测试注入内存替身,不初始化 RTC 或连接设备。
@MainActor
protocol DroneDockLivePlaying: AnyObject {
func start(_ configuration: DroneDockVolcLiveConfiguration, in view: UIView,
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void)
func stop()
}
/// 火山 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 var generation = UUID()
private var timeoutTask: Task<Void, Never>?
private var expiryTask: Task<Void, Never>?
/// 加入凭证指定的房间,等待已发布的主视频流;不调用业务 live 接口。
func start(_ configuration: DroneDockVolcLiveConfiguration, in view: UIView,
onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) {
stop()
guard !DeviceCommandDebugPolicy.blocksLiveRequests else {
onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return
}
guard configuration.expiresAt.timeIntervalSinceNow > 5 else { onEvent(.expired); return }
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.delegate = delegate
let config = ByteRTCEngineConfig()
config.appID = configuration.appID
guard let engine = ByteRTCEngine.createRTCEngine(config, delegate: delegate) else {
onEvent(.failed("图传播放器初始化失败")); stop(); return
}
self.engine = engine
guard let room = engine.createRTCRoom(configuration.roomID) else {
onEvent(.failed("无法创建图传接收会话")); stop(); return
}
self.room = room
room.setRTCRoomDelegate(delegate)
let roomConfig = ByteRTCRoomConfig()
roomConfig.isPublishAudio = false
roomConfig.isPublishVideo = false
roomConfig.isAutoSubscribeAudio = false
roomConfig.isAutoSubscribeVideo = false
let user = ByteRTCUserInfo()
user.userId = configuration.userID
let result = room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: roomConfig)
guard result == 0 else {
onEvent(.failed("图传进房失败(\(result))")); stop(); return
}
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("暂未收到图传画面,请重试"))
}
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)
}
}
/// 销毁房间会退出订阅;只结束本机 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 receive(_ event: DroneDockVolcEvent, roomID: String) {
switch event {
case .published(let id, let sourceRoom, let index, let published):
guard sourceRoom == roomID, index == 0 else { return }
if !published {
if streamID == id { onEvent?(.failed("图传已停止,请重新连接")) }
return
}
guard streamID == nil, let renderView else { return }
streamID = id
let canvas = ByteRTCVideoCanvas()
canvas.view = renderView
canvas.renderMode = .fit
let renderResult = engine?.setRemoteVideoCanvas(id, withCanvas: canvas)
let subscribeResult = room?.subscribeStreamVideo(id, subscribe: true)
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)
}
}
}
/// 将 SDK 工作线程的回调转换为可发送的值,不跨线程传递 UIKit 或 SDK 对象。
private enum DroneDockVolcEvent: Sendable {
case published(String, String, Int, Bool)
case frame(String)
case failed(Int)
case expired
}
/// SDK 回调桥接;所有 UI 与引擎操作由上层切回主 Actor 后执行。
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) {
emit(.published(streamId, info.roomId, info.streamIndex, isPublish))
}
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String,
state: Int, extraInfo: String) {
if state != 0 { emit(.failed(state)) }
}
func rtcEngine(_ engine: ByteRTCEngine, onFirstRemoteVideoFrameRendered streamId: String,
info: ByteRTCStreamInfo, withFrameInfo frameInfo: ByteRTCVideoFrameInfo) {
emit(.frame(streamId))
}
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)) }
}
func onTokenWillExpire(_ rtcRoom: ByteRTCRoom) { emit(.expired) }
func onSubscribePrivilegeTokenWillExpire(_ rtcRoom: ByteRTCRoom) { emit(.expired) }
}