-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathSecureDFUPeripheral.swift
More file actions
370 lines (323 loc) · 15.8 KB
/
Copy pathSecureDFUPeripheral.swift
File metadata and controls
370 lines (323 loc) · 15.8 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
/*
* Copyright (c) 2019, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
internal class SecureDFUPeripheral : BaseCommonDFUPeripheral<SecureDFUExecutor, SecureDFUService> {
/// A flag indicating whether setting alternative advertising name is
/// enabled (SDK 14+) (`true` by default).
let alternativeAdvertisingNameEnabled: Bool
/// The alternative advertising name to use specified by the user, if
/// `nil` then use a randomly generated name.
let alternativeAdvertisingName: String?
/// This flag is set when the bootloader is setting alternative advertising name.
/// If the buttonless service is not configured correctly, it will reboot on the attempt to
/// set the name, and will freeze.
///
/// For more info, see:
/// https://github.com/NordicSemiconductor/IOS-Pods-DFU-Library/issues/365
/// and for solution:
/// https://devzone.nordicsemi.com/f/nordic-q-a/59881/advertising-rename-feature-not-working
var possibleDisconnectionOnSettingAlternativeName: Bool = false
// MARK: - Peripheral API
override var requiredServices: [CBUUID]? {
return [SecureDFUService.serviceUuid(from: uuidHelper)]
}
override func isInitPacketRequired() -> Bool {
// Init packet is obligatory in Secure DFU.
return true
}
// MARK: - Implementation
override init(_ initiator: DFUServiceInitiator, _ logger: LoggerHelper) {
self.alternativeAdvertisingNameEnabled = initiator.alternativeAdvertisingNameEnabled
self.alternativeAdvertisingName = initiator.alternativeAdvertisingName
super.init(initiator, logger)
}
/**
Enables notifications on DFU Control Point characteristic.
*/
func enableControlPoint() {
dfuService?.enableControlPoint(
onSuccess: { [weak self] in self?.delegate?.peripheralDidEnableControlPoint() },
onError: defaultErrorCallback
)
}
override func isInApplicationMode(_ forceDfu: Bool) -> Bool {
let applicationMode = dfuService?.isInApplicationMode() ?? !forceDfu
if applicationMode {
logger.w("Application with buttonless update found")
}
return applicationMode
}
/**
Switches target device to the DFU Bootloader mode using either the
experimental or final Buttonless DFU feature.
The experimental buttonless DFU from SDK 12 must be enabled explicitly
in `DFUServiceInitiator`.
*/
func jumpToBootloader() {
guard let dfuService = dfuService else { return }
newAddressExpected = dfuService.newAddressExpected
var name: String?
if alternativeAdvertisingNameEnabled {
if let userSuppliedName = alternativeAdvertisingName {
// Use the user supplied name.
name = userSuppliedName
} else {
// Generate a random 8-character long name.
name = String(format: "Dfu%05d", arc4random_uniform(100000))
}
}
// See `peripheralDidDisconnect()` for details.
possibleDisconnectionOnSettingAlternativeName = name != nil
dfuService.jumpToBootloaderMode(withAlternativeAdvertisingName: name,
onSuccess: { [weak self] in
self?.jumpingToBootloader = true
self?.possibleDisconnectionOnSettingAlternativeName = false
// The device will now disconnect and
// `centralManager(_:didDisconnectPeripheral:error)` will be called.
},
onError: { [weak self] error, message in
self?.jumpingToBootloader = false
self?.possibleDisconnectionOnSettingAlternativeName = false
self?.delegate?.error(error, didOccurWithMessage: message)
}
)
}
override func peripheralDidDisconnect() {
// When the buttonless service reboots when command 0x02 (set advertising name)
// is sent, instead of replying with status (success or error), it means it
// is not properly configured.
//
// Add the following code to the app:
//
// Initialize the async SVCI interface to bootloader before any interrupts are enabled.
// err_code = ble_dfu_buttonless_async_svci_init();
// APP_ERROR_CHECK(err_code);
//
// See https://github.com/NordicSemiconductor/IOS-Pods-DFU-Library/issues/365
if possibleDisconnectionOnSettingAlternativeName {
logger.e("Buttonless service not configured, see: https://devzone.nordicsemi.com/f/nordic-q-a/59881/advertising-rename-feature-not-working/243566#243566. To workaround, disable alternative advertising name.")
possibleDisconnectionOnSettingAlternativeName = false
// We could set the flag below to allow jumping to the bootloader mode
// without using alternative advertising name, but it's better to fail
// and make sure the user knows about the issue. It can be workaround
// by disabling alternative name in DFUServiceInitiator.
// jumpingToBootloader = true
}
super.peripheralDidDisconnect()
}
/**
Selects Data Object.
As a result, the current status and the maximum object size is returned.
*/
func selectDataObject() {
dfuService?.selectDataObject(
onResponse: { [weak self] response in
guard let self = self else { return }
guard response.requestOpCode == .selectObject else {
self.logger.e("Invalid response received (\(response), expected \(SecureDFUOpCode.selectObject))")
self.throwErrorIfNotChecksumResponse(response)
return
}
guard response.maxSize! > 0 else {
self.logger.e("Invalid Data Object Max size = 0 received (expected > 0, typically 4096 bytes)")
self.delegate?.error(.unsupportedResponse,
didOccurWithMessage: "Received max object size = 0, expected 4096")
return
}
self.delegate?.peripheralDidSendDataObjectInfo(maxLen: response.maxSize!,
offset: response.offset!,
crc: response.crc!)
},
onError: defaultErrorCallback
)
}
/**
Selects Command Object.
As a result, the current status and the maximum object size is returned.
*/
func selectCommandObject() {
dfuService?.selectCommandObject(
onResponse: { [weak self] response in
guard let self = self else { return }
guard response.requestOpCode == .selectObject else {
self.logger.e("Invalid response received (\(response), expected \(SecureDFUOpCode.selectObject))")
self.throwErrorIfNotChecksumResponse(response)
return
}
guard response.maxSize! > 0 else {
self.logger.e("Invalid Command Object Max size = 0 received (expected > 0, typically 256 bytes)")
self.delegate?.error(.unsupportedResponse,
didOccurWithMessage: "Received max object size = 0, expected 256")
return
}
self.delegate?.peripheralDidSendCommandObjectInfo(maxLen: response.maxSize!,
offset: response.offset!,
crc: response.crc!)
},
onError: defaultErrorCallback
)
}
/**
[Issue 465](https://github.com/NordicSemiconductor/IOS-DFU-Library/issues/465)
indicates, that sometimes a Checksum response is received here.
It may be a lost PRN, or an invalid response. We don't know yet.
If you encounter this log, please report to the mentioned issue
providing logs. Thank you!
Let's hope for the best and wait for the proper response.
*/
private func throwErrorIfNotChecksumResponse(_ response: SecureDFUResponse) {
if response.requestOpCode != .calculateChecksum {
self.delegate?.error(.unsupportedResponse,
didOccurWithMessage: "Invalid response received (\(response), expected \(SecureDFUOpCode.selectObject))")
}
}
/**
Creates data object with given length.
- parameter length: Exact size of the object.
*/
func createDataObject(withLength length: UInt32) {
dfuService?.createDataObject(withLength: length,
onSuccess: { [weak self] in self?.delegate?.peripheralDidCreateDataObject() },
onError: defaultErrorCallback
)
}
/**
Creates command object with given length.
- parameter length: Exact size of the object.
*/
func createCommandObject(withLength length: UInt32) {
dfuService?.createCommandObject(withLength: length,
onSuccess: { [weak self] in self?.delegate?.peripheralDidCreateCommandObject() },
onError: defaultErrorCallback
)
}
/**
Sends a given range of data from the firmware.
- parameter range: Given range of the firmware will be sent.
- parameter firmware: The firmware from with part is to be sent.
- parameter progress: An optional progress delegate.
- parameter queue: The queue to dispatch progress events on.
*/
func sendNextObject(from range: Range<Int>, of firmware: DFUFirmware,
andReportProgressTo progress: DFUProgressDelegate?,
on queue: DispatchQueue) {
dfuService?.sendNextObject(from: range, of: firmware,
andReportProgressTo: progress, on: queue,
onSuccess: { [weak self] in self?.delegate?.peripheralDidReceiveObject() },
onError: defaultErrorCallback
)
}
/**
Sets the Packet Receipt Notification value.
0 disables the PRN procedure.
On older version of iOS the value may not be greater than ~20 or equal to 0,
otherwise a buffer overflow error may occur.
This library sends the Init packet without PRNs, but that's only because of
the Init packet is small enough.
- parameter newValue: Packet Receipt Notification value (0 to disable PRNs).
*/
func setPRNValue(_ newValue: UInt16 = 0) {
dfuService?.setPacketReceiptNotificationValue(newValue,
onSuccess: { [weak self] in self?.delegate?.peripheralDidSetPRNValue() },
onError: defaultErrorCallback
)
}
/**
Sends Init packet. This method is synchronous and calls delegate's
`peripheralDidReceiveInitPacket()` method after the given data are sent.
- parameter packetData: Data to be sent as Init Packet.
*/
func sendInitPacket(_ packetData: Data){
// This method is synchronous.
// It sends all bytes of init packet in up-to-20-byte packets.
// The init packet may not be too long as sending > ~15 packets without
// PRNs may lead to buffer overflow.
dfuService?.sendInitPacket(withData: packetData,
onError: defaultErrorCallback
)
self.delegate?.peripheralDidReceiveInitPacket()
}
/**
Sends Calculate Checksum request.
*/
func sendCalculateChecksumCommand() {
dfuService?.calculateChecksumCommand(
onSuccess: { [weak self] response in
self?.delegate?.peripheralDidSendChecksum(offset: response.offset!,
crc: response.crc!)
},
onError: defaultErrorCallback
)
}
/**
Sends Execute command.
- parameter isCommandObject: `True`, when it is the Command Object executed,
`false` if a Data Object.
- parameter activating: If the parameter is set to `true` the service will
assume that the whole firmware was sent and the device
will disconnect on its own on Execute command.
Delegate's `onTransferComplete` event will be called when
the disconnect event is received.
*/
func sendExecuteCommand(forCommandObject isCommandObject: Bool = false,
andActivateIf complete: Bool = false) {
activating = complete
dfuService?.executeCommand(
onSuccess: { [weak self] in self?.delegate?.peripheralDidExecuteObject() },
onError: { [weak self] error, message in
guard let self = self else { return }
self.activating = false
// In SDK 15.2 (and perhaps 15.x), the DFU target may report only full pages
// when reconnected after interrupted DFU. In such case Executing object will fail
// with Operation Not Permitted error. Instead, we have to create the new object
// and continue sending data assuming the last object executed.
if isCommandObject == false && error == DFUError.remoteSecureDFUOperationNotPermitted {
self.delegate?.peripheralDidExecuteObject()
return
}
// When a remote error is return from a Command Object execution, the library
// may still be able to continue with second part of the Firmware, if such exist.
if isCommandObject == true && error.isRemote {
self.delegate?.peripheralRejectedCommandObject(withError: error, andMessage: message)
return
}
// Default action for an error
self.delegate?.error(error, didOccurWithMessage: message)
}
)
}
override func resetDevice() {
guard let dfuService = dfuService, dfuService.supportsReset() else {
super.resetDevice()
return
}
dfuService.sendReset(onError: defaultErrorCallback)
}
}