fix: 自动开启机巢图传并修复日志崩溃与订阅重连

This commit is contained in:
2026-11-03 10:18:23 +08:00
parent 203799b2f4
commit 5d48e37cd7
12 changed files with 301 additions and 36 deletions
@@ -6,7 +6,7 @@ import OSLog
enum APIConsoleDiagnostics {
private static let logger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "API")
private static let droneDockLogger = Logger(subsystem: "com.yuanzhixiang.suixinkan", category: "DroneDock")
private static let outputLock = NSLock()
private static let outputWriter = APIConsoleOutputWriter()
/// Xcode 附加调试时输出一个完整 JSON;脱离调试器时继续写入系统日志。
static func write(_ message: String) {
@@ -20,12 +20,7 @@ enum APIConsoleDiagnostics {
private static func output(_ message: String, logger: Logger) {
guard let text = APIConsoleFormat.render(message) else { return }
outputLock.lock()
defer { outputLock.unlock() }
if isDebuggerAttached || isatty(STDOUT_FILENO) != 0 {
// 不受系统日志单条长度限制,也不受 DEBUG 编译条件影响。
FileHandle.standardOutput.write(Data((text + "\n").utf8))
} else {
outputWriter.write(text, prefersStandardOutput: isDebuggerAttached || isatty(STDOUT_FILENO) != 0) { text in
// 保留独立运行 Release 包的系统日志可见性,不加 session/entry/part 等包装。
for chunk in DroneDockDiagnostics.chunks(text) { logger.notice("\(chunk, privacy: .public)") }
}
@@ -39,3 +34,40 @@ enum APIConsoleDiagnostics {
&& (info.kp_proc.p_flag & P_TRACED) != 0
}
}
/// 串行写入日志;Xcode 输出通道断开后,本次运行改用系统日志,写入错误不能中断业务。
final class APIConsoleOutputWriter: @unchecked Sendable {
private let lock = NSLock()
private var standardOutputFailed = false
private let writeStandardOutput: @Sendable (Data) throws -> Void
/// 注入可失败的输出通道,以便使用隔离文件句柄验证断连及回退。
init(writeStandardOutput: @escaping @Sendable (Data) throws -> Void = {
try APIConsoleOutputWriter.write($0, to: .standardOutput)
}) {
self.writeStandardOutput = writeStandardOutput
}
/// 完整记录只走一个出口;stdout 失败时把原始记录交给系统日志,不再尝试损坏的通道。
func write(_ text: String, prefersStandardOutput: Bool, fallback: (String) -> Void) {
lock.lock()
defer { lock.unlock() }
if prefersStandardOutput && !standardOutputFailed {
do {
try writeStandardOutput(Data((text + "\n").utf8))
return
} catch {
standardOutputFailed = true
}
}
fallback(text)
}
/// 使用可抛 Swift 错误的写入 API,并把断管转成 EPIPE,避免 NSException 或 SIGPIPE 退出进程。
static func write(_ data: Data, to handle: FileHandle) throws {
guard fcntl(handle.fileDescriptor, F_SETNOSIGPIPE, 1) != -1 else {
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
}
try handle.write(contentsOf: data)
}
}
@@ -1,6 +1,6 @@
import Foundation
/// 朱工任务图传参数服务;请求可能启动设备图传,Release 可手动开启,Debug 只允许隔离模拟注入。
/// 朱工任务图传参数服务;请求可能启动设备图传,Release 随页面自动开启,Debug 只允许隔离模拟注入。
protocol DroneDockLiveServing: Sendable {
/// 读取同一订单飞行任务的图传回执,不创建任务或更换飞机。
@MainActor
@@ -14,7 +14,13 @@ enum DroneDockShootingSocketMessage {
/// WebSocket 成功码为 0,不使用 HTTP 的 100000 Envelope。
static func decode(_ data: Data) throws -> Self {
guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],
// 服务端建连先发 Opened。它不代表 310 订阅成功,也不能取消订阅超时或 HTTP 兜底。
if String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) == "Opened" {
return .unrelated
}
let json = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)
if json as? String == "Opened" { return .unrelated }
guard let root = json as? [String: Any],
let code = root["code"] as? Int else { throw APIError.invalidResponse }
if code != 0 {
return .rejected(code: code, message: root["msg"] as? String ?? "任务订阅失败")
@@ -1,6 +1,6 @@
import Foundation
/// 任务图传的单次请求与生命周期;正式图传手动开启,模拟来源单独注入。
/// 任务图传的单次请求与生命周期;页面可见时自动开启,模拟来源单独注入。
final class DroneDockLiveViewModel {
/// 当前图传所属的账号、景区与门店范围。
let context: DroneDockHomeContext
@@ -14,8 +14,8 @@ final class DroneDockLiveViewModel {
private(set) var isLoading = false
/// 仅显式正式入口允许解析设备 RTC;本地模拟即使收到参数也不连接设备。
let allowsDevicePlayback: Bool
/// 正式图传必须手动开启;演示入口可自动载入本地样片。
var loadsAutomatically: Bool { !allowsDevicePlayback }
/// 每次进入页面或回前台仅从空闲态自动加载,状态刷新不重复启动图传。
var loadsAutomatically: Bool { canLoad && state == .idle }
private(set) var rtcConfiguration: DroneDockVolcLiveConfiguration?
private(set) var playbackSessionID: UUID?
@@ -68,7 +68,7 @@ final class DroneDockLiveViewModel {
var message: String {
switch state {
case .restricted: return "禁飞调试期间不启动设备图传"
case .idle: return allowsDevicePlayback ? "点击开启当前任务的实时图传" : "按当前任务获取图传信息"
case .idle: return allowsDevicePlayback ? "正在准备连接图传" : "按当前任务获取图传信息"
case .loading: return "请稍候"
case .unavailable(let reason), .failed(let reason): return reason
case .localPreview: return "仅播放本地样片,未连接无人机"
@@ -80,14 +80,14 @@ final class DroneDockLiveViewModel {
/// 操作名称跟随当前阶段,模拟来源始终显式标记。
var actionTitle: String? {
guard service != nil else { return nil }
if isLoading { return "正在加载…" }
if isLoading { return allowsDevicePlayback ? nil : "正在加载…" }
switch state {
case .restricted: return nil
case .idle: return allowsDevicePlayback ? "开启实时图传" : (localPreviewURL == nil ? "获取图传信息" : "查看模拟图传")
case .loading: return "正在加载…"
case .idle: return nil
case .loading: return allowsDevicePlayback ? nil : "正在加载…"
case .failed, .unavailable: return "重试"
case .localPreview: return "重新加载模拟图传"
case .connecting: return "重新连接"
case .connecting: return nil
case .playing: return "刷新图传"
}
}
@@ -1,7 +1,7 @@
import SnapKit
import UIKit
/// 拍摄任务页:前台优先订阅快照、异常时 HTTP 兜底;图传与控制仍须用户手动操作。
/// 拍摄任务页:前台优先订阅快照、异常时 HTTP 兜底;自动开启图传,飞控仍由用户操作。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
@@ -14,7 +14,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private let summaryView = UIView()
private let taskTitleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let subtitleLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let feedPlaceholder = DroneDockTaskLiveView()
private let feedPlaceholder: DroneDockTaskLiveView
private let telemetryView = DroneShootingTaskTelemetryView()
private let statusView = DroneDockTaskStatusView()
private let safetyView = DroneDockTaskSafetyView()
@@ -45,11 +45,13 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
liveViewModel: DroneDockLiveViewModel? = nil,
livePlayer: (any DroneDockLivePlaying)? = nil,
realtimeSession: DroneDockShootingRealtimeSession? = nil,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil,
shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.feedPlaceholder = livePlayer.map { DroneDockTaskLiveView(rtcPlayer: $0) } ?? DroneDockTaskLiveView()
self.realtimeSession = realtimeSession
self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel(
context: viewModel.context, taskID: viewModel.taskID,
@@ -453,7 +455,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
}
/// 图传请求不轮询;正式入口仅响应用户点击,本地样片允许随页面加载。
/// 可见且活跃时自动开启一次;失败可手动重试,不随 shooting/Socket 刷新重复请求。
private func refreshLiveIfVisible(automatically: Bool = false) {
guard !automatically || liveViewModel.loadsAutomatically else { return }
guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return }
@@ -81,7 +81,7 @@ final class DroneDockTaskLiveView: UIView {
updatePlayback()
}
/// 页面离开或进入后台立即释放播放器;回来后仅恢复已经明确注入的本地来源。
/// 页面离开或进入后台立即释放播放器;重新获取图传参数由控制器协调。
func setPlaybackActive(_ active: Bool) {
isPlaybackActive = active
updatePlayback()