-
Notifications
You must be signed in to change notification settings - Fork 37
/
ImageManager.swift
761 lines (671 loc) · 30.7 KB
/
ImageManager.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
/*
* Copyright (c) 2017-2018 Runtime Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import CoreBluetooth
import SwiftCBOR
// MARK: - ImageManager
public class ImageManager: McuManager {
// MARK: Image
public struct Image {
public let image: Int
public let slot: Int
public let hash: Data
public let data: Data
/**
All of the previous code / modes target `slot` 1 (Secondary) as where they
want the image uploaded, so that's the default. Only DirectXIP would
target `slot` 0 (Primary) for upload.
*/
public init(image: Int, slot: Int = 1, hash: Data, data: Data) {
self.image = image
self.slot = slot
self.hash = hash
self.data = data
}
public init(_ manifest: McuMgrManifest.File, hash: Data, data: Data) {
self.image = manifest.image
self.slot = manifest.slot
self.hash = hash
self.data = data
}
internal init(_ image: FirmwareUpgradeImage) {
self.image = image.image
self.slot = image.slot
self.hash = image.hash
self.data = image.data
}
}
override class var TAG: McuMgrLogCategory { .image }
private static let PIPELINED_WRITES_TIMEOUT_SECONDS = 10
// MARK: - IDs
enum ImageID: UInt8 {
case state = 0
case upload = 1
case file = 2
case coreList = 3
case coreLoad = 4
case erase = 5
case eraseState = 6
}
//**************************************************************************
// MARK: Initializers
//**************************************************************************
public init(transporter: McuMgrTransport) {
super.init(group: McuMgrGroup.image, transporter: transporter)
}
//**************************************************************************
// MARK: Commands
//**************************************************************************
/// List the images on the device.
///
/// - parameter callback: The response callback.
public func list(callback: @escaping McuMgrCallback<McuMgrImageStateResponse>) {
send(op: .read, commandId: ImageID.state, payload: nil, callback: callback)
}
/// Sends the next packet of data from given offset.
/// To send a complete image, use upload(data:image:delegate) method instead.
///
/// - parameter data: The image data.
/// - parameter image: The image number / slot number for DFU.
/// - parameter offset: The offset from which this data will be sent.
/// - parameter alignment: The byte alignment to apply to the data (if any).
/// - parameter callback: The callback.
public func upload(data: Data, image: Int, offset: UInt64, alignment: ImageUploadAlignment,
callback: @escaping McuMgrCallback<McuMgrUploadResponse>) {
let payloadLength = maxDataPacketLengthFor(data: data, image: image, offset: offset)
let chunkOffset = offset
let chunkEnd = min(chunkOffset + payloadLength, UInt64(data.count))
var payload: [String:CBOR] = ["data": CBOR.byteString([UInt8](data[chunkOffset..<chunkEnd])),
"off": CBOR.unsignedInt(chunkOffset)]
let uploadTimeoutInSeconds: Int
if chunkOffset == 0 {
// 0 is Default behavior, so we can ignore adding it and
// the firmware will do the right thing.
if image > 0 {
payload.updateValue(CBOR.unsignedInt(UInt64(image)), forKey: "image")
}
payload.updateValue(CBOR.unsignedInt(UInt64(data.count)), forKey: "len")
payload.updateValue(CBOR.byteString([UInt8](data.sha256())), forKey: "sha")
// When uploading offset 0, we might trigger an erase on the firmware's end.
// Hence, the longer timeout.
uploadTimeoutInSeconds = McuManager.DEFAULT_SEND_TIMEOUT_SECONDS
} else {
uploadTimeoutInSeconds = McuManager.FAST_TIMEOUT
}
send(op: .write, commandId: ImageID.upload, payload: payload, timeout: uploadTimeoutInSeconds,
callback: callback)
uploadExpectedOffsets.append(chunkEnd)
}
/// Test the image with the provided hash.
///
/// A successful test will put the image in a pending state. A pending image
/// will be booted upon once upon reset, but not again unless confirmed.
///
/// - parameter hash: The hash of the image to test.
/// - parameter callback: The response callback.
public func test(hash: [UInt8], callback: @escaping McuMgrCallback<McuMgrImageStateResponse>) {
let payload: [String:CBOR] = ["hash": CBOR.byteString(hash),
"confirm": CBOR.boolean(false)]
send(op: .write, commandId: ImageID.state, payload: payload, callback: callback)
}
/// Confirm the image with the provided hash.
///
/// A successful confirm will make the image permanent (i.e. the image will
/// be booted upon reset).
///
/// - parameter hash: The hash of the image to confirm. If not provided, the
/// current image running on the device will be made permanent.
/// - parameter callback: The response callback.
public func confirm(hash: [UInt8]? = nil, callback: @escaping McuMgrCallback<McuMgrImageStateResponse>) {
var payload: [String:CBOR] = ["confirm": CBOR.boolean(true)]
if let hash = hash {
payload.updateValue(CBOR.byteString(hash), forKey: "hash")
}
send(op: .write, commandId: ImageID.state, payload: payload, callback: callback)
}
/// Begins the image upload to a peripheral.
///
/// An instance of ImageManager can only have one upload in progress at a
/// time, but we support uploading multiple images in a single call. If
/// this method is called multiple times on the same ImageManager instance,
/// all calls after the first will return false. Upload progress is reported
/// asynchronously to the delegate provided in this method.
///
/// - parameter images: The images to upload.
/// - parameter configuration: The parameters used during the upgrade process. Set with defaults if not provided.
/// - parameter delegate: The delegate to receive progress callbacks.
///
/// - returns: True if the upload has started successfully, false otherwise.
public func upload(images: [Image], using configuration: FirmwareUpgradeConfiguration = FirmwareUpgradeConfiguration(),
delegate: ImageUploadDelegate?) -> Bool {
// Make sure two uploads cant start at once.
objc_sync_enter(self)
defer {
objc_sync_exit(self)
}
// If upload is already in progress or paused, do not continue.
if uploadState == .none {
// Set upload flag to true.
uploadState = .uploading
} else {
log(msg: "An image upload is already in progress", atLevel: .warning)
return false
}
guard let firstImage = images.first else {
log(msg: "Nothing to upload", atLevel: .warning)
return false
}
// Set upload delegate.
uploadDelegate = delegate
uploadImages = images
// Set image data.
imageData = firstImage.data
// Set the slot we're uploading the image to.
// Grab a strong reference to something holding a strong reference to self.
cyclicReferenceHolder = { return self }
uploadIndex = 0
uploadExpectedOffsets = []
uploadLastOffset = 0
// Note that pipelining requires the use of byte-alignment, otherwise we
// can't predict how many bytes the firmware will accept in each chunk.
uploadConfiguration = configuration
// Don't exceed UInt16.max payload size.
uploadConfiguration.reassemblyBufferSize = min(uploadConfiguration.reassemblyBufferSize, UInt64(UInt16.max))
if let bleTransport = transporter as? McuMgrBleTransport {
bleTransport.numberOfParallelWrites = configuration.pipelineDepth
bleTransport.chunkSendDataToMtuSize = configuration.reassemblyBufferSize != 0
}
log(msg: "Uploading Image \(firstImage.image) with Target Slot \(firstImage.slot) (\(firstImage.data.count) bytes)...", atLevel: .verbose)
upload(data: firstImage.data, image: firstImage.image, offset: 0,
alignment: configuration.byteAlignment,
callback: uploadCallback)
return true
}
/// Erases an unused image from the secondary image slot on the device.
///
/// The image cannot be erased if the image is a confirmed image, is marked
/// for test on the next reboot, or is an active image for a split image
/// setup.
///
/// - parameter callback: The response callback.
public func erase(callback: @escaping McuMgrCallback<McuMgrResponse>) {
send(op: .write, commandId: ImageID.erase, payload: nil, callback: callback)
}
/// Erases the state of the secondary image slot on the device.
///
/// - parameter callback: The response callback.
public func eraseState(callback: @escaping McuMgrCallback<McuMgrResponse>) {
send(op: .write, commandId: ImageID.eraseState, payload: nil, callback: callback)
}
/// Request core dump on the device. The data will be stored in the dump
/// area.
///
/// - parameter callback: The response callback.
public func coreList(callback: @escaping McuMgrCallback<McuMgrResponse>) {
send(op: .read, commandId: ImageID.coreList, payload: nil, callback: callback)
}
/// Read core dump from the given offset.
///
/// - parameter offset: The offset to load from, in bytes.
/// - parameter callback: The response callback.
public func coreLoad(offset: UInt, callback: @escaping McuMgrCallback<McuMgrCoreLoadResponse>) {
let payload: [String:CBOR] = ["off": CBOR.unsignedInt(UInt64(offset))]
send(op: .read, commandId: ImageID.coreLoad, payload: payload, callback: callback)
}
/// Erase the area if it has a core dump, or the header is empty.
///
/// - parameter callback: The response callback.
public func coreErase(callback: @escaping McuMgrCallback<McuMgrResponse>) {
send(op: .write, commandId: ImageID.coreLoad, payload: nil, callback: callback)
}
//**************************************************************************
// MARK: Image Upload
//**************************************************************************
/// Image upload states
public enum UploadState: UInt8 {
case none = 0
case uploading = 1
case paused = 2
}
/// State of the image upload.
private var uploadState: UploadState = .none
/// Contains the current Image's data to send to the device.
private var imageData: Data?
/// Image 'slot' or core of the device we're sending data to.
/// Default value, will be secondary slot of core 0.
private var uploadIndex: Int = 0
/// Current image byte offset to send from.
private var uploadLastOffset: UInt64!
private var uploadExpectedOffsets: [UInt64] = []
/// The sequence of images we want to send to the device.
private var uploadImages: [Image]?
/// Delegate to send image upload updates to.
private weak var uploadDelegate: ImageUploadDelegate?
/// Groups multiple Settings regarding DFU Upload, such as enabling Pipelining,
/// Byte Alignment and/or SMP Reassembly.
private var uploadConfiguration: FirmwareUpgradeConfiguration!
/// Cyclic reference is used to prevent from releasing the manager
/// in the middle of an update. The reference cycle will be set
/// when upload was started and released on success, error or cancel.
private var cyclicReferenceHolder: (() -> ImageManager)?
/// Cancels the current upload.
///
/// If an error is supplied, the delegate's didFailUpload method will be
/// called with the Upload Error provided.
///
/// - parameter error: The optional upload error which caused the
/// cancellation. This error (if supplied) is used as the argument for the
/// delegate's didFailUpload method.
public func cancelUpload(error: Error? = nil) {
objc_sync_enter(self)
if uploadState == .none {
log(msg: "Image upload is not in progress", atLevel: .warning)
} else {
if let error = error {
resetUploadVariables()
uploadDelegate?.uploadDidFail(with: error)
uploadDelegate = nil
log(msg: "Upload cancelled due to error: \(error)", atLevel: .error)
// Release cyclic reference.
cyclicReferenceHolder = nil
} else {
if uploadState == .paused {
resetUploadVariables()
uploadDelegate?.uploadDidCancel()
uploadDelegate = nil
log(msg: "Upload cancelled", atLevel: .application)
// Release cyclic reference.
cyclicReferenceHolder = nil
}
// else
// Transfer will be cancelled after the next notification is received.
}
uploadState = .none
}
objc_sync_exit(self)
}
/// Pauses the current upload. If there is no upload in progress, nothing
/// happens.
public func pauseUpload() {
objc_sync_enter(self)
if uploadState == .none {
log(msg: "Upload is not in progress and therefore cannot be paused", atLevel: .warning)
} else {
uploadState = .paused
log(msg: "Upload paused", atLevel: .application)
}
objc_sync_exit(self)
}
/// Continues a paused upload. If the upload is not paused or not uploading,
/// nothing happens.
public func continueUpload() {
objc_sync_enter(self)
guard let imageData = imageData else {
objc_sync_exit(self)
if uploadState != .none {
cancelUpload(error: ImageUploadError.invalidData)
}
return
}
if uploadState == .paused {
let image: Int! = self.uploadImages?[uploadIndex].image
uploadState = .uploading
let offset = uploadLastOffset ?? 0
log(msg: "Resuming uploading image \(image) from \(offset)/\(imageData.count)...", atLevel: .application)
upload(data: imageData, image: image, offset: offset, alignment: uploadConfiguration.byteAlignment,
callback: uploadCallback)
} else {
log(msg: "Upload has not been previously paused", atLevel: .warning)
}
objc_sync_exit(self)
}
// MARK: - Image Upload Private Methods
private lazy var uploadCallback: McuMgrCallback<McuMgrUploadResponse> = {
[weak self] (response: McuMgrUploadResponse?, error: Error?) in
// Ensure the manager is not released.
guard let self else { return }
if #available(iOS 10.0, watchOS 3.0, *) {
dispatchPrecondition(condition: .onQueue(.main))
}
// Check for an error.
if let error {
if case let McuMgrTransportError.insufficientMtu(newMtu) = error {
do {
try self.setMtu(newMtu)
self.restartUpload()
} catch let mtuResetError {
self.cancelUpload(error: mtuResetError)
}
return
}
self.cancelUpload(error: error)
return
}
// If response includes 'match' value, it should be true.
// Else, we assume everything is OK.
guard response?.match ?? true else {
self.cancelUpload(error: ImageUploadError.offsetMismatch)
return
}
// Make sure the image data is set.
guard let currentImageData = self.imageData, let images = self.uploadImages else {
self.cancelUpload(error: ImageUploadError.invalidData)
return
}
// Make sure the response is not nil.
guard let response else {
self.cancelUpload(error: ImageUploadError.invalidPayload)
return
}
if let error = response.getError() {
self.cancelUpload(error: error)
return
}
if let offset = response.off {
// We expect In-Order Responses.
if self.uploadExpectedOffsets.contains(offset) {
self.uploadLastOffset = max(self.uploadLastOffset, UInt64(offset))
} else {
// Offset Mismatch.
self.uploadLastOffset = offset
if !self.uploadExpectedOffsets.isEmpty {
self.uploadExpectedOffsets.removeFirst()
}
// All of our previous 'sends' are invalid.
// Wait for all of them to return and then continue.
guard self.uploadExpectedOffsets.isEmpty else {
return
}
}
self.uploadExpectedOffsets.removeAll(where: { $0 <= offset })
self.uploadDelegate?.uploadProgressDidChange(bytesSent: Int(self.uploadLastOffset), imageSize: currentImageData.count, timestamp: Date())
self.log(msg: "Response Offset: \(offset), UploadOffset: \(self.uploadLastOffset), Pending Offsets: \(self.uploadExpectedOffsets.map({ $0 })), ",
atLevel: .debug)
if self.uploadState == .none {
self.log(msg: "Upload cancelled", atLevel: .application)
self.resetUploadVariables()
self.uploadDelegate?.uploadDidCancel()
self.uploadDelegate = nil
// Release cyclic reference.
self.cyclicReferenceHolder = nil
return
}
guard self.uploadState == .uploading else { return }
// Check if the upload has completed.
if offset == currentImageData.count {
if self.uploadIndex == images.count - 1 {
self.log(msg: "Upload finished (\(self.uploadIndex + 1) of \(images.count))", atLevel: .application)
self.resetUploadVariables()
self.uploadDelegate?.uploadDidFinish()
self.uploadDelegate = nil
// Release cyclic reference.
self.cyclicReferenceHolder = nil
} else {
self.uploadDelegate?.uploadProgressDidChange(
bytesSent: images[self.uploadIndex].data.count,
imageSize: images[self.uploadIndex].data.count,
timestamp: Date())
self.log(msg: "Uploaded image \(images[self.uploadIndex].image) (\(self.uploadIndex + 1) of \(images.count))", atLevel: .application)
// Don't trigger writes to another image unless all write(s) have returned for
// the current one.
guard self.uploadExpectedOffsets.isEmpty else {
return
}
// Move on to the next image.
self.uploadIndex += 1
self.uploadLastOffset = 0
self.imageData = images[self.uploadIndex].data
self.log(msg: "Uploading image \(images[self.uploadIndex].image) with Target Slot \(images[self.uploadIndex].slot) (\(self.imageData?.count) bytes)...", atLevel: .application)
self.uploadDelegate?.uploadProgressDidChange(bytesSent: 0, imageSize: images[self.uploadIndex].data.count, timestamp: Date())
self.sendNext(from: UInt64(0))
}
return
}
let currentImageDataSize = self.imageData?.count ?? 0
for i in 0..<(self.uploadConfiguration.pipelineDepth - self.uploadExpectedOffsets.count) {
guard let chunkOffset = self.uploadExpectedOffsets.last ?? self.uploadLastOffset,
chunkOffset < currentImageData.count else {
// No remaining chunks to be sent?
self.log(msg: "No remaining chunks to be sent? chunkOffset: \(self.uploadExpectedOffsets.last ?? self.uploadLastOffset), imageData: \(currentImageDataSize).", atLevel: .warning)
return
}
self.sendNext(from: chunkOffset)
}
} else {
self.cancelUpload(error: ImageUploadError.invalidPayload)
}
}
private func sendNext(from offset: UInt64) {
let imageData: Data! = self.uploadImages?[uploadIndex].data
let imageSlot: Int! = self.uploadImages?[uploadIndex].image
upload(data: imageData, image: imageSlot, offset: offset,
alignment: uploadConfiguration.byteAlignment,
callback: uploadCallback)
}
private func resetUploadVariables() {
objc_sync_enter(self)
// Reset upload state.
uploadState = .none
// Deallocate and nil image data pointers.
imageData = nil
uploadImages = nil
// Reset upload vars.
uploadIndex = 0
uploadExpectedOffsets = []
objc_sync_exit(self)
}
private func restartUpload() {
objc_sync_enter(self)
guard let uploadImages = uploadImages, let uploadDelegate = uploadDelegate else {
log(msg: "Could not restart upload: image data or callback is null", atLevel: .error)
return
}
let tempUploadImages = uploadImages
let tempUploadIndex = uploadIndex
let tempDelegate = uploadDelegate
resetUploadVariables()
let remainingImages = tempUploadImages.filter({ $0.image >= tempUploadIndex })
_ = upload(images: remainingImages, using: uploadConfiguration, delegate: tempDelegate)
objc_sync_exit(self)
}
private func maxDataPacketLengthFor(data: Data, image: Int, offset: UInt64) -> UInt64 {
guard offset < data.count else { return UInt64(McuMgrHeader.HEADER_LENGTH) }
let remainingBytes = UInt64(data.count) - offset
let packetOverhead = calculatePacketOverhead(data: data, image: image, offset: UInt64(offset))
let maxPacketSize = max(uploadConfiguration.reassemblyBufferSize, UInt64(mtu))
var maxDataLength = maxPacketSize - UInt64(packetOverhead)
if uploadConfiguration.byteAlignment != .disabled {
maxDataLength = (maxDataLength / uploadConfiguration.byteAlignment.rawValue) * uploadConfiguration.byteAlignment.rawValue
}
return min(maxDataLength, remainingBytes)
}
private func calculatePacketOverhead(data: Data, image: Int, offset: UInt64) -> Int {
// Get the Mcu Manager header.
var payload: [String:CBOR] = ["data": CBOR.byteString([UInt8]([0])),
"off": CBOR.unsignedInt(offset)]
// If this is the initial packet we have to include the length of the
// entire image.
if offset == 0 {
if image > 0 {
payload.updateValue(CBOR.unsignedInt(UInt64(image)), forKey: "image")
}
payload.updateValue(CBOR.unsignedInt(UInt64(data.count)), forKey: "len")
payload.updateValue(CBOR.byteString([UInt8](data.sha256())), forKey: "sha")
}
// Build the packet and return the size.
let packet = McuManager.buildPacket(scheme: transporter.getScheme(), version: .SMPv2, op: .write,
flags: 0, group: group.rawValue, sequenceNumber: 0,
commandId: ImageID.upload, payload: payload)
var packetOverhead = packet.count + 5
if transporter.getScheme().isCoap() {
// Add 25 bytes to packet overhead estimate for the CoAP header.
packetOverhead = packetOverhead + 25
}
return packetOverhead
}
}
// MARK: - ImageUploadAlignment
public enum ImageUploadAlignment: UInt64, Codable, CaseIterable, CustomDebugStringConvertible {
case disabled = 0
case twoByte = 2
case fourByte = 4
case eightByte = 8
case sixteenByte = 16
public var debugDescription: String {
guard self != .disabled else { return "disabled" }
return "\(rawValue)-byte"
}
}
// MARK: - ImageUploadError
public enum ImageUploadError: Error, LocalizedError {
/// Response payload values do not exist.
case invalidPayload
/// Image Data is nil.
case invalidData
/// Response payload reports package offset does not match expected value.
case offsetMismatch
case invalidUploadSequenceNumber(McuSequenceNumber)
public var errorDescription: String? {
switch self {
case .invalidPayload:
return "Response payload values do not exist"
case .invalidData:
return "Image data is nil"
case .offsetMismatch:
return "Response payload reports package offset does not match expected value"
case .invalidUploadSequenceNumber(let sequenceNumber):
return "Received Response for unknown Sequence Number \(sequenceNumber)"
}
}
}
// MARK: - ImageManagerError
public enum ImageManagerError: UInt64, Error, LocalizedError {
case noError = 0
case unknown = 1
case flashConfigurationQueryFailure = 2
case noImage = 3
case noTLVs = 4
case invalidTLV = 5
case tlvHashCollision = 6
case tlvInvalidSize = 7
case hashNotFound = 8
case fullSlots = 9
case flashOpenFailed = 10
case flashReadFailed = 11
case flashWriteFailed = 12
case flashEraseFailed = 13
case invalidSlot = 14
case mallocFailed = 15
case flashContextAlreadySet = 16
case flashContextNotSet = 17
case flashAreaNull = 18
case invalidPageOffset = 19
case missingOffset = 20
case missingLength = 21
case invalidImageHeader = 22
case invalidImageHeaderMagic = 23
case invalidHash = 24
case invalidFlashAddress = 25
case versionGetFailed = 26
case newerCurrentVersion = 27
case imageAlreadyPending = 28
case invalidImageVectorTable = 29
case invalidImageTooLarge = 30
case invalidImageDataOverrun = 31
case imageConfirmationDenied = 32
case imageSettingTestToActiveDenied = 33
public var errorDescription: String? {
switch self {
case .noError:
return "Success"
case .unknown:
return "Unknown error"
case .flashConfigurationQueryFailure:
return "Failed to query flash area configuration"
case .noImage:
return "There's no image in the slot"
case .noTLVs:
return "Slot image is missing TLV information"
case .invalidTLV:
return "Slot image has an invalid TLV type and/or length"
case .tlvHashCollision:
return "Slot image has multiple hash TLVs, which is invalid"
case .tlvInvalidSize:
return "Slot image has an invalid TLV size"
case .hashNotFound:
return "Slot image has no hash TLV"
case .fullSlots:
return "There is no free slot to place the image"
case .flashOpenFailed:
return "Flash area opening failed"
case .flashReadFailed:
return "Flash area reading failed"
case .flashWriteFailed:
return "Flash area writing failed"
case .flashEraseFailed:
return "Flash area erasing failed"
case .invalidSlot:
return "Given slot is not valid"
case .mallocFailed:
return "Insufficient heap memory (malloc failed)"
case .flashContextAlreadySet:
return "Flash context is already set"
case .flashContextNotSet:
return "Flash context is not set"
case .flashAreaNull:
return "device for the flash area is null"
case .invalidPageOffset:
return "Invalid page number offset"
case .missingOffset:
return "Required offset parameter not found"
case .missingLength:
return "Required length parameter not found"
case .invalidImageHeader:
return "Image length is smaller than the size of an image header"
case .invalidImageHeaderMagic:
return "Image header magic value does not match the expected value"
case .invalidHash:
return "Invalid hash parameter"
case .invalidFlashAddress:
return "Image load address does not match the address of the flash area"
case .versionGetFailed:
return "Failed to get version of currently running application"
case .newerCurrentVersion:
return "Currently running application is newer than uploading version"
case .imageAlreadyPending:
return "Image operation already pending"
case .invalidImageVectorTable:
return "Image vector table is invalid"
case .invalidImageTooLarge:
return "Image is too large to fit"
case .invalidImageDataOverrun:
return "Data sent is larger than the provided image size"
case .imageConfirmationDenied:
return "Image confirmation denied"
case .imageSettingTestToActiveDenied:
return "Setting active slot to test is not allowed"
}
}
}
//******************************************************************************
// MARK: Image Upload Delegate
//******************************************************************************
public protocol ImageUploadDelegate: AnyObject {
/// Called when a packet of image data has been sent successfully.
///
/// - parameter bytesSent: The total number of image bytes sent so far.
/// - parameter imageSize: The overall size of the image being uploaded.
/// - parameter timestamp: The time this response packet was received.
func uploadProgressDidChange(bytesSent: Int, imageSize: Int, timestamp: Date)
/// Called when an image upload has failed.
///
/// - parameter error: The error that caused the upload to fail.
func uploadDidFail(with error: Error)
/// Called when the upload has been cancelled.
func uploadDidCancel()
/// Called when the upload has finished successfully.
func uploadDidFinish()
}