forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStorageSyncService.swift
More file actions
416 lines (337 loc) · 11.2 KB
/
Copy pathStorageSyncService.swift
File metadata and controls
416 lines (337 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import Combine
import Foundation
import OmiWAL
import os.log
// MARK: - Storage Sync Service
/// Service for syncing audio data from device SD card via BLE
/// Ported from: omi/app/lib/services/wals/sdcard_wal_sync.dart
@MainActor
final class StorageSyncService: ObservableObject {
// MARK: - Singleton
static let shared = StorageSyncService()
// MARK: - Published Properties
/// Whether sync is in progress
@Published private(set) var isSyncing = false
/// Current sync progress
@Published private(set) var progress: SyncProgress = SyncProgress()
/// Error message if sync fails
@Published var errorMessage: String?
// MARK: - Constants
/// Minimum bytes to trigger a sync (10 frames worth)
static let minBytesToSync = 80 * 10 * 100 // 10 seconds at 80 bytes/frame, 100 fps
/// BLE packet size for standard packets
static let standardPacketSize = 83
/// BLE packet size for packed format
static let packedPacketSize = 440
// MARK: - Properties
private let logger = Logger(subsystem: "me.omi.desktop", category: "StorageSyncService")
private let walService = WALService.shared
private let deviceProvider = DeviceProvider.shared
private var syncTask: Task<Void, Never>?
private var currentWal: WALEntry?
private var downloadedFrames: [Data] = []
private var totalBytesDownloaded = 0
private var lastProgressUpdate = Date()
private var lastProgressBytes = 0
// MARK: - Initialization
private init() {}
// MARK: - Public Methods
/// Check if device has data to sync
func checkForStorageData() async -> (totalBytes: Int, currentOffset: Int)? {
guard let connection = deviceProvider.activeConnection else {
logger.warning("No device connected for storage check")
return nil
}
let storageList = await connection.getStorageList()
guard storageList.count >= 2 else {
logger.debug("No storage data available")
return nil
}
let totalBytes = Int(storageList[0])
let currentOffset = Int(storageList[1])
logger.info("Storage check: total=\(totalBytes), offset=\(currentOffset)")
return (totalBytes, currentOffset)
}
/// Start syncing from device storage
func startSync(device: BtDevice, codec: String) async throws {
guard !isSyncing else {
logger.warning("Sync already in progress")
return
}
guard let connection = deviceProvider.activeConnection else {
throw StorageSyncError.deviceNotConnected
}
// Check storage status
guard let (totalBytes, currentOffset) = await checkForStorageData() else {
throw StorageSyncError.noDataToSync
}
let bytesToDownload = totalBytes - currentOffset
guard bytesToDownload >= Self.minBytesToSync else {
logger.info("Not enough data to sync: \(bytesToDownload) bytes")
return
}
isSyncing = true
errorMessage = nil
downloadedFrames = []
totalBytesDownloaded = 0
lastProgressUpdate = Date()
lastProgressBytes = 0
// Create WAL for this sync
currentWal = walService.createSdCardWal(
device: device.id,
deviceModel: device.type.displayName,
codec: codec,
totalBytes: totalBytes,
currentOffset: currentOffset
)
progress = SyncProgress(
totalBytes: bytesToDownload,
downloadedBytes: 0
)
logger.info("Starting SD card sync: \(bytesToDownload) bytes to download")
// Start sync task
syncTask = Task { [weak self] in
await self?.performSync(connection: connection, offset: currentOffset)
}
}
/// Stop current sync
func stopSync() {
syncTask?.cancel()
syncTask = nil
isSyncing = false
// Save partial progress
if let wal = currentWal, !downloadedFrames.isEmpty {
walService.updateWalWithDownloadedData(
walId: wal.id,
downloadedBytes: totalBytesDownloaded,
frames: downloadedFrames
)
}
currentWal = nil
downloadedFrames = []
totalBytesDownloaded = 0
lastProgressBytes = 0
logger.info("Sync stopped")
}
/// Clear device storage after successful sync
func clearDeviceStorage() async -> Bool {
guard let connection = deviceProvider.activeConnection else {
logger.warning("No device connected for storage clear")
return false
}
let success = await connection.writeToStorage(
fileNum: 1,
command: StorageCommand.clear.rawValue,
offset: 0
)
if success {
logger.info("Device storage cleared")
} else {
logger.error("Failed to clear device storage")
}
return success
}
// MARK: - Private Methods
private func performSync(connection: DeviceConnection, offset: Int) async {
// Send read command to start transfer
let success = await connection.writeToStorage(
fileNum: 1,
command: StorageCommand.read.rawValue,
offset: offset
)
guard success else {
await MainActor.run {
errorMessage = "Failed to start storage transfer"
isSyncing = false
}
return
}
// Listen for data stream
let stream = connection.getStorageStream()
do {
for try await data in stream {
if Task.isCancelled { break }
let result = processPacket(data)
switch result {
case .continue:
continue
case .complete:
logger.info("Transfer complete")
await finishSync()
return
case .error(let message):
logger.error("Transfer error: \(message)")
await MainActor.run {
errorMessage = message
isSyncing = false
}
return
}
}
} catch {
if !Task.isCancelled {
logger.error("Stream error: \(error.localizedDescription)")
await MainActor.run {
errorMessage = error.localizedDescription
isSyncing = false
}
}
}
}
private enum PacketResult {
case `continue`
case complete
case error(String)
}
private func processPacket(_ data: Data) -> PacketResult {
guard !data.isEmpty else { return .continue }
// Check for response codes
if data.count == 1 {
let code = data[0]
if let response = StorageResponse(rawValue: code) {
switch response {
case .ok:
return .continue
case .endOfTransmission:
return .complete
case .badFileSize:
return .error("Bad file size")
case .fileSizeZero:
return .error("File is empty")
}
}
// Unknown single-byte response
if code >= 100 {
return .complete
}
return .continue
}
// Process data packet
if data.count == Self.standardPacketSize {
processStandardPacket(data)
} else if data.count == Self.packedPacketSize {
processPackedPacket(data)
} else {
// Variable size packet - try to parse as frames. Count its bytes too
// (mirroring processPackedPacket): without this, a packet whose length is
// neither the standard nor packed size contributes decoded frames but zero
// counted bytes, so totalBytesDownloaded (and the WAL storageOffset it
// advances) stays ~0 — progress reports ~0%/bogus B-s and the
// `storageOffset >= storageTotalBytes` completion check never fires even
// though the audio was actually downloaded.
parseFramesFromData(data)
totalBytesDownloaded += data.count
}
// Update progress periodically
updateProgress()
return .continue
}
private func processStandardPacket(_ data: Data) {
// Format: [header(3)][count][data(80)]
guard data.count >= 4 else { return }
let frameData = data.suffix(80)
if frameData.count == 80 && OpusFrameValidator.startsWithValidFrame(Data(frameData)) {
downloadedFrames.append(Data(frameData))
totalBytesDownloaded += 80
}
}
private func processPackedPacket(_ data: Data) {
// Format: [frameSize][frameData][frameSize][frameData]...
parseFramesFromData(data)
totalBytesDownloaded += data.count
}
private func parseFramesFromData(_ data: Data) {
var offset = 0
while offset < data.count {
// Read frame size (1 byte)
let frameSize = Int(data[offset])
offset += 1
// Check for padding/empty slot
if frameSize == 0 {
// Skip padding until next block boundary
let blockOffset = offset % Self.packedPacketSize
if blockOffset != 0 {
let remaining = Self.packedPacketSize - blockOffset
offset += remaining
}
continue
}
// Validate frame size
guard frameSize > 0, offset + frameSize <= data.count else {
break
}
// Check if valid Opus frame
let frameData = data.subdata(in: offset..<(offset + frameSize))
if OpusFrameValidator.startsWithValidFrame(frameData) {
downloadedFrames.append(frameData)
}
offset += frameSize
}
}
/// Throughput over an interval. `nonisolated static` so it is synchronously
/// unit-testable without hopping the main actor.
nonisolated static func bytesPerSecond(bytesDelta: Int, interval: TimeInterval) -> Double {
interval > 0 ? Double(bytesDelta) / interval : 0
}
private func updateProgress() {
let now = Date()
let interval = now.timeIntervalSince(lastProgressUpdate)
guard interval >= 0.5 else { return }
// Rate over the elapsed interval since the last update, using the bytes
// downloaded in that window. The previous code reassigned lastProgressUpdate
// to `now` before computing `elapsed = now - lastProgressUpdate`, so `elapsed`
// was always 0 and the reported speed was always 0 B/s.
let bytesDelta = totalBytesDownloaded - lastProgressBytes
let bytesPerSecond = Self.bytesPerSecond(bytesDelta: bytesDelta, interval: interval)
lastProgressUpdate = now
lastProgressBytes = totalBytesDownloaded
Task { @MainActor in
progress = SyncProgress(
totalBytes: progress.totalBytes,
downloadedBytes: totalBytesDownloaded,
framesDownloaded: downloadedFrames.count,
bytesPerSecond: bytesPerSecond
)
}
}
private func finishSync() async {
guard let wal = currentWal else { return }
// Save downloaded data
walService.updateWalWithDownloadedData(
walId: wal.id,
downloadedBytes: totalBytesDownloaded,
frames: downloadedFrames
)
let frameCount = downloadedFrames.count
// Upload downloaded WALs to cloud (real POST /v2/sync-local-files) before
// resetting isSyncing, so a concurrent BLE download cannot start and get
// its own syncToCloud() skipped by WALService's isSyncing guard.
await walService.syncToCloud()
await MainActor.run {
isSyncing = false
currentWal = nil
downloadedFrames = []
totalBytesDownloaded = 0
}
logger.info("Sync completed: \(frameCount) frames downloaded")
}
}
// MARK: - Storage Sync Errors
enum StorageSyncError: LocalizedError {
case deviceNotConnected
case noDataToSync
case transferFailed(String)
case timeout
var errorDescription: String? {
switch self {
case .deviceNotConnected:
return "Device not connected"
case .noDataToSync:
return "No data available to sync"
case .transferFailed(let reason):
return "Transfer failed: \(reason)"
case .timeout:
return "Transfer timed out"
}
}
}