-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathFirmwareUpgradeManager.swift
1248 lines (1087 loc) · 50.2 KB
/
FirmwareUpgradeManager.swift
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017-2018 Runtime Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import CoreBluetooth
// MARK: - FirmwareUpgradeManager
public class FirmwareUpgradeManager : FirmwareUpgradeController, ConnectionObserver {
private let imageManager: ImageManager
private let defaultManager: DefaultManager
private let basicManager: BasicManager
private weak var delegate: FirmwareUpgradeDelegate?
/// Cyclic reference is used to prevent from releasing the manager
/// in the middle of an update. The reference cycle will be set
/// when upgrade was started and released on success, error or cancel.
private var cyclicReferenceHolder: (() -> FirmwareUpgradeManager)?
private var images: [FirmwareUpgradeImage]!
private var configuration: FirmwareUpgradeConfiguration!
private var state: FirmwareUpgradeState
private var paused: Bool
/// Logger delegate may be used to obtain logs.
public weak var logDelegate: McuMgrLogDelegate? {
didSet {
imageManager.logDelegate = logDelegate
defaultManager.logDelegate = logDelegate
}
}
private var resetResponseTime: Date?
//**************************************************************************
// MARK: Initializer
//**************************************************************************
public init(transporter: McuMgrTransport, delegate: FirmwareUpgradeDelegate?) {
self.imageManager = ImageManager(transporter: transporter)
self.defaultManager = DefaultManager(transporter: transporter)
self.basicManager = BasicManager(transporter: transporter)
self.delegate = delegate
self.state = .none
self.paused = false
}
//**************************************************************************
// MARK: Control Functions
//**************************************************************************
/// Start the firmware upgrade.
///
/// Use this convenience call of ``start(images:using:)`` if you're only
/// updating the App Core (i.e. no Multi-Image).
/// - parameter hash: The hash of the Image to be uploaded, used for comparison with the target firmware.
/// - parameter data: `Data` to upload to App Core (Image 0).
/// - parameter configuration: Fine-tuning of details regarding the upgrade process.
public func start(hash: Data, data: Data, using configuration: FirmwareUpgradeConfiguration = FirmwareUpgradeConfiguration()) throws {
try start(images: [ImageManager.Image(image: 0, hash: hash, data: data)],
using: configuration)
}
/// Start the firmware upgrade.
///
/// This is the full-featured API to start DFU update, including support for Multi-Image uploads.
/// - parameter images: An Array of (`ImageManager.Image`) to upload.
/// - parameter configuration: Fine-tuning of details regarding the upgrade process.
public func start(images: [ImageManager.Image], using configuration: FirmwareUpgradeConfiguration = FirmwareUpgradeConfiguration()) throws {
objc_sync_enter(self)
defer {
objc_sync_exit(self)
}
guard state == .none else {
log(msg: "Firmware upgrade is already in progress", atLevel: .warning)
return
}
self.images = try images.map { try FirmwareUpgradeImage($0) }
self.configuration = configuration
// Grab a strong reference to something holding a strong reference to self.
cyclicReferenceHolder = { return self }
log(msg: "Upgrade started with \(images.count) image(s) using '\(configuration.upgradeMode)' mode",
atLevel: .application)
if #available(iOS 10.0, watchOS 3.0, *) {
dispatchPrecondition(condition: .onQueue(.main))
} else {
assert(Thread.isMainThread)
}
delegate?.upgradeDidStart(controller: self)
requestMcuMgrParameters()
}
public func cancel() {
objc_sync_enter(self)
if state == .upload {
imageManager.cancelUpload()
paused = false
}
objc_sync_exit(self)
}
public func pause() {
objc_sync_enter(self)
if state.isInProgress() && !paused {
paused = true
if state == .upload {
imageManager.pauseUpload()
}
}
objc_sync_exit(self)
}
public func resume() {
objc_sync_enter(self)
if paused {
paused = false
currentState()
}
objc_sync_exit(self)
}
public func isPaused() -> Bool {
return paused
}
public func isInProgress() -> Bool {
return state.isInProgress() && !paused
}
public func setUploadMtu(mtu: Int) throws {
try imageManager.setMtu(mtu)
}
//**************************************************************************
// MARK: Firmware Upgrade State Machine
//**************************************************************************
private func objc_sync_setState(_ state: FirmwareUpgradeState) {
objc_sync_enter(self)
let previousState = self.state
self.state = state
if state != previousState {
DispatchQueue.main.async { [weak self] in
self?.delegate?.upgradeStateDidChange(from: previousState, to: state)
}
}
objc_sync_exit(self)
}
private func requestMcuMgrParameters() {
objc_sync_setState(.requestMcuMgrParameters)
if !paused {
log(msg: "Requesting McuMgr Parameters...", atLevel: .verbose)
defaultManager.params(callback: mcuManagerParametersCallback)
}
}
private func bootloaderInfo() {
objc_sync_setState(.bootloaderInfo)
if !paused {
log(msg: "Requesting Bootloader Info...", atLevel: .verbose)
defaultManager.bootloaderInfo(query: .mode, callback: bootloaderInfoCallback)
}
}
private func validate() {
objc_sync_setState(.validate)
if !paused {
log(msg: "Sending Image List command...", atLevel: .verbose)
imageManager.list(callback: listCallback)
}
}
private func upload() {
objc_sync_setState(.upload)
if !paused {
let imagesToUpload = images
.filter { !$0.uploaded }
.map { ImageManager.Image($0) }
guard !imagesToUpload.isEmpty else {
log(msg: "Nothing to be uploaded", atLevel: .application)
// Allow Library Apps to show 100% Progress in this case.
DispatchQueue.main.async { [weak self] in
self?.delegate?.uploadProgressDidChange(bytesSent: 100, imageSize: 100,
timestamp: Date())
}
uploadDidFinish()
return
}
for image in imagesToUpload {
let hash = (try? McuMgrImage(data: image.data).hash)
let hashString = hash?.hexEncodedString(options: [.prepend0x, .upperCase]) ?? "Unknown"
log(msg: "Scheduling upload (hash: \(hashString)) for image \(image.image) (slot: \(image.slot))", atLevel: .application)
}
_ = imageManager.upload(images: imagesToUpload, using: configuration, delegate: self)
}
}
private func test(_ image: FirmwareUpgradeImage) {
objc_sync_setState(.test)
if !paused {
log(msg: "Sending Image Test command for image \(image.image) (slot: \(image.slot))...", atLevel: .verbose)
imageManager.test(hash: [UInt8](image.hash), callback: testCallback)
}
}
private func confirm(_ image: FirmwareUpgradeImage) {
objc_sync_setState(.confirm)
if !paused {
log(msg: "Sending Image Confirm command to image \(image.image) (slot \(image.slot))...", atLevel: .verbose)
imageManager.confirm(hash: [UInt8](image.hash), callback: confirmCallback)
}
}
private func eraseAppSettings() {
objc_sync_setState(.eraseAppSettings)
log(msg: "Erasing app settings...", atLevel: .verbose)
basicManager.eraseAppSettings(callback: eraseAppSettingsCallback)
}
private func reset() {
objc_sync_setState(.reset)
if !paused {
log(msg: "Sending Reset command...", atLevel: .verbose)
defaultManager.transporter.addObserver(self)
defaultManager.reset(callback: resetCallback)
}
}
/**
Called in .test&Confirm mode after uploaded images have been sent 'Test' command, they
are tested, then Reset, and now we need to Confirm all Images.
*/
private func testAndConfirmAfterReset() {
if let untestedImage = images.first(where: { $0.uploaded && !$0.tested }) {
self.fail(error: FirmwareUpgradeError.untestedImageFound(image: untestedImage.image, slot: untestedImage.slot))
return
}
if let firstUnconfirmedImage = images.first(where: {
$0.uploaded && !$0.confirmed && !$0.confirmSent }
) {
confirm(firstUnconfirmedImage)
mark(firstUnconfirmedImage, as: \.confirmSent)
} else {
// in .testAndConfirm, we test all uploaded images before Reset.
// So if we're here after Reset and there's nothing to confirm, we're done.
self.success()
}
}
private func success() {
objc_sync_setState(.success)
objc_sync_enter(self)
defer {
objc_sync_exit(self)
}
state = .none
paused = false
DispatchQueue.main.async { [weak self] in
self?.delegate?.upgradeDidComplete()
// Release cyclic reference.
self?.cyclicReferenceHolder = nil
}
}
private func fail(error: Error) {
objc_sync_enter(self)
defer {
objc_sync_exit(self)
}
log(msg: error.localizedDescription, atLevel: .error)
let tmp = state
state = .none
paused = false
DispatchQueue.main.async { [weak self] in
self?.delegate?.upgradeDidFail(inState: tmp, with: error)
// Release cyclic reference.
self?.cyclicReferenceHolder = nil
}
}
private func currentState() {
objc_sync_enter(self)
defer {
objc_sync_exit(self)
}
if !paused {
switch state {
case .requestMcuMgrParameters:
requestMcuMgrParameters()
case .validate:
validate()
case .upload:
imageManager.continueUpload()
case .test:
guard let nextImageToTest = self.images.first(where: { $0.uploaded && !$0.tested }) else { return }
test(nextImageToTest)
mark(nextImageToTest, as: \.testSent)
case .reset:
reset()
case .confirm:
guard let nextImageToConfirm = self.images.first(where: { $0.uploaded && !$0.confirmed }) else { return }
confirm(nextImageToConfirm)
mark(nextImageToConfirm, as: \.confirmSent)
default:
break
}
}
}
// MARK: McuMgr Parameters Callback
/// Callback for devices running NCS firmware version 2.0 or later, which support McuMgrParameters call.
///
/// Error handling here is not considered important because we don't expect many devices to support this.
/// If this feature is not supported, the upload will take place with default parameters.
private lazy var mcuManagerParametersCallback: McuMgrCallback<McuMgrParametersResponse> = { [weak self] response, error in
guard let self = self else { return }
guard error == nil, let response, response.rc != 8 else {
self.log(msg: "Mcu Manager parameters not supported", atLevel: .warning)
self.bootloaderInfo() // Continue to Bootloader Info.
return
}
self.log(msg: "Mcu Manager parameters received (\(response.bufferCount) x \(response.bufferSize))", atLevel: .application)
if response.bufferSize > UInt16.max {
response.bufferSize = UInt64(UInt16.max)
self.log(msg: "Parameters SAR Buffer Size is larger than maximum of \(UInt16.max) bytes. Reducing Buffer Size to maximum value.", atLevel: .warning)
}
self.log(msg: "Setting SAR Buffer Size to \(response.bufferSize) bytes.", atLevel: .verbose)
self.configuration.reassemblyBufferSize = response.bufferSize
self.bootloaderInfo() // Continue to Bootloader Info.
}
// MARK: Bootloader Info Callback
private lazy var bootloaderInfoCallback: McuMgrCallback<BootloaderInfoResponse> = { [weak self] response, error in
guard let self = self else { return }
guard error == nil, let response, response.rc != 8 else {
self.log(msg: "Bootloader info not supported", atLevel: .warning)
self.validate() // Continue Upload
return
}
self.log(msg: "Bootloader info received (mode: \(response.mode?.debugDescription ?? "Unknown"))",
atLevel: .application)
self.configuration.bootloaderMode = response.mode ?? self.configuration.bootloaderMode
if self.configuration.bootloaderMode == .directXIPNoRevert {
// Mark all images as confirmed for DirectXIP No Revert, because there's no need.
// No Revert means we just Reset and the firmware will handle it.
for image in self.images {
self.mark(image, as: \.confirmed)
}
}
self.validate() // Continue Upload
}
// MARK: List Callback
/// Callback for the List (VALIDATE) state.
///
/// This callback will fail the upgrade on error and continue to the next
/// state on success.
private lazy var listCallback: McuMgrCallback<McuMgrImageStateResponse> = { [weak self] response, error in
// Ensure the manager is not released.
guard let self = self else { return }
// Check for an error.
if let error = error {
self.fail(error: error)
return
}
guard let response = response else {
self.fail(error: FirmwareUpgradeError.unknown("Image List response is nil."))
return
}
self.log(msg: "Image List response: \(response)", atLevel: .application)
// Check for an error return code.
if let error = response.getError() {
self.fail(error: error)
return
}
// Check that the image array exists.
guard let responseImages = response.images, responseImages.count > 0 else {
self.fail(error: FirmwareUpgradeError.invalidResponse(response))
return
}
var discardedImages: [FirmwareUpgradeImage] = []
// We need to loop over the indices, because we change the array from within it.
// So 'for image in self.images' would make each 'image' not reflect changes.
for i in self.images.indices {
let image = self.images[i]
guard !image.uploaded else { continue }
// Look for corresponding image.
let targetImage = responseImages.first(where: { $0.image == image.image })
// Regardless of where we'd upload the image (slot), if the hash
// matches then we don't need to do anything about it.
if let targetImage, Data(targetImage.hash) == image.hash {
self.targetSlotMatch(for: targetImage, to: image)
continue // next Image.
}
let imageForAlternativeSlotAvailable = self.images.first(where: {
$0.image == image.image && $0.slot != image.slot
})
// if (DirectXIP) basically
if let imageForAlternativeSlotAvailable {
// Do we need to upload this image?
if let alternativeAlreadyUploaded = responseImages.first(where: {
$0.image == image.image && $0.slot == imageForAlternativeSlotAvailable.slot
}), Data(alternativeAlreadyUploaded.hash) == imageForAlternativeSlotAvailable.hash {
self.log(msg: "Image \(image.image) has already been uploaded", atLevel: .debug)
for skipImage in self.images ?? [] where skipImage.image == image.image {
// Remove all Target Slot(s) for this Image.
discardedImages.append(skipImage)
// Mark as Uploaded so we skip it over in the for-loop.
self.mark(skipImage, as: \.uploaded)
}
continue
}
// If we have the same Image but targeted for a different slot (DirectXIP),
// we need to chose one of the two to upload.
if let activeResponseImage = responseImages.first(where: {
$0.image == image.image && $0.active
}), let activeImage = self.images.first(where: { $0.image == activeResponseImage.image && $0.slot == activeResponseImage.slot }) {
discardedImages.append(activeImage)
self.log(msg: "Two possible slots available. Image \(image.image) (slot: \(activeResponseImage.slot)) is active, uploading to the secondary slot", atLevel: .debug)
}
} else {
self.validateSecondarySlotUpload(of: image, with: responseImages)
}
}
// Remove discarded images.
self.images = self.images.filter({
!discardedImages.contains($0)
})
// Validation successful, begin with image upload.
self.upload()
}
private func targetSlotMatch(for responseImage: McuMgrImageStateResponse.ImageSlot,
to uploadImage: FirmwareUpgradeImage) {
// The image is already active in the desired slot.
// No need to upload it again.
mark(uploadImage, as: \.uploaded)
// If the image is already confirmed...
if responseImage.confirmed {
// ...there's no need to send any commands for this image.
log(msg: "Image: \(uploadImage.image) (slot: \(uploadImage.image)) already active", atLevel: .debug)
mark(uploadImage, as: \.confirmed)
mark(uploadImage, as: \.tested)
} else {
// Otherwise, the image must be in test mode.
log(msg: "Image \(uploadImage.image) (slot: \(uploadImage.image)) already active in Test Mode", atLevel: .debug)
mark(uploadImage, as: \.tested)
}
}
private func validateSecondarySlotUpload(of image: FirmwareUpgradeImage,
with responseImages: [McuMgrImageStateResponse.ImageSlot]) {
// Look for the corresponding image in the secondary slot.
if let secondary = responseImages.first(where: { $0.image == image.image && $0.slot == 1 }) {
// Check if the firmware has already been uploaded.
if Data(secondary.hash) == image.hash {
// Firmware is identical to the one in slot 1.
// No need to send anything.
mark(image, as: \.uploaded)
// If the image was already confirmed...
if secondary.permanent {
// ...check if we can continue.
// A confirmed image cannot be un-confirmed and made tested.
guard self.configuration.upgradeMode != .testOnly else {
fail(error: FirmwareUpgradeError.unknown("Image \(image.image) already confirmed. Can't be tested."))
return
}
log(msg: "Image \(image.image) (slot: \(secondary.slot)) already uploaded and confirmed", atLevel: .debug)
mark(image, as: \.confirmed)
return
}
// If the test command was sent to this image...
if secondary.pending {
// ...mark it as tested.
log(msg: "Image \(image.image) (slot: \(secondary.slot)) already uploaded and tested", atLevel: .debug)
mark(image, as: \.tested)
return
}
// Otherwise, the test or confirm commands will be sent later, depending on the mode.
log(msg: "Image \(image.image) already uploaded", atLevel: .debug)
} else {
// Seems like the secondary slot for this image number is already taken
// by some other firmware.
// If the image in secondary slot is confirmed, we won't be able to erase or
// test the slot. Therefore, we confirm the image in the core's primary slot
// to allow us to modify the image in the secondary slot.
if secondary.confirmed {
guard let primary = responseImages.first(where: {
$0.image == image.image && $0.slot == image.slot
}) else { return }
log(msg: "Secondary slot of image \(image.image) is already confirmed", atLevel: .warning)
log(msg: "Confirming image \(primary.image) (slot: \(primary.slot))...", atLevel: .verbose)
listConfirm(image: primary)
return
}
// If the image in secondary slot is pending, we won't be able to
// erase or test the slot. Therefore, we must reset the device
// (which will swap and run the test image) and revalidate the new image state.
if secondary.pending {
log(msg: "Image \(image.image) (slot \(secondary.slot)) is already pending", atLevel: .warning)
log(msg: "Resetting the device...", atLevel: .verbose)
// reset() can't be called here, as it changes the state to RESET.
defaultManager.transporter.addObserver(self)
defaultManager.reset(callback: self.resetCallback)
// The validate() method will be called again.
return
}
// Otherwise, do nothing, as the old firmware will be overwritten by the new one.
log(msg: "Secondary slot of image \(image.image) will be overwritten", atLevel: .warning)
}
}
}
private func listConfirm(image: McuMgrImageStateResponse.ImageSlot) {
imageManager.confirm(hash: image.hash) { [weak self] response, error in
guard let self = self else {
return
}
if let error = error {
self.fail(error: error)
return
}
guard let response = response else {
self.fail(error: FirmwareUpgradeError.unknown("Image Confirm response is nil."))
return
}
self.log(msg: "Image Confirm response: \(response)", atLevel: .application)
if let error = response.getError() {
self.fail(error: error)
return
}
// Check that the image array exists.
guard let responseImages = response.images, responseImages.count > 0 else {
self.fail(error: FirmwareUpgradeError.invalidResponse(response))
return
}
// TODO: Perhaps adding a check to verify if the image was indeed confirmed?
self.log(msg: "Image \(image.image) confirmed", atLevel: .debug)
self.listCallback(response, nil)
}
}
// MARK: Test Callback
/// Callback for the TEST state.
///
/// This callback will fail the upgrade on error and continue to the next
/// state on success.
private lazy var testCallback: McuMgrCallback<McuMgrImageStateResponse> = { [weak self] response, error in
// Ensure the manager is not released.
guard let self = self else {
return
}
// Check for an error.
if let error = error {
self.fail(error: error)
return
}
guard let response = response else {
self.fail(error: FirmwareUpgradeError.unknown("Image Test response is nil."))
return
}
self.log(msg: "Image Test response: \(response)", atLevel: .application)
// Check for McuMgrReturnCode error.
if let error = response.getError() {
self.fail(error: error)
return
}
// Check that the image array exists.
guard let responseImages = response.images else {
self.fail(error: FirmwareUpgradeError.invalidResponse(response))
return
}
// Check that we have the correct number of images in the responseImages array.
guard responseImages.count >= self.images.count else {
self.fail(error: FirmwareUpgradeError.unknown("Expected \(self.images.count) or more images, but received \(responseImages.count) instead."))
return
}
for image in self.images where !image.tested {
guard let targetSlot = responseImages.first(where: {
$0.image == image.image && Data($0.hash) == image.hash
}) else {
self.fail(error: FirmwareUpgradeError.unknown("No image \(image.image) (slot: \(image.slot)) in Test Response."))
return
}
// Check the target image is pending (i.e. test succeeded).
guard targetSlot.pending else {
// For every image we upload, we need to send it the TEST Command.
if image.tested && !image.testSent {
self.test(image)
self.mark(image, as: \.testSent)
return
}
// If we've sent it the TEST Command, the slot must be in pending state to pass test.
self.fail(error: FirmwareUpgradeError.unknown("Image \(image.image) (slot: \(image.slot)) was tested but it did not switch to a pending state."))
return
}
self.mark(image, as: \.tested)
}
// Test image succeeded. Begin device reset.
self.log(msg: "All Test commands sent", atLevel: .debug)
self.reset()
}
// MARK: Confirm Callback
/// Callback for the CONFIRM state.
///
/// This callback will fail the upload on error or move to the next state on
/// success.
private lazy var confirmCallback: McuMgrCallback<McuMgrImageStateResponse> = { [weak self] response, error in
// Ensure the manager is not released.
guard let self else { return }
// Check for an error.
if let error {
self.fail(error: error)
return
}
guard let response else {
self.fail(error: FirmwareUpgradeError.unknown("Image Confirm response is nil."))
return
}
self.log(msg: "Image Confirm response: \(response)", atLevel: .application)
// Check for McuMgrReturnCode error.
if let error = response.getError() {
self.fail(error: error)
return
}
// Check that the image array exists.
guard let responseImages = response.images, responseImages.count > 0 else {
self.fail(error: FirmwareUpgradeError.invalidResponse(response))
return
}
for image in self.images where !image.confirmed {
switch self.configuration.upgradeMode {
case .confirmOnly:
guard let targetSlot = responseImages.first(where: {
$0.image == image.image && Data($0.hash) == image.hash
}) else {
// Let's try the alternative slot...
guard let _ = responseImages.first(where: { $0.image == image.image && $0.slot != image.slot }) else {
self.fail(error: FirmwareUpgradeError.invalidResponse(response))
return
}
self.mark(image, as: \.confirmed)
continue
}
// Check that the new image is in permanent state.
guard targetSlot.permanent else {
// If a TEST command was sent before for the image that is to be confirmed we have to reset.
// It is not possible to confirm such image until the device is reset.
// A new DFU operation has to be performed to confirm the image.
guard !targetSlot.pending else {
continue
}
if !image.confirmed {
if image.confirmSent {
self.fail(error: FirmwareUpgradeError.unknown("Image \(targetSlot.image) (slot: \(targetSlot.slot)) was confirmed, but did not switch to permanent state."))
} else {
self.confirm(image)
self.mark(image, as: \.confirmSent)
}
}
return
}
self.mark(image, as: \.confirmed)
case .testAndConfirm:
if let targetSlot = responseImages.first(where: {
$0.image == image.image && Data($0.hash) == image.hash
}) {
if targetSlot.active || targetSlot.permanent {
// Image booted. All okay.
self.mark(image, as: \.confirmed)
continue
}
if image.confirmSent && !targetSlot.confirmed {
self.fail(error: FirmwareUpgradeError.unknown("Image \(targetSlot.image) (slot: \(targetSlot.slot)) was confirmed, but did not switch to permanent state."))
return
}
self.mark(image, as: \.confirmed)
}
case .testOnly, .uploadOnly:
// Impossible state. Ignore.
return
}
}
self.log(msg: "Upgrade complete", atLevel: .application)
switch self.configuration.upgradeMode {
case .confirmOnly:
self.reset()
case .testAndConfirm:
// No need to reset again.
self.success()
case .testOnly, .uploadOnly:
// Impossible!
return
}
}
// MARK: Erase App Settings Callback
private lazy var eraseAppSettingsCallback: McuMgrCallback<McuMgrResponse> = { [weak self] response, error in
guard let self = self else { return }
if let error = error as? McuMgrTransportError {
// Some devices will not even reply to Erase App Settings. So just move on.
if McuMgrTransportError.sendFailed == error {
self.finishedEraseAppSettings()
} else {
self.fail(error: error)
}
return
}
guard let response = response else {
self.fail(error: FirmwareUpgradeError.unknown("Erase app settings response is nil."))
return
}
switch response.result {
case .success:
self.log(msg: "App settings erased", atLevel: .application)
case .failure:
// rc != 0 is OK, meaning that this feature is not supported. DFU should continue.
self.log(msg: "Erasing app settings not supported", atLevel: .warning)
}
self.finishedEraseAppSettings()
}
private func finishedEraseAppSettings() {
// Set to false so uploadDidFinish() doesn't loop forever.
self.configuration.eraseAppSettings = false
self.uploadDidFinish()
}
// MARK: Reset Callback
/// Callback for the RESET state.
///
/// This callback will fail the upgrade on error. On success, the reset
/// poller will be started after a 3 second delay.
private lazy var resetCallback: McuMgrCallback<McuMgrResponse> = { [weak self] response, error in
// Ensure the manager is not released.
guard let self = self else {
return
}
// Check for an error.
if let error = error {
self.fail(error: error)
return
}
guard let response = response else {
self.fail(error: FirmwareUpgradeError.unknown("Reset response is nil."))
return
}
// Check for McuMgrReturnCode error.
if let error = response.getError() {
self.fail(error: error)
return
}
self.resetResponseTime = Date()
self.log(msg: "Reset request confirmed", atLevel: .info)
self.log(msg: "Waiting for disconnection...", atLevel: .verbose)
}
public func transport(_ transport: McuMgrTransport, didChangeStateTo state: McuMgrTransportState) {
transport.removeObserver(self)
// Disregard connected state.
guard state == .disconnected else {
return
}
self.log(msg: "Device has disconnected", atLevel: .info)
let timeSinceReset: TimeInterval
if let resetResponseTime = resetResponseTime {
let now = Date()
timeSinceReset = now.timeIntervalSince(resetResponseTime)
} else {
// Fallback if state changed prior to `resetResponseTime` is set.
timeSinceReset = 0
}
let remainingTime = configuration.estimatedSwapTime - timeSinceReset
// If DirectXIP, regardless of variant, there's no swap time. So we try to reconnect
// immediately.
let waitForReconnectRequired = !configuration.bootloaderMode.isDirectXIP
&& remainingTime > .leastNonzeroMagnitude
guard waitForReconnectRequired else {
reconnect()
return
}
self.log(msg: "Waiting \(Int(configuration.estimatedSwapTime)) seconds reconnecting...", atLevel: .info)
DispatchQueue.main.asyncAfter(deadline: .now() + remainingTime) { [weak self] in
self?.log(msg: "Reconnecting...", atLevel: .info)
self?.reconnect()
}
}
/// Reconnect to the device and continue the
private func reconnect() {
imageManager.transporter.connect { [weak self] result in
guard let self = self else {
return
}
switch result {
case .connected:
self.log(msg: "Reconnect successful", atLevel: .info)
case .deferred:
self.log(msg: "Reconnect deferred", atLevel: .info)
case .failed(let error):
self.log(msg: "Reconnect failed: \(error)", atLevel: .error)
self.fail(error: error)
return
}
// Continue the upgrade after reconnect.
switch self.state {
case .requestMcuMgrParameters:
self.requestMcuMgrParameters()
case .validate:
self.validate()
case .reset:
switch self.configuration.upgradeMode {
case .testAndConfirm:
self.testAndConfirmAfterReset()
default:
self.log(msg: "Upgrade complete", atLevel: .application)
self.success()
}
default:
break
}
}
}
// MARK: State
private func mark(_ image: FirmwareUpgradeImage, as key: WritableKeyPath<FirmwareUpgradeImage, Bool>) {
guard let i = images.firstIndex(of: image) else { return }
images[i][keyPath: key] = true
}
}
private extension FirmwareUpgradeManager {
func log(msg: @autoclosure () -> String, atLevel level: McuMgrLogLevel) {
if let logDelegate, level >= logDelegate.minLogLevel() {
logDelegate.log(msg(), ofCategory: .dfu, atLevel: level)
}
}
}
// MARK: - FirmwareUpgradeConfiguration
public struct FirmwareUpgradeConfiguration: Codable {
/**
Estimated time required for swapping images, in seconds.
If the mode is set to `.testAndConfirm`, the manager will try to reconnect after this time. 0 by default.
Note: This setting is ignored if `bootloaderMode` is in any DirectXIP variant, since there's no swap whatsoever when DirectXIP is involved. Hence, why we can upload the same Image (though different hash) to either slot.
*/
public var estimatedSwapTime: TimeInterval
/// If enabled, after successful upload but before test/confirm/reset phase, an Erase App Settings Command will be sent and awaited before proceeding.
public var eraseAppSettings: Bool
/// If set to a value larger than 1, this enables SMP Pipelining, wherein multiple packets of data ('chunks') are sent at once before awaiting a response, which can lead to a big increase in transfer speed if the receiving hardware supports this feature.
public var pipelineDepth: Int
/// Necessary to set when Pipeline Length is larger than 1 (SMP Pipelining Enabled) to predict offset jumps as multiple
/// packets are sent.
public var byteAlignment: ImageUploadAlignment
/// If set, it is used instead of the MTU Size as the maximum size of the packet. It is designed to be used with a size
/// larger than the MTU, meaning larger Data chunks per Sequence Number, trusting the reassembly Buffer on the receiving
/// side to merge it all back. Thus, increasing transfer speeds.
///
/// Can be used in conjunction with SMP Pipelining.
///
/// **Cannot exceed `UInt16.max` value of 65535.**
public var reassemblyBufferSize: UInt64
/// Previously set directly in `FirmwareUpgradeManager`, it has since been moved here, to the Configuration. It modifies the steps after `upload` step in Firmware Upgrade that need to be performed for the Upgrade process to be considered Successful.
public var upgradeMode: FirmwareUpgradeMode
/// Provides valuable information regarding how the target device is set up to switch over to the new firmware being uploaded, if available.
///
/// For example, in DirectXIP, some bootloaders will not accept a 'CONFIRM' Command and return an Error
/// that could make the DFU Library return an Error. When in reality, what the target bootloader wants
/// is just to receive a 'RESET' Command instead to conclude the process.
///
/// Set to `.Unknown` by default, since BootloaderInfo is a new addition for NCS 2.5 / SMPv2.
public var bootloaderMode: BootloaderInfoResponse.Mode
/**
SUIT (Software Update for Internet of Things) Images don't support many McuMgr Commands,
like Reset. And 'Upgrade Modes' don't make sense for it either. We want to keep the same
frontend API but we need our backened to know to ignore things such as RESET for SUIT. We
wanted to add a new UpgradeMode, but that was going to cause other issues. So instead, this
toggle is the solution.
*/
public var suitMode: Bool
/// SMP Pipelining is considered Enabled for `pipelineDepth` values larger than `1`.
public var pipeliningEnabled: Bool {
return pipelineDepth > 1
}
public init(estimatedSwapTime: TimeInterval = 0.0, eraseAppSettings: Bool = true, pipelineDepth: Int = 1,
byteAlignment: ImageUploadAlignment = .disabled, reassemblyBufferSize: UInt64 = 0,
upgradeMode: FirmwareUpgradeMode = .confirmOnly,
bootloaderMode: BootloaderInfoResponse.Mode = .unknown, suitMode: Bool = false) {
self.estimatedSwapTime = estimatedSwapTime
self.eraseAppSettings = eraseAppSettings
self.pipelineDepth = pipelineDepth
self.byteAlignment = byteAlignment
self.reassemblyBufferSize = min(reassemblyBufferSize, UInt64(UInt16.max))
self.upgradeMode = upgradeMode
self.bootloaderMode = bootloaderMode
self.suitMode = false
}
}
//******************************************************************************
// MARK: - ImageUploadDelegate
//******************************************************************************
extension FirmwareUpgradeManager: ImageUploadDelegate {
public func uploadProgressDidChange(bytesSent: Int, imageSize: Int, timestamp: Date) {
if bytesSent == imageSize {
// An Image was sent. Mark as uploaded.
if let image = self.images.first(where: { !$0.uploaded && $0.data.count == imageSize }) {
self.mark(image, as: \.uploaded)
}
}
DispatchQueue.main.async { [weak self] in
self?.delegate?.uploadProgressDidChange(bytesSent: bytesSent, imageSize: imageSize, timestamp: timestamp)
}
}
public func uploadDidFail(with error: Error) {
// If the upload fails, fail the upgrade.
fail(error: error)
}
public func uploadDidCancel() {
DispatchQueue.main.async { [weak self] in
self?.delegate?.upgradeDidCancel(state: .none)
}