feat: Sdk 封装
This commit is contained in:
@@ -1,84 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// ANI 转换接口错误。
|
||||
struct AniConverterError: LocalizedError {
|
||||
let message: String
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
|
||||
/// 将源视频转换为设备可用的 ANI 文件。
|
||||
///
|
||||
/// 接口定义详见 duooomi-ble-sdk/CLAUDE.md 的"外部依赖 > ANI 转换 API"。
|
||||
/// 除 `videoUrl` 外,`width / height / fps` 全部固定写死,不得暴露为可调参数。
|
||||
enum AniConverter {
|
||||
private static let endpoint = URL(string: "https://api.mixvideo.bowong.cc/api/auth/loomart/file/convert-to-ani")!
|
||||
|
||||
/// 专用 session:延长超时,避免 ANI 转换耗时长被空闲连接关闭(-1005)。
|
||||
private static let session: URLSession = {
|
||||
let config = URLSessionConfiguration.default
|
||||
config.timeoutIntervalForRequest = 120
|
||||
config.timeoutIntervalForResource = 180
|
||||
config.waitsForConnectivity = true
|
||||
return URLSession(configuration: config)
|
||||
}()
|
||||
|
||||
/// 调用 ANI 转换接口,返回 ani 文件的 CDN URL。
|
||||
/// - Parameter videoUrl: 源视频的公网 URL。
|
||||
/// - Returns: 转换后 ani 文件的 CDN URL。
|
||||
/// - Throws: 网络异常、服务返回失败或响应解析失败等错误。
|
||||
/// - Note: 遇到 -1005(连接丢失)时自动重试一次。
|
||||
static func convert(videoUrl: String) async throws -> String {
|
||||
do {
|
||||
return try await performConvert(videoUrl: videoUrl)
|
||||
} catch let error as NSError where error.code == NSURLErrorNetworkConnectionLost {
|
||||
// -1005 重试一次
|
||||
return try await performConvert(videoUrl: videoUrl)
|
||||
}
|
||||
}
|
||||
|
||||
/// 实际执行转换请求。
|
||||
/// - Parameter videoUrl: 源视频 URL。
|
||||
/// - Returns: ani 文件 URL。
|
||||
/// - Throws: 各类网络或业务错误。
|
||||
private static func performConvert(videoUrl: String) async throws -> String {
|
||||
var request = URLRequest(url: endpoint)
|
||||
request.httpMethod = "POST"
|
||||
request.setValue("application/json", forHTTPHeaderField: "content-type")
|
||||
request.setValue(NetworkConfig.apiKey, forHTTPHeaderField: "x-api-key")
|
||||
request.timeoutInterval = 120
|
||||
|
||||
let body: [String: Any] = [
|
||||
"videoUrl": videoUrl,
|
||||
"width": 360,
|
||||
"height": 360,
|
||||
"fps": "24",
|
||||
]
|
||||
request.httpBody = try JSONSerialization.data(withJSONObject: body)
|
||||
|
||||
let (data, response) = try await session.data(for: request)
|
||||
|
||||
if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
|
||||
throw AniConverterError(message: "HTTP \(http.statusCode)")
|
||||
}
|
||||
|
||||
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
throw AniConverterError(message: "Invalid JSON response")
|
||||
}
|
||||
|
||||
guard (json["success"] as? Bool) == true,
|
||||
let outer = json["data"] as? [String: Any] else {
|
||||
throw AniConverterError(message: "ANI API reported failure")
|
||||
}
|
||||
|
||||
if (outer["status"] as? Bool) != true {
|
||||
let msg = (outer["msg"] as? String) ?? "ANI conversion failed"
|
||||
throw AniConverterError(message: msg)
|
||||
}
|
||||
|
||||
guard let aniUrl = outer["data"] as? String, !aniUrl.isEmpty else {
|
||||
throw AniConverterError(message: "Missing ani url in response")
|
||||
}
|
||||
|
||||
return aniUrl
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
import SwiftUI
|
||||
import DuooomiBleSDK
|
||||
|
||||
/// Demo 入口:初始化 SDK 并注入到视图树。
|
||||
/// 只需传 apiKey,其余配置(apiHost/cdnHost/firmwareIdentifier/firmwareStatus)使用默认值。
|
||||
@main
|
||||
struct DemoApp: App {
|
||||
@StateObject private var sdk = DuooomiBleSDK()
|
||||
@StateObject private var sdk = DuooomiBleSDK(config: .init(
|
||||
apiKey: ""
|
||||
))
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
struct FirmwareInfo: Codable, Equatable {
|
||||
let version: String
|
||||
let fileUrl: String
|
||||
let notes: String?
|
||||
}
|
||||
|
||||
enum FirmwareServiceError: LocalizedError {
|
||||
case invalidBrand
|
||||
case invalidResponse
|
||||
case http(Int)
|
||||
case network(String)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidBrand: return "Invalid brand"
|
||||
case .invalidResponse: return "Invalid firmware info response"
|
||||
case .http(let code): return "HTTP error: \(code)"
|
||||
case .network(let msg): return msg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum FirmwareUpdateService {
|
||||
// 可根据后端实际接口调整
|
||||
private static let base = NetworkConfig.apiHost
|
||||
private static let latestPath = "/api/auth/firmware/latest"
|
||||
|
||||
/// 获取指定品牌的最新固件信息。
|
||||
/// - Parameters:
|
||||
/// - brand: 设备品牌,如 Bowong。
|
||||
/// - status: 固件状态筛选,默认 `PUBLISHED`。
|
||||
/// - Returns: 最新固件信息(版本、下载地址、备注)。
|
||||
/// - Throws: 参数不合法、网络/HTTP 错误或响应解析失败。
|
||||
static func fetchLatest(brand: String, status: String = "PUBLISHED") async throws -> FirmwareInfo {
|
||||
guard !brand.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw FirmwareServiceError.invalidBrand
|
||||
}
|
||||
var comps = URLComponents(url: base.appendingPathComponent(latestPath), resolvingAgainstBaseURL: false)!
|
||||
comps.queryItems = [
|
||||
URLQueryItem(name: "brand", value: brand),
|
||||
URLQueryItem(name: "status", value: status)
|
||||
]
|
||||
guard let url = comps.url else { throw FirmwareServiceError.invalidResponse }
|
||||
|
||||
var req = URLRequest(url: url)
|
||||
req.httpMethod = "GET"
|
||||
req.setValue(NetworkConfig.apiKey, forHTTPHeaderField: "x-api-key")
|
||||
req.setValue("application/json", forHTTPHeaderField: "accept")
|
||||
|
||||
do {
|
||||
let (data, resp) = try await URLSession.shared.data(for: req)
|
||||
guard let http = resp as? HTTPURLResponse else { throw FirmwareServiceError.invalidResponse }
|
||||
guard (200...299).contains(http.statusCode) else {
|
||||
throw FirmwareServiceError.http(http.statusCode)
|
||||
}
|
||||
|
||||
// 期望返回 { version: String, fileUrl: String, notes?: String }
|
||||
let info = try JSONDecoder().decode(FirmwareInfo.self, from: data)
|
||||
return info
|
||||
} catch let e as FirmwareServiceError {
|
||||
throw e
|
||||
} catch {
|
||||
throw FirmwareServiceError.network(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
enum NetworkConfig {
|
||||
/// Shared API host for mixvideo endpoints
|
||||
static let apiHost = URL(string: "https://api.mixvideo.bowong.cc")!
|
||||
|
||||
/// Shared API key used across ANI conversion and firmware APIs
|
||||
static let apiKey = "gsUBjxphRjvpERpLiMSUFXERSsuqXvPTkzNSnoHgLqzlByabSemmMpTemyvRkRuj"
|
||||
}
|
||||
|
||||
@@ -4,14 +4,14 @@ import DuooomiBleSDK
|
||||
// MARK: - CDN Helper
|
||||
|
||||
private enum CDNHelper {
|
||||
static let host = "https://cdn.bowong.cc/"
|
||||
static var cdnHost = "https://cdn.bowong.cc/"
|
||||
|
||||
static func ensureFullUrl(_ keyOrUrl: String) -> String {
|
||||
if keyOrUrl.hasPrefix("http://") || keyOrUrl.hasPrefix("https://") {
|
||||
return keyOrUrl
|
||||
}
|
||||
let key = keyOrUrl.hasPrefix("/") ? String(keyOrUrl.dropFirst()) : keyOrUrl
|
||||
return host + key
|
||||
return cdnHost + key
|
||||
}
|
||||
|
||||
static func isImage(_ url: String) -> Bool {
|
||||
@@ -21,17 +21,28 @@ private enum CDNHelper {
|
||||
}
|
||||
|
||||
// MARK: - View
|
||||
//
|
||||
// Demo 演示 SDK 全部功能:
|
||||
// 1. Scan & Connect — sdk.scan() / sdk.connect(deviceId:) / sdk.disconnect()
|
||||
// 2. Device — sdk.getDeviceInfo() / sdk.getVersion() / sdk.bind(userId:) / sdk.unbind(userId:)
|
||||
// 3. Transfer — sdk.transferMedia(fileUrl:) 一步传输(内部自动 ANI 转换 + prepare + transfer)
|
||||
// 4. Firmware — sdk.fetchLatestFirmware() 查询 + sdk.transferFile(fileUri:commandType:.otaPackage) OTA
|
||||
// 5. Device Files — sdk.deleteFile(key:) 删除设备文件
|
||||
//
|
||||
// 可观察状态:btState / connectedDevice / deviceInfo / version / transferProgress / error
|
||||
|
||||
struct WrapperTestView: View {
|
||||
@EnvironmentObject var sdk: DuooomiBleSDK
|
||||
|
||||
@State private var userId = "test-user-001"
|
||||
@State private var videoUrl = "https://cdn.bowong.cc/material/569f48a8e29f47859b3a9808be37f94c.mp4"
|
||||
@State private var aniUrlDirect = "https://cdn.bowong.cc/material/c59affcbe0654bf8b69aaadc1900ac3f.ani"
|
||||
// Firmware update
|
||||
@State private var fileUrl = "https://cdn.bowong.cc/material/569f48a8e29f47859b3a9808be37f94c.mp4"
|
||||
// Firmware
|
||||
@State private var firmwareBrand = "duomi"
|
||||
@State private var firmwareStatus = "DRAFT"
|
||||
@State private var firmwareInfo: FirmwareInfo? = nil
|
||||
@State private var firmwareLoading = false
|
||||
@State private var firmwareError: String? = nil
|
||||
// State
|
||||
@State private var isBusy = false
|
||||
@State private var connectingDeviceId: String?
|
||||
@State private var deviceFiles: [String] = []
|
||||
@@ -39,7 +50,6 @@ struct WrapperTestView: View {
|
||||
|
||||
struct LogLine: Identifiable {
|
||||
let id = UUID()
|
||||
let time = Date()
|
||||
let level: Level
|
||||
let message: String
|
||||
enum Level { case info, success, error }
|
||||
@@ -50,19 +60,17 @@ struct WrapperTestView: View {
|
||||
statusSection
|
||||
scanSection
|
||||
deviceSection
|
||||
fileSection
|
||||
directAniSection
|
||||
transferSection
|
||||
firmwareSection
|
||||
deviceFilesSection
|
||||
logSection
|
||||
}
|
||||
.navigationTitle("Native SDK Test")
|
||||
.navigationTitle("SDK Demo")
|
||||
.scrollDismissesKeyboard(.interactively)
|
||||
.onTapGesture {
|
||||
UIApplication.shared.sendAction(
|
||||
#selector(UIResponder.resignFirstResponder),
|
||||
to: nil, from: nil, for: nil
|
||||
)
|
||||
.onAppear {
|
||||
CDNHelper.cdnHost = sdk.config.cdnHost
|
||||
firmwareBrand = sdk.config.firmwareIdentifier
|
||||
firmwareStatus = sdk.config.firmwareStatus
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,9 +78,14 @@ struct WrapperTestView: View {
|
||||
|
||||
private var statusSection: some View {
|
||||
Section("Status") {
|
||||
LabeledContent("btState", value: sdk.btState.rawValue)
|
||||
LabeledContent("isActivated", value: sdk.isActivated ? "YES" : "NO")
|
||||
LabeledContent("busy", value: isBusy ? "YES" : "no")
|
||||
LabeledContent("BLE", value: sdk.btState.rawValue)
|
||||
LabeledContent("Device", value: sdk.connectedDevice?.name ?? "—")
|
||||
LabeledContent("Version", value: sdk.version.isEmpty ? "—" : sdk.version)
|
||||
if sdk.transferProgress > 0 {
|
||||
ProgressView(value: Double(sdk.transferProgress), total: 100) {
|
||||
Text("\(sdk.transferProgress)%").font(.caption)
|
||||
}
|
||||
}
|
||||
if let err = sdk.error {
|
||||
Text(err).foregroundStyle(.red).font(.caption)
|
||||
}
|
||||
@@ -80,7 +93,7 @@ struct WrapperTestView: View {
|
||||
}
|
||||
|
||||
private var scanSection: some View {
|
||||
Section("Scan") {
|
||||
Section("Scan & Connect") {
|
||||
HStack {
|
||||
Button("Scan") {
|
||||
sdk.scan()
|
||||
@@ -102,9 +115,7 @@ struct WrapperTestView: View {
|
||||
Text(device.id).font(.caption2).foregroundStyle(.secondary)
|
||||
}
|
||||
Spacer()
|
||||
Text("\(device.rssi) dBm")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Text("\(device.rssi) dBm").font(.caption).foregroundStyle(.secondary)
|
||||
|
||||
if sdk.connectedDevice?.id == device.id {
|
||||
Button("Disconnect") {
|
||||
@@ -130,19 +141,10 @@ struct WrapperTestView: View {
|
||||
|
||||
private var deviceSection: some View {
|
||||
Section("Device") {
|
||||
LabeledContent("Name", value: sdk.connectedDevice?.name ?? "—")
|
||||
LabeledContent("ID", value: sdk.connectedDevice?.id ?? "—")
|
||||
LabeledContent("Brand", value: sdk.deviceInfo?.brand ?? "—")
|
||||
LabeledContent("Size", value: sdk.deviceInfo?.size ?? "—")
|
||||
LabeledContent(
|
||||
"Power",
|
||||
value: sdk.deviceInfo.map { "\($0.powerlevel)%" } ?? "—"
|
||||
)
|
||||
LabeledContent(
|
||||
"Storage",
|
||||
value: sdk.deviceInfo.map { "\($0.freespace)/\($0.allspace)" } ?? "—"
|
||||
)
|
||||
LabeledContent("Version", value: sdk.version.isEmpty ? "—" : sdk.version)
|
||||
LabeledContent("Power", value: sdk.deviceInfo.map { "\($0.powerlevel)%" } ?? "—")
|
||||
LabeledContent("Storage", value: sdk.deviceInfo.map { "\($0.freespace)/\($0.allspace)" } ?? "—")
|
||||
|
||||
HStack {
|
||||
Button("getDeviceInfo") { Task { await runGetDeviceInfo() } }
|
||||
@@ -161,54 +163,54 @@ struct WrapperTestView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var fileSection: some View {
|
||||
private var transferSection: some View {
|
||||
Section("Transfer") {
|
||||
if sdk.transferProgress > 0 {
|
||||
ProgressView(value: Double(sdk.transferProgress), total: 100) {
|
||||
Text("Transfer: \(sdk.transferProgress)%").font(.caption)
|
||||
}
|
||||
}
|
||||
|
||||
TextField("videoUrl (source)", text: $videoUrl)
|
||||
TextField("File URL (mp4/jpg/png/ani)", text: $fileUrl)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.autocapitalization(.none)
|
||||
.disableAutocorrection(true)
|
||||
|
||||
Button("Convert → PrepareTransfer → Transfer") {
|
||||
Task { await runConvertAndTransfer() }
|
||||
Button("Transfer") {
|
||||
Task { await runTransfer() }
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(videoUrl.isEmpty || sdk.connectedDevice == nil)
|
||||
.disabled(fileUrl.isEmpty || sdk.connectedDevice == nil || isBusy)
|
||||
}
|
||||
}
|
||||
|
||||
private var directAniSection: some View {
|
||||
Section("Direct ANI Transfer") {
|
||||
TextField("aniUrl (https://... .ani)", text: $aniUrlDirect)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.autocapitalization(.none)
|
||||
.disableAutocorrection(true)
|
||||
|
||||
Button("Prepare → Transfer ANI") {
|
||||
Task { await runTransferAniDirect() }
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(aniUrlDirect.isEmpty || sdk.connectedDevice == nil || isBusy)
|
||||
}
|
||||
}
|
||||
private static let statusOptions = ["DRAFT", "PUBLISHED"]
|
||||
|
||||
private var firmwareSection: some View {
|
||||
Section("Firmware Update") {
|
||||
LabeledContent("Current Version", value: sdk.version.isEmpty ? "—" : sdk.version)
|
||||
LabeledContent("Brand", value: sdk.deviceInfo?.brand ?? "—")
|
||||
|
||||
HStack {
|
||||
Text("Identifier")
|
||||
TextField("duomi", text: $firmwareBrand)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.autocapitalization(.none)
|
||||
.disableAutocorrection(true)
|
||||
}
|
||||
|
||||
Picker("Status", selection: $firmwareStatus) {
|
||||
ForEach(Self.statusOptions, id: \.self) { Text($0) }
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
|
||||
if let info = firmwareInfo {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("Latest: \(info.version)")
|
||||
Text(info.fileUrl).font(.caption2).foregroundStyle(.secondary)
|
||||
if let notes = info.notes, !notes.isEmpty {
|
||||
Text(notes).font(.caption)
|
||||
LabeledContent("Latest", value: info.version)
|
||||
if let size = info.fileSize {
|
||||
let bytes = Int(size) ?? 0
|
||||
LabeledContent("Size", value: ByteCountFormatter.string(fromByteCount: Int64(bytes), countStyle: .file))
|
||||
}
|
||||
if let md5 = info.fileMd5, !md5.isEmpty {
|
||||
LabeledContent("MD5", value: md5).font(.caption2)
|
||||
}
|
||||
if let desc = info.description, !desc.isEmpty {
|
||||
Text(desc).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Text(info.fileUrl).font(.caption2).foregroundStyle(.secondary).lineLimit(2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,18 +218,25 @@ struct WrapperTestView: View {
|
||||
Text(err).font(.caption).foregroundStyle(.red)
|
||||
}
|
||||
|
||||
if firmwareLoading {
|
||||
HStack {
|
||||
ProgressView().controlSize(.small)
|
||||
Text("Fetching...").font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
HStack {
|
||||
Button(firmwareLoading ? "Fetching..." : "Get Update Info") {
|
||||
Button("Get Update Info") {
|
||||
Task { await runFetchFirmwareInfo() }
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.disabled(firmwareLoading || sdk.connectedDevice == nil || sdk.deviceInfo?.brand == nil)
|
||||
.disabled(firmwareLoading || firmwareBrand.isEmpty)
|
||||
|
||||
Button("Upgrade Firmware") {
|
||||
Button("Upgrade") {
|
||||
Task { await runUpgradeFirmware() }
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(firmwareInfo?.fileUrl.isEmpty != false || sdk.connectedDevice == nil || isBusy)
|
||||
.disabled(firmwareInfo?.fileUrl.isEmpty != false || sdk.connectedDevice == nil || isBusy || firmwareLoading)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -261,9 +270,9 @@ struct WrapperTestView: View {
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
Text(URL(string: fileUrl)?.lastPathComponent ?? fileUrl)
|
||||
.font(.caption)
|
||||
.lineLimit(1)
|
||||
Text(rawKey)
|
||||
.font(.caption2)
|
||||
.lineLimit(2)
|
||||
|
||||
Spacer()
|
||||
|
||||
@@ -284,19 +293,11 @@ struct WrapperTestView: View {
|
||||
ForEach(logs.prefix(80)) { line in
|
||||
Text(line.message)
|
||||
.font(.caption)
|
||||
.foregroundStyle(color(for: line.level))
|
||||
.foregroundStyle(line.level == .error ? .red : line.level == .success ? .green : .primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func color(for level: LogLine.Level) -> Color {
|
||||
switch level {
|
||||
case .info: return .primary
|
||||
case .success: return .green
|
||||
case .error: return .red
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Logging
|
||||
|
||||
private func log(_ message: String, level: LogLine.Level = .info) {
|
||||
@@ -304,8 +305,10 @@ struct WrapperTestView: View {
|
||||
if logs.count > 200 { logs.removeLast() }
|
||||
}
|
||||
|
||||
// MARK: - Async runners
|
||||
// MARK: - Actions
|
||||
// 每个 run* 方法对应一个 SDK API 调用,展示输入/输出和错误处理
|
||||
|
||||
/// sdk.connect(deviceId:) → DiscoveredDevice
|
||||
private func runConnect(deviceId: String) async {
|
||||
connectingDeviceId = deviceId
|
||||
defer { connectingDeviceId = nil }
|
||||
@@ -318,6 +321,7 @@ struct WrapperTestView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// sdk.disconnect()
|
||||
private func runDisconnect() async {
|
||||
log("→ disconnect")
|
||||
do {
|
||||
@@ -329,21 +333,20 @@ struct WrapperTestView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// sdk.getDeviceInfo() → DeviceInfo
|
||||
private func runGetDeviceInfo() async {
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
log("→ getDeviceInfo")
|
||||
do {
|
||||
let info = try await sdk.getDeviceInfo()
|
||||
log(
|
||||
"getDeviceInfo ✓ brand=\(info.brand) size=\(info.size) battery=\(info.powerlevel)",
|
||||
level: .success
|
||||
)
|
||||
log("getDeviceInfo ✓ brand=\(info.brand) power=\(info.powerlevel)%", level: .success)
|
||||
} catch {
|
||||
log("getDeviceInfo ✗ \(error.localizedDescription)", level: .error)
|
||||
}
|
||||
}
|
||||
|
||||
/// sdk.getVersion() → VersionInfo
|
||||
private func runGetVersion() async {
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
@@ -356,6 +359,7 @@ struct WrapperTestView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// sdk.bind(userId:) → BindingResponse (sn + contents)。绑定后才能查看设备文件
|
||||
private func runBind() async {
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
@@ -369,6 +373,7 @@ struct WrapperTestView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// sdk.unbind(userId:) → UnbindResponse。解绑后该账号的设备文件将被删除
|
||||
private func runUnbind() async {
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
@@ -382,90 +387,20 @@ struct WrapperTestView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private func runConvertAndTransfer() async {
|
||||
/// sdk.transferMedia(fileUrl:) — 一步完成:自动转换 ANI + prepare + transfer
|
||||
private func runTransfer() async {
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
log("→ transferMedia(\(fileUrl))")
|
||||
do {
|
||||
// 1. Convert
|
||||
log("→ AniConverter.convert")
|
||||
let aniUrl = try await AniConverter.convert(videoUrl: videoUrl)
|
||||
log("ani url: \(aniUrl)", level: .success)
|
||||
|
||||
// 2. HEAD request to get ani file size
|
||||
log("→ HEAD \(aniUrl)")
|
||||
let aniSize = try await getFileSize(url: aniUrl)
|
||||
log("ani size: \(aniSize) bytes")
|
||||
|
||||
// 3. key = source video full URL
|
||||
let key = videoUrl
|
||||
log("key: \(key)")
|
||||
|
||||
// 4. prepareTransfer
|
||||
log("→ prepareTransfer")
|
||||
let prepareResult = try await sdk.prepareTransfer(key: key, size: aniSize)
|
||||
log("prepareTransfer → status=\(prepareResult.status)", level: .success)
|
||||
|
||||
guard prepareResult.status == "ready" else {
|
||||
log("device not ready: \(prepareResult.status)", level: .error)
|
||||
return
|
||||
}
|
||||
|
||||
// 5. transferFile
|
||||
log("→ transferFile")
|
||||
try await sdk.transferFile(fileUri: aniUrl)
|
||||
log("transferFile ✓", level: .success)
|
||||
try await sdk.transferMedia(fileUrl: fileUrl)
|
||||
log("transfer ✓", level: .success)
|
||||
} catch {
|
||||
log("transfer failed: \(error.localizedDescription)", level: .error)
|
||||
}
|
||||
}
|
||||
|
||||
private func runTransferAniDirect() async {
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
let aniUrl = aniUrlDirect.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !aniUrl.isEmpty else { return }
|
||||
|
||||
// 1) 获取 ani 文件大小(优先 HEAD,失败则直读数据长度)
|
||||
log("→ HEAD \(aniUrl)")
|
||||
var aniSize: Int = 0
|
||||
do {
|
||||
aniSize = try await getFileSize(url: aniUrl)
|
||||
} catch {
|
||||
aniSize = 0
|
||||
}
|
||||
if aniSize <= 0, let url = URL(string: aniUrl) {
|
||||
log("HEAD 无法获取大小,回退为直接下载计算")
|
||||
let (data, response) = try await URLSession.shared.data(from: url)
|
||||
if let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode) {
|
||||
aniSize = data.count
|
||||
} else {
|
||||
throw AniConverterError(message: "下载 ani 失败")
|
||||
}
|
||||
}
|
||||
log("ani size: \(aniSize) bytes")
|
||||
|
||||
// 2) 使用 aniUrl 作为 key 进行 prepare
|
||||
let key = aniUrl
|
||||
log("key: \(key)")
|
||||
log("→ prepareTransfer")
|
||||
let prepareResult = try await sdk.prepareTransfer(key: key, size: aniSize)
|
||||
log("prepareTransfer → status=\(prepareResult.status)", level: .success)
|
||||
|
||||
guard prepareResult.status == "ready" else {
|
||||
log("device not ready: \(prepareResult.status)", level: .error)
|
||||
return
|
||||
}
|
||||
|
||||
// 3) 传输 ANI 文件
|
||||
log("→ transferFile (ANI)")
|
||||
try await sdk.transferFile(fileUri: aniUrl, commandType: .transferAniVideo)
|
||||
log("transferFile ✓", level: .success)
|
||||
} catch {
|
||||
log("transfer failed: \(error.localizedDescription)", level: .error)
|
||||
log("transfer ✗ \(error.localizedDescription)", level: .error)
|
||||
}
|
||||
}
|
||||
|
||||
/// sdk.deleteFile(key:) → DeleteFileResponse
|
||||
private func runDeleteFile(_ rawKey: String) async {
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
@@ -479,48 +414,42 @@ struct WrapperTestView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// sdk.fetchLatestFirmware(identifier:status:) → FirmwareInfo?
|
||||
private func runFetchFirmwareInfo() async {
|
||||
guard let brand = sdk.deviceInfo?.brand, !brand.isEmpty else {
|
||||
firmwareError = "No device brand"
|
||||
let brand = firmwareBrand.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !brand.isEmpty else {
|
||||
firmwareError = "No identifier specified"
|
||||
return
|
||||
}
|
||||
firmwareLoading = true
|
||||
firmwareError = nil
|
||||
defer { firmwareLoading = false }
|
||||
log("→ fetch firmware info for \(brand)")
|
||||
log("→ fetchLatestFirmware(\(brand), \(firmwareStatus))")
|
||||
do {
|
||||
let info = try await FirmwareUpdateService.fetchLatest(brand: brand)
|
||||
let info = try await sdk.fetchLatestFirmware(identifier: brand, status: firmwareStatus)
|
||||
firmwareInfo = info
|
||||
log("firmware latest: \(info.version)", level: .success)
|
||||
if let info {
|
||||
log("firmware latest: \(info.version)", level: .success)
|
||||
} else {
|
||||
log("no firmware available", level: .info)
|
||||
}
|
||||
} catch {
|
||||
firmwareError = error.localizedDescription
|
||||
log("firmware info ✗ \(error.localizedDescription)", level: .error)
|
||||
}
|
||||
}
|
||||
|
||||
/// 固件升级第二步:sdk.upgradeFirmware(fileUrl:)
|
||||
private func runUpgradeFirmware() async {
|
||||
guard let url = firmwareInfo?.fileUrl, !url.isEmpty else { return }
|
||||
guard let info = firmwareInfo, !info.fileUrl.isEmpty else { return }
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
log("→ OTA transfer")
|
||||
log("→ upgradeFirmware \(info.version)")
|
||||
do {
|
||||
try await sdk.transferFile(fileUri: url, commandType: .otaPackage)
|
||||
try await sdk.upgradeFirmware(fileUrl: info.fileUrl)
|
||||
log("OTA ✓", level: .success)
|
||||
} catch {
|
||||
log("OTA ✗ \(error.localizedDescription)", level: .error)
|
||||
}
|
||||
}
|
||||
|
||||
private func getFileSize(url: String) async throws -> Int {
|
||||
guard let fileUrl = URL(string: url) else {
|
||||
throw AniConverterError(message: "Invalid URL: \(url)")
|
||||
}
|
||||
var request = URLRequest(url: fileUrl)
|
||||
request.httpMethod = "HEAD"
|
||||
let (_, response) = try await URLSession.shared.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw AniConverterError(message: "Invalid response")
|
||||
}
|
||||
return Int(http.expectedContentLength)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user