49 lines
1.6 KiB
Swift
49 lines
1.6 KiB
Swift
import Foundation
|
||
|
||
/// 文件传输服务:下载文件并通过协议发送二进制数据
|
||
final class FileTransferService {
|
||
private let protocolService: BleProtocolService
|
||
|
||
init(protocolService: BleProtocolService) {
|
||
self.protocolService = protocolService
|
||
}
|
||
|
||
/// 传输文件到设备
|
||
/// - Parameters:
|
||
/// - fileUri: 本地 file:// URL 或远程 https:// URL
|
||
/// - commandType: 传输命令类型
|
||
/// - onProgress: 进度回调 0.0 ~ 1.0
|
||
func transferFile(
|
||
fileUri: String,
|
||
commandType: CommandType,
|
||
onProgress: ((Double) -> Void)? = nil
|
||
) async throws {
|
||
BleLog.i("Load file: \(fileUri)", "Transfer")
|
||
let data = try await loadFileData(from: fileUri)
|
||
BleLog.d("File loaded: size=\(data.count) bytes", "Transfer")
|
||
|
||
try await protocolService.send(
|
||
type: commandType.rawValue,
|
||
data: data,
|
||
onProgress: onProgress
|
||
)
|
||
}
|
||
|
||
private func loadFileData(from uri: String) async throws -> Data {
|
||
guard let url = URL(string: uri) else {
|
||
throw DuooomiBleError.transferFailed("Invalid URL: \(uri)")
|
||
}
|
||
|
||
if url.isFileURL {
|
||
return try Data(contentsOf: url)
|
||
} else {
|
||
let (data, response) = try await URLSession.shared.data(from: url)
|
||
guard let httpResponse = response as? HTTPURLResponse,
|
||
(200...299).contains(httpResponse.statusCode) else {
|
||
throw DuooomiBleError.transferFailed("Failed to download file: \(uri)")
|
||
}
|
||
return data
|
||
}
|
||
}
|
||
}
|