Skip to content

Commit 236f2fb

Browse files
committed
Save point
1 parent df1fdac commit 236f2fb

File tree

7 files changed

+48
-74
lines changed

7 files changed

+48
-74
lines changed

InfiniLink/Core/Settings/General/Filesystem/Views/FilesystemView.swift

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,7 @@ struct FileSystemToolbar: ViewModifier {
1616
for file in fileSystemViewModel.files {
1717
let lowercaseFilename = file.filename.lowercased()
1818

19-
guard let fileDataPath = file.url else {
20-
continue
21-
}
19+
guard file.url.startAccessingSecurityScopedResource() else { return }
2220

2321
do {
2422
if lowercaseFilename.hasSuffix(".png") ||
@@ -31,7 +29,7 @@ struct FileSystemToolbar: ViewModifier {
3129
lowercaseFilename.hasSuffix(".heif") ||
3230
lowercaseFilename.hasSuffix(".heic") {
3331

34-
guard let img = UIImage(contentsOfFile: fileDataPath.path),
32+
guard let img = UIImage(contentsOfFile: file.url.path),
3533
let cgImage = img.cgImage else {
3634
continue
3735
}
@@ -47,7 +45,7 @@ struct FileSystemToolbar: ViewModifier {
4745
var _ = bleFSHandler.writeFile(data: convertedImage, path: fileSystemViewModel.directory + "/" + String(fileNameWithoutExtension.prefix(26).trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "\\s+", with: "_", options: .regularExpression)) + ".bin", offset: 0)
4846
}
4947
} else {
50-
let fileData = try Data(contentsOf: fileDataPath)
48+
let fileData = try Data(contentsOf: file.url)
5149

5250
DispatchQueue.main.async {
5351
self.fileSystemViewModel.fileSize = 0
@@ -61,6 +59,8 @@ struct FileSystemToolbar: ViewModifier {
6159
} catch {
6260
log("Error sending files: \(error.localizedDescription)", caller: "FilesystemView", target: .ble)
6361
}
62+
63+
file.url.stopAccessingSecurityScopedResource()
6464
}
6565

6666
DispatchQueue.main.async {
@@ -224,8 +224,7 @@ struct FileSystemView: View {
224224

225225
self.fileSystemViewModel.files.append(FSFile(url: fileURL, filename: fileURL.lastPathComponent))
226226

227-
// Don't stop accessing the security-scoped resource because then the upload button won't work due to lack of necessary permissions
228-
// fileURL.stopAccessingSecurityScopedResource()
227+
fileURL.stopAccessingSecurityScopedResource()
229228
}
230229
} catch {
231230
log("Error getting file: \(error.localizedDescription)", caller: "FilesystemView")

InfiniLink/Core/Settings/General/Update/CurrentUpdateView.swift

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ struct CurrentUpdateView: View {
3131
.font(.title.weight(.bold))
3232
}
3333
Button {
34-
dfuUpdater.stopTransfer()
35-
dfuUpdater.isUpdating = false
34+
dfuUpdater.stopTransfer(abort: true)
3635
downloadManager.updateStarted = false
3736
} label: {
3837
Text("Cancel Update")

InfiniLink/Core/Settings/General/Update/SoftwareUpdateView.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,14 @@ struct SoftwareUpdateView: View {
9999
dfuUpdater.percentComplete = 0
100100
if downloadManager.externalResources {
101101
downloadManager.startTransfer = true
102-
downloadManager.startDownload(url: downloadManager.browserDownloadResourcesUrl)
103102
downloadManager.updateStarted = true
103+
downloadManager.startDownload(url: downloadManager.browserDownloadResourcesUrl)
104104
} else {
105105
if dfuUpdater.local {
106106
if useExperimentalDFU {
107107
DFUUpdaterCustom.shared.startDFU()
108108
} else {
109-
dfuUpdater.transfer()
109+
dfuUpdater.updateFirmware()
110110
downloadManager.updateStarted = true
111111
}
112112
} else {

InfiniLink/Model/FSFile.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,6 @@ import Foundation
99

1010
struct FSFile: Identifiable {
1111
let id = UUID()
12-
var url: URL?
12+
var url: URL
1313
var filename: String
1414
}

InfiniLink/Utils/DFUUpdater.swift

Lines changed: 15 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ class DFUUpdater: ObservableObject, DFUServiceDelegate, DFUProgressDelegate, Log
1818

1919
@Published var dfuState: String = ""
2020
@Published var transferCompleted = false
21-
@Published var isUpdating = false
2221
@Published var isUpdatingResources = false
2322
@Published var percentComplete: Double = 0
2423

@@ -31,36 +30,12 @@ class DFUUpdater: ObservableObject, DFUServiceDelegate, DFUProgressDelegate, Log
3130

3231
@AppStorage("updateResourcesWithFirmware") var updateResourcesWithFirmware = true
3332

34-
func transfer() {
35-
guard let url = firmwareURL else {return}
36-
guard url.startAccessingSecurityScopedResource() else { return }
37-
guard let selectedFirmware = try? DFUFirmware(urlToZipFile:url) else {
38-
log("Failed to load firmware.", caller: "DFUUpdater")
39-
return
40-
}
41-
let initiator = DFUServiceInitiator().with(firmware: selectedFirmware)
42-
43-
// Optional:
44-
// initiator.forceDfu = true/false // default false
45-
initiator.packetReceiptNotificationParameter = 20
46-
initiator.logger = self // - to get log info
47-
initiator.delegate = self // - to be informed about current state and errors
48-
initiator.progressDelegate = self // - to show progress bar
49-
// initiator.peripheralSelector = ... // the default selector is used
50-
if bleManager.infiniTime != nil {
51-
dfuController = initiator.start(target: bleManager.infiniTime)
52-
}
53-
url.stopAccessingSecurityScopedResource()
54-
}
55-
5633
func updateFirmware() {
5734
guard let selectedFirmware = try? DFUFirmware(urlToZipFile: firmwareURL) else {
5835
log("Failed to load firmware.", caller: "DFUUpdater")
5936
return
6037
}
6138

62-
self.isUpdating = true
63-
6439
let initiator = DFUServiceInitiator().with(firmware: selectedFirmware)
6540

6641
// Optional:
@@ -89,43 +64,41 @@ class DFUUpdater: ObservableObject, DFUServiceDelegate, DFUProgressDelegate, Log
8964
}
9065
}
9166

92-
func stopTransfer() {
93-
if dfuController != nil {
67+
func stopTransfer(abort: Bool) {
68+
if abort {
9469
_ = dfuController.abort()
95-
dfuController = nil
9670
}
71+
72+
firmwareURL?.stopAccessingSecurityScopedResource()
73+
74+
dfuController = nil
9775
dfuState = ""
98-
transferCompleted = false
99-
isUpdating = false
76+
10077
percentComplete = 0
78+
79+
downloadManager.updateAvailable = false
80+
downloadManager.updateStarted = false
81+
firmwareSelected = false
82+
transferCompleted = false
10183
}
10284

10385
func dfuStateDidChange(to state: DFUState) {
10486
dfuState = state.description
10587

10688
switch state {
10789
case .completed:
108-
transferCompleted = true
109-
isUpdating = false
110-
firmwareSelected = false
111-
112-
downloadManager.updateAvailable = false
113-
downloadManager.updateStarted = false
114-
115-
dfuController = nil
116-
percentComplete = 0
90+
stopTransfer(abort: false)
11791
case .disconnecting:
11892
bleManager.hasDisconnectedForUpdate = true
11993
case .aborted:
120-
dfuController = nil
121-
percentComplete = 0
94+
log("DFU upload successfully aborted", caller: "DFUUpdater", target: .dfu)
12295
default:
12396
break
12497
}
12598
}
12699

127100
func dfuError(_ error: DFUError, didOccurWithMessage message: String) {
128-
self.stopTransfer()
101+
stopTransfer(abort: false)
129102
}
130103

131104
func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) {

InfiniLink/Utils/DownloadManager.swift

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,6 @@ extension DownloadManager: URLSessionDelegate, URLSessionDownloadDelegate {
428428

429429
func urlSession(_: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
430430
do {
431-
432431
let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
433432
let savedURL = documentsURL.appendingPathComponent(
434433
isDownloadingResources ? "resources.zip" : "firmware.zip")
@@ -441,32 +440,31 @@ extension DownloadManager: URLSessionDelegate, URLSessionDownloadDelegate {
441440
// move downloaded file out of ephemeral storage and tell DFU where to look
442441
try FileManager.default.moveItem(at: location, to: savedURL)
443442

444-
DispatchQueue.main.async {
445-
if self.isDownloadingResources && self.dfuUpdater.resourceURL == nil {
446-
self.dfuUpdater.resourceURL = savedURL
447-
self.hasDownloadedResources = true
443+
DispatchQueue.main.async { [self] in
444+
if isDownloadingResources && dfuUpdater.resourceURL == nil {
445+
dfuUpdater.resourceURL = savedURL
446+
hasDownloadedResources = true
448447
} else {
449-
self.dfuUpdater.firmwareURL = savedURL
448+
dfuUpdater.firmwareURL = savedURL
450449
}
451450
}
452451
} catch {
453452
log("Error downloading resource or firmware: \(error.localizedDescription)", caller: "DownloadManager")
454453
}
455454

456-
DispatchQueue.main.async {
457-
if !self.hasDownloadedResources && self.dfuUpdater.updateResourcesWithFirmware {
458-
self.isDownloadingResources = true
459-
self.startDownload(url: self.browserDownloadResourcesUrl)
455+
DispatchQueue.main.async { [self] in
456+
if !hasDownloadedResources && dfuUpdater.updateResourcesWithFirmware {
457+
isDownloadingResources = true
458+
startDownload(url: browserDownloadResourcesUrl)
460459
} else {
461-
if self.startTransfer {
462-
self.startTransfer = false
463-
self.dfuUpdater.isUpdating = true
464-
self.downloading = false
460+
if startTransfer {
461+
startTransfer = false
462+
downloading = false
465463

466-
if self.externalResources {
464+
if externalResources {
467465
BLEFSHandler.shared.uploadExternalResources {}
468466
} else {
469-
DFUUpdater.shared.downloadTransfer()
467+
dfuUpdater.downloadTransfer()
470468
}
471469
}
472470
}

InfiniLink/Utils/WeatherController.swift

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,18 @@ class WeatherController: ObservableObject {
1616

1717
@ObservedObject var deviceManager = DeviceManager.shared
1818

19-
@Published var weather: Weather?
20-
21-
@Published var errorWhileFetching: Error?
22-
2319
@AppStorage("latitude") var latitude: Double = 0.0
2420
@AppStorage("longitude") var longitude: Double = 0.0
2521

2622
@AppStorage("setLocation") var setLocation = "Cupertino"
2723

2824
@AppStorage("useCurrentLocation") var useCurrentLocation = true
2925

26+
@Published var weather: Weather?
27+
@Published var errorWhileFetching: Error?
3028
@Published var temperature = 0.0
3129
@Published var forecastDays = [DayWeather]()
30+
@Published var lastTimeWeatherFetched: Date?
3231

3332
private let service = WeatherService()
3433
private var locationManager = LocationManager.shared
@@ -70,12 +69,18 @@ class WeatherController: ObservableObject {
7069
}
7170

7271
func fetchWeatherData() {
72+
let guardInterval: TimeInterval = 600
73+
74+
// Make sure the weather has not been fetched in the past 5 minutes
75+
guard lastTimeWeatherFetched?.timeIntervalSinceNow ?? guardInterval >= guardInterval else { return }
76+
7377
let currentLocation = CLLocation(latitude: latitude, longitude: longitude)
7478

7579
Task {
7680
do {
7781
let weather = try await service.weather(for: currentLocation)
7882

83+
self.lastTimeWeatherFetched = Date()
7984
self.weather = weather
8085
self.forecastDays = Array(weather.dailyForecast.dropFirst().prefix(5))
8186

0 commit comments

Comments
 (0)