Files
duooomi-ios-sdk/Sources/DuooomiBleSDK/Services/FirmwareService.swift
2026-04-10 16:15:53 +08:00

61 lines
2.1 KiB
Swift

import Foundation
///
public struct FirmwareInfo: Codable, Equatable, Sendable {
public let version: String
public let fileUrl: String
public let description: String?
public let fileSize: String?
public let fileMd5: String?
public let identifier: String?
public let status: String?
}
struct FirmwareResponse: Codable {
let success: Bool
let data: FirmwareInfo?
}
///
final class FirmwareService {
private let config: DuooomiBleConfig
private let latestPath = "api/auth/loomart/firmware/latest-published"
init(config: DuooomiBleConfig) {
self.config = config
}
func fetchLatest(identifier: String? = nil, status: String? = nil) async throws -> FirmwareInfo? {
let id = (identifier ?? config.firmwareIdentifier).trimmingCharacters(in: .whitespacesAndNewlines)
let st = status ?? config.firmwareStatus
guard !id.isEmpty else {
throw DuooomiBleError.transferFailed("Invalid firmware identifier")
}
var comps = URLComponents(url: config.apiHost.appendingPathComponent(latestPath), resolvingAgainstBaseURL: false)!
comps.queryItems = [
URLQueryItem(name: "identifier", value: id),
URLQueryItem(name: "status", value: st)
]
guard let url = comps.url else {
throw DuooomiBleError.transferFailed("Invalid firmware URL")
}
var req = URLRequest(url: url)
req.httpMethod = "GET"
req.setValue(config.apiKey, forHTTPHeaderField: "x-api-key")
req.setValue("application/json", forHTTPHeaderField: "accept")
let (data, resp) = try await URLSession.shared.data(for: req)
guard let http = resp as? HTTPURLResponse else {
throw DuooomiBleError.transferFailed("Invalid response")
}
guard (200...299).contains(http.statusCode) else {
throw DuooomiBleError.transferFailed("HTTP \(http.statusCode)")
}
let decoded = try JSONDecoder().decode(FirmwareResponse.self, from: data)
return decoded.data
}
}