-
Notifications
You must be signed in to change notification settings - Fork 263
/
SecureDfuImpl.java
990 lines (898 loc) · 45.5 KB
/
SecureDfuImpl.java
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
/*
* Copyright (c) 2018, 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.
*/
package no.nordicsemi.android.dfu;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.UUID;
import java.util.zip.CRC32;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import no.nordicsemi.android.dfu.internal.ArchiveInputStream;
import no.nordicsemi.android.dfu.internal.exception.DeviceDisconnectedException;
import no.nordicsemi.android.dfu.internal.exception.DfuException;
import no.nordicsemi.android.dfu.internal.exception.RemoteDfuException;
import no.nordicsemi.android.dfu.internal.exception.RemoteDfuExtendedErrorException;
import no.nordicsemi.android.dfu.internal.exception.UnknownResponseException;
import no.nordicsemi.android.dfu.internal.exception.UploadAbortedException;
import no.nordicsemi.android.error.SecureDfuError;
/* package */
@SuppressWarnings("JavaDoc")
class SecureDfuImpl extends BaseCustomDfuImpl {
// UUIDs used by the DFU
static final UUID DEFAULT_DFU_SERVICE_UUID = new UUID(0x0000FE5900001000L, 0x800000805F9B34FBL); // 16-bit UUID assigned by Bluetooth SIG
static final UUID DEFAULT_DFU_CONTROL_POINT_UUID = new UUID(0x8EC90001F3154F60L, 0x9FB8838830DAEA50L);
static final UUID DEFAULT_DFU_PACKET_UUID = new UUID(0x8EC90002F3154F60L, 0x9FB8838830DAEA50L);
static UUID DFU_SERVICE_UUID = DEFAULT_DFU_SERVICE_UUID;
static UUID DFU_CONTROL_POINT_UUID = DEFAULT_DFU_CONTROL_POINT_UUID;
static UUID DFU_PACKET_UUID = DEFAULT_DFU_PACKET_UUID;
private static final int DFU_STATUS_SUCCESS = 1;
private static final int MAX_ATTEMPTS = 3;
// Object types
private static final int OBJECT_COMMAND = 0x01;
private static final int OBJECT_DATA = 0x02;
// Operation codes and packets
private static final int OP_CODE_CREATE_KEY = 0x01;
private static final int OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY = 0x02;
private static final int OP_CODE_CALCULATE_CHECKSUM_KEY = 0x03;
private static final int OP_CODE_EXECUTE_KEY = 0x04;
private static final int OP_CODE_SELECT_OBJECT_KEY = 0x06;
private static final int OP_CODE_RESPONSE_CODE_KEY = 0x60;
private static final byte[] OP_CODE_CREATE_COMMAND = new byte[]{OP_CODE_CREATE_KEY, OBJECT_COMMAND, 0x00, 0x00, 0x00, 0x00 };
private static final byte[] OP_CODE_CREATE_DATA = new byte[]{OP_CODE_CREATE_KEY, OBJECT_DATA, 0x00, 0x00, 0x00, 0x00};
private static final byte[] OP_CODE_PACKET_RECEIPT_NOTIF_REQ = new byte[]{OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY, 0x00, 0x00 /* param PRN uint16 in Little Endian */};
private static final byte[] OP_CODE_CALCULATE_CHECKSUM = new byte[]{OP_CODE_CALCULATE_CHECKSUM_KEY};
private static final byte[] OP_CODE_EXECUTE = new byte[]{OP_CODE_EXECUTE_KEY};
private static final byte[] OP_CODE_SELECT_OBJECT = new byte[]{OP_CODE_SELECT_OBJECT_KEY, 0x00 /* type */};
private BluetoothGattCharacteristic mControlPointCharacteristic;
private BluetoothGattCharacteristic mPacketCharacteristic;
private long prepareObjectDelay;
private final SecureBluetoothCallback mBluetoothCallback = new SecureBluetoothCallback();
protected class SecureBluetoothCallback extends BaseCustomBluetoothCallback {
@Override
public void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
if (characteristic.getValue() == null || characteristic.getValue().length < 3) {
loge("Empty response: " + parse(characteristic));
mError = DfuBaseService.ERROR_INVALID_RESPONSE;
notifyLock();
return;
}
final int responseType = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
// The first byte should always be the response code
if (responseType == OP_CODE_RESPONSE_CODE_KEY) {
final int requestType = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
//noinspection SwitchStatementWithTooFewBranches
switch (requestType) {
case OP_CODE_CALCULATE_CHECKSUM_KEY: {
final int offset = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3);
final int remoteCrc = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 4);
final int localCrc = (int) (((ArchiveInputStream) mFirmwareStream).getCrc32() & 0xFFFFFFFFL);
// Check whether local and remote CRC match
if (localCrc == remoteCrc) {
// If so, update the number of bytes received
mProgressInfo.setBytesReceived(offset);
} else {
// Else, and only in case it was a PRN received, not the response for
// Calculate Checksum Request, stop sending data
if (mFirmwareUploadInProgress) {
mFirmwareUploadInProgress = false;
notifyLock();
return;
} // else will be handled by sendFirmware(gatt) below
}
handlePacketReceiptNotification(gatt, characteristic);
break;
}
default: {
/*
* If the DFU target device is in invalid state (e.g. the Init Packet is
* required but has not been selected), the target will send
* DFU_STATUS_INVALID_STATE error for each firmware packet that was send.
* We are interested may ignore all but the first one.
*/
if (mRemoteErrorOccurred)
break;
final int status = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 2);
if (status != DFU_STATUS_SUCCESS)
mRemoteErrorOccurred = true;
handleNotification(gatt, characteristic);
break;
}
}
} else {
loge("Invalid response: " + parse(characteristic));
mError = DfuBaseService.ERROR_INVALID_RESPONSE;
}
notifyLock();
}
}
SecureDfuImpl(@NonNull final Intent intent, @NonNull final DfuBaseService service) {
super(intent, service);
}
@Override
public boolean isClientCompatible(@NonNull final Intent intent, @NonNull final BluetoothGatt gatt) {
final BluetoothGattService dfuService = gatt.getService(DFU_SERVICE_UUID);
if (dfuService == null)
return false;
final BluetoothGattCharacteristic characteristic = dfuService.getCharacteristic(DFU_CONTROL_POINT_UUID);
if (characteristic == null || characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG) == null)
return false;
mControlPointCharacteristic = characteristic;
mPacketCharacteristic = dfuService.getCharacteristic(DFU_PACKET_UUID);
return mPacketCharacteristic != null;
}
@Override
public boolean initialize(@NonNull final Intent intent, @NonNull final BluetoothGatt gatt,
@FileType final int fileType,
@NonNull final InputStream firmwareStream,
@Nullable final InputStream initPacketStream)
throws DfuException, DeviceDisconnectedException, UploadAbortedException {
if (initPacketStream == null) {
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR,
"The Init packet is required by this version DFU Bootloader");
mService.terminateConnection(gatt, DfuBaseService.ERROR_INIT_PACKET_REQUIRED);
return false;
}
return super.initialize(intent, gatt, fileType, firmwareStream, initPacketStream);
}
@Override
public BaseBluetoothGattCallback getGattCallback() {
return mBluetoothCallback;
}
@Override
protected UUID getControlPointCharacteristicUUID() {
return DFU_CONTROL_POINT_UUID;
}
@Override
protected UUID getPacketCharacteristicUUID() {
return DFU_PACKET_UUID;
}
@Override
protected UUID getDfuServiceUUID() {
return DFU_SERVICE_UUID;
}
@Override
public void performDfu(@NonNull final Intent intent)
throws DfuException, DeviceDisconnectedException, UploadAbortedException {
logw("Secure DFU bootloader found");
mProgressInfo.setProgress(DfuBaseService.PROGRESS_STARTING);
// Add one second delay to avoid the traffic jam before the DFU mode is enabled
// Related:
// issue: https://github.com/NordicSemiconductor/Android-DFU-Library/issues/10
// pull request: https://github.com/NordicSemiconductor/Android-DFU-Library/pull/12
mService.waitFor(1000);
// End
final BluetoothGatt gatt = mGatt;
// Secure DFU since SDK 15 supports higher MTUs.
// Let's request the MTU requested by the user. It may be that a lower MTU will be used.
if (intent.hasExtra(DfuBaseService.EXTRA_MTU) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final int requiredMtu = intent.getIntExtra(DfuBaseService.EXTRA_MTU, 517);
logi("Requesting MTU = " + requiredMtu);
requestMtu(requiredMtu);
}
prepareObjectDelay = intent.getLongExtra(DfuBaseService.EXTRA_DATA_OBJECT_DELAY, 0);
try {
// Enable notifications
enableCCCD(mControlPointCharacteristic, NOTIFICATIONS);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION,
"Notifications enabled");
// Wait a second here before going further
// Related:
// pull request: https://github.com/NordicSemiconductor/Android-DFU-Library/pull/11
mService.waitFor(1000);
// End
final boolean allowResume = !intent.hasExtra(DfuBaseService.EXTRA_DISABLE_RESUME)
|| !intent.getBooleanExtra(DfuBaseService.EXTRA_DISABLE_RESUME, false);
if (!allowResume)
logi("Resume feature disabled. Performing fresh DFU");
try {
sendInitPacket(gatt, allowResume);
} catch (final RemoteDfuException e) {
// If the SD+BL upload failed, we may still be able to upload the App.
// The SD+BL might have been updated before.
if (!mProgressInfo.isLastPart()) {
mRemoteErrorOccurred = false;
logw("Sending SD+BL failed. Trying to send App only");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING,
"Invalid system components. Trying to send application");
mFileType = DfuBaseService.TYPE_APPLICATION;
// Set new content type in the ZIP Input Stream and update sizes of images
final ArchiveInputStream zhis = (ArchiveInputStream) mFirmwareStream;
zhis.setContentType(mFileType);
final byte[] applicationInit = zhis.getApplicationInit();
mInitPacketStream = new ByteArrayInputStream(applicationInit);
mInitPacketSizeInBytes = applicationInit.length;
mImageSizeInBytes = zhis.applicationImageSize();
mProgressInfo.init(mImageSizeInBytes, 2, 2);
sendInitPacket(gatt, false);
} else {
// There's noting we could do about it.
throw e;
}
}
sendFirmware(gatt);
// The device will reset so we don't have to send Disconnect signal.
mProgressInfo.setProgress(DfuBaseService.PROGRESS_DISCONNECTING);
mService.waitUntilDisconnected();
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "Disconnected by the remote device");
// We are ready with DFU, the device is disconnected, let's close it and finalize the operation.
finalize(intent, false);
} catch (@SuppressWarnings("CaughtExceptionImmediatelyRethrown") final UploadAbortedException e) {
// In secure DFU there is currently not possible to reset the device to application mode, so... do nothing
// The connection will be terminated in the DfuBaseService
throw e;
} catch (final UnknownResponseException e) {
final int error = DfuBaseService.ERROR_INVALID_RESPONSE;
loge(e.getMessage());
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, e.getMessage());
mService.terminateConnection(gatt, error);
} catch (final RemoteDfuException e) {
final int error = DfuBaseService.ERROR_REMOTE_TYPE_SECURE | e.getErrorNumber();
loge(e.getMessage() + ": " + SecureDfuError.parse(error));
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, String.format(Locale.US,
"Remote DFU error: %s", SecureDfuError.parse(error)));
// For the Extended Error more details can be obtained on some devices.
if (e instanceof RemoteDfuExtendedErrorException) {
final RemoteDfuExtendedErrorException ee = (RemoteDfuExtendedErrorException) e;
final int extendedError = DfuBaseService.ERROR_REMOTE_TYPE_SECURE_EXTENDED | ee.getExtendedErrorNumber();
loge("Extended Error details: " + SecureDfuError.parseExtendedError(extendedError));
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR,
"Details: " + SecureDfuError.parseExtendedError(extendedError) + " (Code = " + ee.getExtendedErrorNumber() + ")");
mService.terminateConnection(gatt, extendedError | DfuBaseService.ERROR_REMOTE_MASK);
} else {
mService.terminateConnection(gatt, error | DfuBaseService.ERROR_REMOTE_MASK);
}
}
}
/**
* This method does the following:
* <ol>
* <li>Selects the Command object - this Op Code returns the maximum acceptable size of a
* command object, and the offset and CRC32 of the command that is already stored in the
* device (in case the DFU was started in a previous connection and disconnected before
* it has finished).</li>
* <li>If the offset received is greater than 0 and less or equal to the size of the
* Init file that is to be sent, it will compare the
* received CRC with the local one and, if they match:
* <ul>
* <li>If offset < init file size - it will continue sending the Init file from the
* point it stopped before,</li>
* <li>If offset == init file size - it will send Execute command to execute the
* Init file, as it may have not been executed before.</li>
* </ul>
* </li>
* <li>If the CRC don't match, or the received offset is greater then init file size,
* it creates the Command Object and sends the whole Init file as the previous one was
* different.</li>
* </ol>
* Sending of the Init packet is done without using PRNs (Packet Receipt Notifications),
* so they are disabled prior to sending the data.
*
* @param gatt the target GATT device.
* @param allowResume true to allow resuming sending Init Packet. If false, it will be started
* again.
* @throws RemoteDfuException
* @throws DeviceDisconnectedException
* @throws DfuException
* @throws UploadAbortedException
* @throws UnknownResponseException
*/
private void sendInitPacket(@NonNull final BluetoothGatt gatt, final boolean allowResume)
throws RemoteDfuException, DeviceDisconnectedException, DfuException, UploadAbortedException, UnknownResponseException {
final CRC32 crc32 = new CRC32(); // Used to calculate CRC32 of the Init packet
ObjectChecksum checksum;
// First, select the Command Object. As a response the maximum command size and information whether there is already
// a command saved from a previous connection is returned.
logi("Setting object to Command (Op Code = 6, Type = 1)");
final ObjectInfo info = selectObject(OBJECT_COMMAND);
logi(String.format(Locale.US, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32));
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32));
//noinspection StatementWithEmptyBody
if (mInitPacketSizeInBytes > info.maxSize) {
// Ignore this here. Later, after sending the 'Create object' command, DFU target will send an error if init packet is too large
}
// Can we resume? If the offset obtained from the device is greater then zero we can compare it with the local init packet CRC
// and resume sending the init packet, or even skip sending it if the whole file was sent before.
boolean skipSendingInitPacket = false;
boolean resumeSendingInitPacket = false;
if (allowResume && info.offset > 0 && info.offset <= mInitPacketSizeInBytes) {
try {
// Read the same number of bytes from the current init packet to calculate local CRC32
final byte[] buffer = new byte[info.offset];
mInitPacketStream.read(buffer);
// Calculate the CRC32
crc32.update(buffer);
final int crc = (int) (crc32.getValue() & 0xFFFFFFFFL);
if (info.CRC32 == crc) {
logi("Init packet CRC is the same");
if (info.offset == mInitPacketSizeInBytes) {
// The whole init packet was sent and it is equal to one we try to send now.
// There is no need to send it again. We may try to resume sending data.
logi("-> Whole Init packet was sent before");
skipSendingInitPacket = true;
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Received CRC match Init packet");
} else {
logi("-> " + info.offset + " bytes of Init packet were sent before");
resumeSendingInitPacket = true;
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Resuming sending Init packet...");
}
} else {
// A different Init packet was sent before, or the error occurred while sending.
// We have to send the whole Init packet again.
mInitPacketStream.reset();
crc32.reset();
info.offset = 0;
}
} catch (final IOException e) {
loge("Error while reading " + info.offset + " bytes from the init packet stream", e);
try {
// Go back to the beginning of the stream, we will send the whole init packet
mInitPacketStream.reset();
crc32.reset();
info.offset = 0;
} catch (final IOException e1) {
loge("Error while resetting the init packet stream", e1);
mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION);
return;
}
}
}
if (!skipSendingInitPacket) {
// The Init packet is sent different way in this implementation than the firmware, and receiving PRNs is not implemented.
// This value might have been stored on the device, so we have to explicitly disable PRNs.
setPacketReceiptNotifications(0);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Packet Receipt Notif disabled (Op Code = 2, Value = 0)");
for (int attempt = 1; attempt <= MAX_ATTEMPTS;) {
if (!resumeSendingInitPacket) {
// Create the Init object
logi("Creating Init packet object (Op Code = 1, Type = 1, Size = " + mInitPacketSizeInBytes + ")");
writeCreateRequest(OBJECT_COMMAND, mInitPacketSizeInBytes);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Command object created");
}
// Write Init data to the Packet Characteristic
try {
logi("Sending " + (mInitPacketSizeInBytes - info.offset) + " bytes of init packet...");
writeInitData(mPacketCharacteristic, crc32);
} catch (final DeviceDisconnectedException e) {
loge("Disconnected while sending init packet");
throw e;
}
final int crc = (int) (crc32.getValue() & 0xFFFFFFFFL);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Command object sent (CRC = %08X)", crc));
// Calculate Checksum
logi("Sending Calculate Checksum command (Op Code = 3)");
checksum = readChecksum();
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32));
logi(String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32));
if (crc == checksum.CRC32) {
// Everything is OK, we can proceed
break;
} else {
if (attempt < MAX_ATTEMPTS) {
attempt++;
logi("CRC does not match! Retrying...(" + attempt + "/" + MAX_ATTEMPTS + ")");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "CRC does not match! Retrying...(" + attempt + "/" + MAX_ATTEMPTS + ")");
try {
// Go back to the beginning, we will send the whole Init packet again
resumeSendingInitPacket = false;
info.offset = 0;
info.CRC32 = 0;
mInitPacketStream.reset();
crc32.reset();
} catch (final IOException e) {
loge("Error while resetting the init packet stream", e);
mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION);
return;
}
} else {
loge("CRC does not match!");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, "CRC does not match!");
mService.terminateConnection(gatt, DfuBaseService.ERROR_CRC_ERROR);
return;
}
}
}
}
// Execute Init packet. It's better to execute it twice than not execute at all...
logi("Executing init packet (Op Code = 4)");
writeExecute();
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Command object executed");
}
/**
* This method does the following:
* <ol>
* <li>Sets the Packet Receipt Notification to a value specified in the settings.</li>
* <li>Selects the Data object - this returns maximum single object size and the offset
* and CRC of the data already saved.</li>
* <li>If the offset received is greater than 0 it will calculate the CRC of the same
* number of bytes of the firmware to be sent. If the CRC match it will continue sending data.
* Otherwise, it will go back to the beginning of the last chunk, or to the beginning
* of the previous chunk assuming the last one was not executed before, and continue
* sending data from there.</li>
* <li>If the CRC and offset received match and the offset is equal to the firmware size,
* it will only send the Execute command.</li>
* </ol>
* @param gatt the target GATT device.
* @throws RemoteDfuException
* @throws DeviceDisconnectedException
* @throws DfuException
* @throws UploadAbortedException
* @throws UnknownResponseException
*/
private void sendFirmware(final BluetoothGatt gatt) throws RemoteDfuException,
DeviceDisconnectedException, DfuException, UploadAbortedException, UnknownResponseException {
// Send the number of packets of firmware before receiving a receipt notification
int numberOfPacketsBeforeNotification = mPacketsBeforeNotification;
if (numberOfPacketsBeforeNotification > 0) {
setPacketReceiptNotifications(numberOfPacketsBeforeNotification);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION,
"Packet Receipt Notif Req (Op Code = 2) sent (Value = " + numberOfPacketsBeforeNotification + ")");
}
// We are ready to start sending the new firmware.
logi("Setting object to Data (Op Code = 6, Type = 2)");
final ObjectInfo info = selectObject(OBJECT_DATA);
logi(String.format(Locale.US,
"Data object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32));
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US,
"Data object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32));
mProgressInfo.setMaxObjectSizeInBytes(info.maxSize);
// Number of chunks in which the data will be sent
final int chunkCount = (mImageSizeInBytes + info.maxSize - 1) / info.maxSize;
int currentChunk = 0;
boolean resumeSendingData = false;
// Can we resume? If the offset obtained from the device is greater then zero we can compare it with the local CRC
// and resume sending the data.
if (info.offset > 0) {
try {
currentChunk = info.offset / info.maxSize;
int bytesSentAndExecuted = info.maxSize * currentChunk;
int bytesSentNotExecuted = info.offset - bytesSentAndExecuted;
// If the offset is dividable by maxSize, assume that the last page was not executed
if (bytesSentNotExecuted == 0) {
bytesSentAndExecuted -= info.maxSize;
bytesSentNotExecuted = info.maxSize;
}
// Read the same number of bytes from the current init packet to calculate local CRC32
if (bytesSentAndExecuted > 0) {
mFirmwareStream.read(new byte[bytesSentAndExecuted]); // Read executed bytes
mFirmwareStream.mark(info.maxSize); // Mark here
}
// Here the bytesSentNotExecuted is for sure greater then 0
mFirmwareStream.read(new byte[bytesSentNotExecuted]); // Read the rest
// Calculate the CRC32
final int crc = (int) (((ArchiveInputStream) mFirmwareStream).getCrc32() & 0xFFFFFFFFL);
if (crc == info.CRC32) {
logi(info.offset + " bytes of data sent before, CRC match");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION,
info.offset + " bytes of data sent before, CRC match");
mProgressInfo.setBytesSent(info.offset);
mProgressInfo.setBytesReceived(info.offset);
// If the whole page was sent and CRC match, we have to make sure it was executed
if (bytesSentNotExecuted == info.maxSize && info.offset < mImageSizeInBytes) {
logi("Executing data object (Op Code = 4)");
writeExecute();
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Data object executed");
} else {
resumeSendingData = true;
}
} else {
logi(info.offset + " bytes sent before, CRC does not match");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING,
info.offset + " bytes sent before, CRC does not match");
// The CRC of the current object is not correct. If there was another Data object sent before, its CRC must have been correct,
// as it has been executed. Either way, we have to create the current object again.
mProgressInfo.setBytesSent(bytesSentAndExecuted);
mProgressInfo.setBytesReceived(bytesSentAndExecuted);
info.offset -= bytesSentNotExecuted;
info.CRC32 = 0; // invalidate
mFirmwareStream.reset();
logi("Resuming from byte " + info.offset + "...");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION,
"Resuming from byte " + info.offset + "...");
}
} catch (final IOException e) {
loge("Error while reading firmware stream", e);
mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION);
return;
}
} else {
// Initialize the timer used to calculate the transfer speed
mProgressInfo.setBytesSent(0);
}
final long startTime = SystemClock.elapsedRealtime();
if (info.offset < mImageSizeInBytes) {
int attempt = 1;
// Each page will be sent in MAX_ATTEMPTS
while (mProgressInfo.getAvailableObjectSizeIsBytes() > 0) {
if (!resumeSendingData) {
// Create the Data object
final int availableObjectSizeInBytes = mProgressInfo.getAvailableObjectSizeIsBytes();
logi("Creating Data object (Op Code = 1, Type = 2, Size = " + availableObjectSizeInBytes + ") (" + (currentChunk + 1) + "/" + chunkCount + ")");
writeCreateRequest(OBJECT_DATA, availableObjectSizeInBytes);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION,
"Data object (" + (currentChunk + 1) + "/" + chunkCount + ") created");
// Waiting until the device is ready to receive the data object.
// If prepare data object delay was set in the initiator, the delay will be used
// for all data objects.
if (prepareObjectDelay > 0 || chunkCount == 0) {
mService.waitFor(prepareObjectDelay > 0 ? prepareObjectDelay : 400);
}
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION,
"Uploading firmware...");
} else {
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION,
"Resuming uploading firmware...");
resumeSendingData = false;
}
// Send the current object part
try {
logi("Uploading firmware...");
uploadFirmwareImage(mPacketCharacteristic);
} catch (final DeviceDisconnectedException e) {
loge("Disconnected while sending data");
throw e;
}
// Calculate Checksum
logi("Sending Calculate Checksum command (Op Code = 3)");
final ObjectChecksum checksum = readChecksum();
logi(String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32));
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US,
"Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32));
// It may happen, that not all bytes that were sent were received by the remote device
final int bytesLost = mProgressInfo.getBytesSent() - checksum.offset;
if (bytesLost > 0) {
logw(bytesLost + " bytes were lost!");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING,
bytesLost + " bytes were lost");
try {
// We have to reset the stream and read 'offset' number of bytes to recalculate the CRC
mFirmwareStream.reset(); // Resets to the beginning of current object
mFirmwareStream.read(new byte[info.maxSize - bytesLost]); // Reads additional bytes that were sent and received in this object
mProgressInfo.setBytesSent(checksum.offset);
} catch (final IOException e) {
loge("Error while reading firmware stream", e);
mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION);
return;
}
// To decrease the chance of loosing data next time let's set PRN to 1.
// This will make the update very long, but perhaps it will succeed.
final int newPrn = 1;
if (mPacketsBeforeNotification == 0 || mPacketsBeforeNotification > newPrn) {
numberOfPacketsBeforeNotification = mPacketsBeforeNotification = newPrn;
setPacketReceiptNotifications(numberOfPacketsBeforeNotification);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION,
"Packet Receipt Notif Req (Op Code = 2) sent (Value = " + newPrn + ")");
}
}
// Calculate the CRC32
final int crc = (int) (((ArchiveInputStream) mFirmwareStream).getCrc32() & 0xFFFFFFFFL);
if (crc == checksum.CRC32) {
if (bytesLost > 0) {
resumeSendingData = true;
continue;
}
// Execute Init packet
logi("Executing data object (Op Code = 4)");
writeExecute(mProgressInfo.isComplete());
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Data object executed");
// Increment iterator
currentChunk++;
attempt = 1;
//Mark this location after completion of successful transfer. In the event of a CRC retry on the next packet we will restart from this point.
mFirmwareStream.mark(0);
} else {
String crcFailMessage = String.format(Locale.US, "CRC does not match! Expected %08X but found %08X.", crc, checksum.CRC32);
if (attempt < MAX_ATTEMPTS) {
attempt++;
crcFailMessage += String.format(Locale.US, " Retrying...(%d/%d)", attempt, MAX_ATTEMPTS);
logi(crcFailMessage);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, crcFailMessage);
try {
// Reset the CRC and file pointer back to the previous mark() point after completion of the last successful packet.
mFirmwareStream.reset();
mProgressInfo.setBytesSent(((ArchiveInputStream) mFirmwareStream).getBytesRead());
} catch (final IOException e) {
loge("Error while resetting the firmware stream", e);
mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION);
return;
}
} else {
loge(crcFailMessage);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, crcFailMessage);
mService.terminateConnection(gatt, DfuBaseService.ERROR_CRC_ERROR);
return;
}
}
}
} else {
// Looks as if the whole file was sent correctly but has not been executed
logi("Executing data object (Op Code = 4)");
writeExecute(true);
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Data object executed");
}
final long endTime = SystemClock.elapsedRealtime();
logi("Transfer of " + (mProgressInfo.getBytesSent() - info.offset) + " bytes has taken " + (endTime - startTime) + " ms");
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Upload completed in " + (endTime - startTime) + " ms");
}
/**
* Checks whether the response received is valid and returns the status code.
*
* @param response the response received from the DFU device.
* @param request the expected Op Code
* @return the status code
* @throws UnknownResponseException if response was not valid
*/
private int getStatusCode(final byte[] response, final int request) throws UnknownResponseException {
if (response == null || response.length < 3 || response[0] != OP_CODE_RESPONSE_CODE_KEY || response[1] != request ||
(response[2] != DFU_STATUS_SUCCESS &&
response[2] != SecureDfuError.OP_CODE_NOT_SUPPORTED &&
response[2] != SecureDfuError.INVALID_PARAM &&
response[2] != SecureDfuError.INSUFFICIENT_RESOURCES &&
response[2] != SecureDfuError.INVALID_OBJECT &&
response[2] != SecureDfuError.UNSUPPORTED_TYPE &&
response[2] != SecureDfuError.OPERATION_NOT_PERMITTED &&
response[2] != SecureDfuError.OPERATION_FAILED &&
response[2] != SecureDfuError.EXTENDED_ERROR))
throw new UnknownResponseException("Invalid response received", response, OP_CODE_RESPONSE_CODE_KEY, request);
return response[2];
}
/**
* Sets number of data packets that will be send before the notification will be received.
*
* @param data control point data packet
* @param value number of packets before receiving notification. If this value is 0, then the
* notification of packet receipt will be disabled by the DFU target.
*/
private void setNumberOfPackets(@SuppressWarnings("SameParameterValue") @NonNull final byte[] data, final int value) {
data[1] = (byte) (value & 0xFF);
data[2] = (byte) ((value >> 8) & 0xFF);
}
/**
* Sets the object size in correct position of the data array.
*
* @param data control point data packet
* @param value Object size in bytes.
*/
private void setObjectSize(@NonNull final byte[] data, final int value) {
data[2] = (byte) (value & 0xFF);
data[3] = (byte) ((value >> 8) & 0xFF);
data[4] = (byte) ((value >> 16) & 0xFF);
data[5] = (byte) ((value >> 24) & 0xFF);
}
/**
* Sets the number of packets that needs to be sent to receive the Packet Receipt Notification.
* Value 0 disables PRNs. By default this is disabled. The PRNs may be used to send both the
* Data and Command object, but this Secure DFU implementation can handle them only during Data transfer.
* <p>
* The intention of having PRNs is to make sure the outgoing BLE buffer is not getting overflown.
* The PRN will be sent after sending all packets from the queue.
*
* @param number number of packets required before receiving a Packet Receipt Notification.
* @throws DfuException
* @throws DeviceDisconnectedException
* @throws UploadAbortedException
* @throws UnknownResponseException
* @throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}
*/
private void setPacketReceiptNotifications(final int number)
throws DfuException, DeviceDisconnectedException, UploadAbortedException,
UnknownResponseException, RemoteDfuException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
// Send the number of packets of firmware before receiving a receipt notification
logi("Sending the number of packets before notifications (Op Code = 2, Value = " + number + ")");
setNumberOfPackets(OP_CODE_PACKET_RECEIPT_NOTIF_REQ, number);
writeOpCode(mControlPointCharacteristic, OP_CODE_PACKET_RECEIPT_NOTIF_REQ);
// Read response
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Sending the number of packets failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Sending the number of packets failed", status);
}
/**
* Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the
* {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* will be called or the device gets disconnected.
* If connection state will change, or an error will occur, an exception will be thrown.
*
* @param characteristic the characteristic to write to. Should be the DFU CONTROL POINT.
* @param value the value to write to the characteristic.
* @throws DeviceDisconnectedException
* @throws DfuException
* @throws UploadAbortedException
*/
private void writeOpCode(@NonNull final BluetoothGattCharacteristic characteristic, @NonNull final byte[] value)
throws DeviceDisconnectedException, DfuException, UploadAbortedException {
writeOpCode(characteristic, value, false);
}
/**
* Writes Create Object request providing the type and size of the object.
*
* @param type {@link #OBJECT_COMMAND} or {@link #OBJECT_DATA}.
* @param size size of the object or current part of the object.
* @throws DeviceDisconnectedException
* @throws DfuException
* @throws UploadAbortedException
* @throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS}
* @throws UnknownResponseException
*/
private void writeCreateRequest(final int type, final int size)
throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException,
UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to create object: device disconnected");
final byte[] data = (type == OBJECT_COMMAND) ? OP_CODE_CREATE_COMMAND : OP_CODE_CREATE_DATA;
setObjectSize(data, size);
writeOpCode(mControlPointCharacteristic, data);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_CREATE_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Creating Command object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Creating Command object failed", status);
}
/**
* Selects the current object and reads its metadata. The object info contains the max object
* size, and the offset and CRC32 of the whole object until now.
*
* @return object info.
* @throws DeviceDisconnectedException
* @throws DfuException
* @throws UploadAbortedException
* @throws RemoteDfuException thrown when the returned status code is not equal to
* {@link #DFU_STATUS_SUCCESS}.
*/
private ObjectInfo selectObject(final int type)
throws DeviceDisconnectedException, DfuException, UploadAbortedException,
RemoteDfuException, UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read object info: device disconnected");
OP_CODE_SELECT_OBJECT[1] = (byte) type;
writeOpCode(mControlPointCharacteristic, OP_CODE_SELECT_OBJECT);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_SELECT_OBJECT_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Selecting object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Selecting object failed", status);
final ObjectInfo info = new ObjectInfo();
info.maxSize = unsignedBytesToInt(response, 3);
info.offset = unsignedBytesToInt(response, 3 + 4);
info.CRC32 = unsignedBytesToInt(response, 3 + 8);
return info;
}
/**
* Sends the Calculate Checksum request. As a response a notification will be sent with current
* offset and CRC32 of the current object.
*
* @return requested object info.
* @throws DeviceDisconnectedException
* @throws DfuException
* @throws UploadAbortedException
* @throws RemoteDfuException thrown when the returned status code is not equal to
* {@link #DFU_STATUS_SUCCESS}.
*/
private ObjectChecksum readChecksum() throws DeviceDisconnectedException, DfuException,
UploadAbortedException, RemoteDfuException, UnknownResponseException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
writeOpCode(mControlPointCharacteristic, OP_CODE_CALCULATE_CHECKSUM);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_CALCULATE_CHECKSUM_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Receiving Checksum failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Receiving Checksum failed", status);
final ObjectChecksum checksum = new ObjectChecksum();
checksum.offset = unsignedBytesToInt(response, 3);
checksum.CRC32 = unsignedBytesToInt(response, 3 + 4);
return checksum;
}
private int unsignedBytesToInt(@NonNull final byte[] array, final int offset) {
return (array[offset] & 0xFF) + ((array[offset + 1] & 0xFF) << 8)
+ ((array[offset + 2] & 0xFF) << 16) + ((array[offset + 3] & 0xFF) << 24);
}
/**
* Sends the Execute operation code and awaits for a return notification containing status code.
* The Execute command will confirm the last chunk of data or the last command that was sent.
* Creating the same object again, instead of executing it allows to retransmitting it in case
* of a CRC error.
*
* @throws DfuException
* @throws DeviceDisconnectedException
* @throws UploadAbortedException
* @throws UnknownResponseException
* @throws RemoteDfuException thrown when the returned status code is not equal to
* {@link #DFU_STATUS_SUCCESS}.
*/
private void writeExecute() throws DfuException, DeviceDisconnectedException,
UploadAbortedException, UnknownResponseException, RemoteDfuException {
if (!mConnected)
throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
writeOpCode(mControlPointCharacteristic, OP_CODE_EXECUTE);
final byte[] response = readNotificationResponse();
final int status = getStatusCode(response, OP_CODE_EXECUTE_KEY);
if (status == SecureDfuError.EXTENDED_ERROR)
throw new RemoteDfuExtendedErrorException("Executing object failed", response[3]);
if (status != DFU_STATUS_SUCCESS)
throw new RemoteDfuException("Executing object failed", status);
}
/**
* After the whole firmware image was sent, the last command Execute will cause erasing memory
* and flashing the new firmware. This may result in INVALID_OBJECT error in 2 cases:
* <ol>
* <li>The SoftDevice (which is responsible for allowing writing) was busy and the bootloader
* tried to erase the memory N times without a success. Then we can resend the Execute here.</li>
* <li>The firmware sent contained only SoftDevice (no Bootloader) and the Major version has
* changed comparing to the previous one. The old bootloader would not work with this new SD
* so such update is forbidden as it would brick the device.</li>
* </ol>
* See: <a href="https://github.com/NordicSemiconductor/Android-DFU-Library/issues/86">https://github.com/NordicSemiconductor/Android-DFU-Library/issues/86</a>
*
* @param allowRetry if true service will retry to send the execute command in case of
* INVALID_OBJECT error.
* @throws DfuException
* @throws DeviceDisconnectedException
* @throws UploadAbortedException
* @throws UnknownResponseException
* @throws RemoteDfuException thrown when the returned status code is not equal to
* {@link #DFU_STATUS_SUCCESS}.
*/
private void writeExecute(final boolean allowRetry)
throws DfuException, DeviceDisconnectedException, UploadAbortedException,
UnknownResponseException, RemoteDfuException {
try {
writeExecute();
} catch (final RemoteDfuException e) {
if (allowRetry && e.getErrorNumber() == SecureDfuError.INVALID_OBJECT) {
logw(e.getMessage() + ": " + SecureDfuError.parse(DfuBaseService.ERROR_REMOTE_TYPE_SECURE | SecureDfuError.INVALID_OBJECT));
if (mFileType == DfuBaseService.TYPE_SOFT_DEVICE) {
logw("Are you sure your new SoftDevice is API compatible with the updated one? If not, update the bootloader as well");
// API compatible = both SoftDevices have the same Major version
}
mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, String.format(Locale.US, "Remote DFU error: %s. SD busy? Retrying...",
SecureDfuError.parse(DfuBaseService.ERROR_REMOTE_TYPE_SECURE | SecureDfuError.INVALID_OBJECT)));
logi("SD busy? Retrying...");
logi("Executing data object (Op Code = 4)");
writeExecute();
} else {
throw e;
}
}
}
private class ObjectInfo extends ObjectChecksum {
int maxSize;
}
private class ObjectChecksum {
int offset;
int CRC32;
}
}