This repository has been archived by the owner on Aug 17, 2023. It is now read-only.
/
AmazonFreeRTOSDevice.java
1315 lines (1220 loc) · 60.9 KB
/
AmazonFreeRTOSDevice.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
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.freertos.amazonfreertossdk;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import software.amazon.freertos.amazonfreertossdk.deviceinfo.BrokerEndpoint;
import software.amazon.freertos.amazonfreertossdk.deviceinfo.Mtu;
import software.amazon.freertos.amazonfreertossdk.deviceinfo.Version;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttClientStatusCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttManager;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttMessageDeliveryCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback;
import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import lombok.Getter;
import lombok.NonNull;
import software.amazon.freertos.amazonfreertossdk.mqttproxy.*;
import software.amazon.freertos.amazonfreertossdk.networkconfig.*;
import static android.bluetooth.BluetoothDevice.BOND_BONDING;
import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.*;
import static software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.AmazonFreeRTOSError.BLE_DISCONNECTED_ERROR;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.DISCOVER_SERVICES;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.NOTIFICATION;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.READ_CHARACTERISTIC;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.REQUEST_MTU;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.WRITE_CHARACTERISTIC;
import static software.amazon.freertos.amazonfreertossdk.BleCommand.CommandType.WRITE_DESCRIPTOR;
public class AmazonFreeRTOSDevice {
private static final String TAG = "FRD";
private static final boolean VDBG = false;
private Context mContext;
@Getter
private BluetoothDevice mBluetoothDevice;
private BluetoothGatt mBluetoothGatt;
private BleConnectionStatusCallback mBleConnectionStatusCallback;
private NetworkConfigCallback mNetworkConfigCallback;
private DeviceInfoCallback mDeviceInfoCallback;
private BleConnectionState mBleConnectionState = BleConnectionState.BLE_DISCONNECTED;
private String mAmazonFreeRTOSLibVersion = "NA";
private String mAmazonFreeRTOSDeviceType = "NA";
private String mAmazonFreeRTOSDeviceId = "NA";
private boolean mGattAutoReconnect = false;
private BroadcastReceiver mBondStateCallback = null;
private int mMtu = 0;
private boolean rr = false;
private Queue<BleCommand> mMqttQueue = new LinkedList<>();
private Queue<BleCommand> mNetworkQueue = new LinkedList<>();
private Queue<BleCommand> mIncomingQueue = new LinkedList<>();
private boolean mBleOperationInProgress = false;
private boolean mRWinProgress = false;
private Handler mHandler;
private HandlerThread mHandlerThread;
private byte[] mValueWritten;
private Semaphore mutex = new Semaphore(1);
private Semaphore mIncomingMutex = new Semaphore(1);
//Buffer for receiving messages from device
private ByteArrayOutputStream mTxLargeObject = new ByteArrayOutputStream();
private ByteArrayOutputStream mTxLargeNw = new ByteArrayOutputStream();
//Buffer for sending messages to device.
private int mTotalPackets = 0;
private int mPacketCount = 1;
private int mMessageId = 0;
private int mMaxPayloadLen = 0;
private AWSIotMqttManager mIotMqttManager;
private MqttConnectionState mMqttConnectionState = MqttConnectionState.MQTT_Disconnected;
private AWSCredentialsProvider mAWSCredential;
private KeyStore mKeystore;
/**
* Construct an AmazonFreeRTOSDevice instance.
*
* @param context The app context. Should be passed in by the app that creates a new instance
* of AmazonFreeRTOSDevice.
* @param device BluetoothDevice returned from BLE scan result.
* @param cp AWS credential for connection to AWS IoT. If null is passed in,
* then it will not be able to do MQTT proxy over BLE as it cannot
* connect to AWS IoT.
*/
AmazonFreeRTOSDevice(@NonNull BluetoothDevice device, @NonNull Context context, AWSCredentialsProvider cp) {
this(device, context, cp, null);
}
/**
* Construct an AmazonFreeRTOSDevice instance.
*
* @param context The app context. Should be passed in by the app that creates a new instance
* of AmazonFreeRTOSDevice.
* @param device BluetoothDevice returned from BLE scan result.
* @param ks the KeyStore which contains the certificate used to connect to AWS IoT.
*/
AmazonFreeRTOSDevice(@NonNull BluetoothDevice device, @NonNull Context context, KeyStore ks) {
this(device, context, null, ks);
}
private AmazonFreeRTOSDevice(@NonNull BluetoothDevice device, @NonNull Context context,
AWSCredentialsProvider cp, KeyStore ks) {
mContext = context;
mBluetoothDevice = device;
mAWSCredential = cp;
mKeystore = ks;
}
void connect(@NonNull final BleConnectionStatusCallback connectionStatusCallback,
final boolean autoReconnect) {
mBleConnectionStatusCallback = connectionStatusCallback;
mHandlerThread = new HandlerThread("BleCommandHandler"); //TODO: unique thread name for each device?
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mGattAutoReconnect = autoReconnect;
mBluetoothGatt = mBluetoothDevice.connectGatt(mContext, false, mGattCallback, TRANSPORT_LE);
}
private void cleanUp() {
// If ble connection is lost, clear any pending ble command.
mMqttQueue.clear();
mNetworkQueue.clear();
mIncomingQueue.clear();
mMessageId = 0;
mMtu = 0;
mMaxPayloadLen = 0;
mTxLargeObject.reset();
mTotalPackets = 0;
mPacketCount = 1;
}
/**
* User initiated disconnect
*/
void disconnect() {
if (mBluetoothGatt != null) {
mGattAutoReconnect = false;
mBluetoothGatt.disconnect();
}
}
/**
* Sends a ListNetworkReq command to the connected BLE device. The available WiFi networks found
* by the connected BLE device will be returned in the callback as a ListNetworkResp. Each found
* WiFi network should trigger the callback once. For example, if there are 10 available networks
* found by the BLE device, this callback will be triggered 10 times, each containing one
* ListNetworkResp that represents that WiFi network. In addition, the order of the callbacks will
* be triggered as follows: the saved networks will be returned first, in decreasing order of their
* preference, as denoted by their index. (The smallest non-negative index denotes the highest
* preference, and is therefore returned first.) For example, the saved network with index 0 will
* be returned first, then the saved network with index 1, then index 2, etc. After all saved
* networks have been returned, the non-saved networks will be returned, in the decreasing order
* of their RSSI value, a network with higher RSSI value will be returned before one with lower
* RSSI value.
*
* @param listNetworkReq The ListNetwork request
* @param callback The callback which will be triggered once the BLE device sends a ListNetwork
* response.
*/
public void listNetworks(ListNetworkReq listNetworkReq, NetworkConfigCallback callback) {
mNetworkConfigCallback = callback;
byte[] listNetworkReqBytes = listNetworkReq.encode();
sendDataToDevice(UUID_NETWORK_SERVICE, UUID_NETWORK_RX, UUID_NETWORK_RXLARGE, listNetworkReqBytes);
}
/**
* Sends a SaveNetworkReq command to the connected BLE device. The SaveNetworkReq contains the
* network credential. A SaveNetworkResp will be sent by the BLE device and triggers the callback.
* To get the updated order of all networks, call listNetworks again.
*
* @param saveNetworkReq The SaveNetwork request.
* @param callback The callback that is triggered once the BLE device sends a SaveNetwork response.
*/
public void saveNetwork(SaveNetworkReq saveNetworkReq, NetworkConfigCallback callback) {
mNetworkConfigCallback = callback;
byte[] saveNetworkReqBytes = saveNetworkReq.encode();
sendDataToDevice(UUID_NETWORK_SERVICE, UUID_NETWORK_RX, UUID_NETWORK_RXLARGE, saveNetworkReqBytes);
}
/**
* Sends an EditNetworkReq command to the connected BLE device. The EditNetwork request is used
* to update the preference of a saved network. It contains the current index of the saved network
* to be updated, and the desired new index of the save network to be updated to. Both the current
* index and the new index must be one of those saved networks. Behavior is undefined if an index
* of an unsaved network is provided in the EditNetworkReq.
* To get the updated order of all networks, call listNetworks again.
*
* @param editNetworkReq The EditNetwork request.
* @param callback The callback that is triggered once the BLE device sends an EditNetwork response.
*/
public void editNetwork(EditNetworkReq editNetworkReq, NetworkConfigCallback callback) {
mNetworkConfigCallback = callback;
byte[] editNetworkReqBytes = editNetworkReq.encode();
sendDataToDevice(UUID_NETWORK_SERVICE, UUID_NETWORK_RX, UUID_NETWORK_RXLARGE, editNetworkReqBytes);
}
/**
* Sends a DeleteNetworkReq command to the connected BLE device. The saved network with the index
* specified in the delete network request will be deleted, making it a non-saved network again.
* To get the updated order of all networks, call listNetworks again.
*
* @param deleteNetworkReq The DeleteNetwork request.
* @param callback The callback that is triggered once the BLE device sends a DeleteNetwork response.
*/
public void deleteNetwork(DeleteNetworkReq deleteNetworkReq, NetworkConfigCallback callback) {
mNetworkConfigCallback = callback;
byte[] deleteNetworkReqBytes = deleteNetworkReq.encode();
sendDataToDevice(UUID_NETWORK_SERVICE, UUID_NETWORK_RX, UUID_NETWORK_RXLARGE, deleteNetworkReqBytes);
}
/**
* Get the current mtu value between device and Android phone. This method returns immediately.
* The request to get mtu value is asynchronous through BLE command. The response will be delivered
* through DeviceInfoCallback.
*
* @param callback The callback to notify app of current mtu value.
*/
public void getMtu(DeviceInfoCallback callback) {
mDeviceInfoCallback = callback;
if (!getMtu() && mDeviceInfoCallback != null) {
mDeviceInfoCallback.onError(BLE_DISCONNECTED_ERROR);
}
}
/**
* Get the current broker endpoint on the device. This broker endpoint is used to connect to AWS
* IoT, hence, this is also the AWS IoT endpoint. This method returns immediately.
* The request is sent asynchronously through BLE command. The response will be delivered
* through DeviceInfoCallback.
*
* @param callback The callback to notify app of current broker endpoint on device.
*/
public void getBrokerEndpoint(DeviceInfoCallback callback) {
mDeviceInfoCallback = callback;
if (!getBrokerEndpoint() && mDeviceInfoCallback != null) {
mDeviceInfoCallback.onError(BLE_DISCONNECTED_ERROR);
}
}
/**
* Get the AmazonFreeRTOS library software version running on the device. This method returns
* immediately. The request is sent asynchronously through BLE command. The response will be
* delivered through DeviceInfoCallback.
*
* @param callback The callback to notify app of current software version.
*/
public void getDeviceVersion(DeviceInfoCallback callback) {
mDeviceInfoCallback = callback;
if (!getDeviceVersion() && mDeviceInfoCallback != null) {
mDeviceInfoCallback.onError(BLE_DISCONNECTED_ERROR);
}
}
/**
* Try to read a characteristic from the Gatt service. If pairing is enabled, it will be triggered
* by this action.
*/
private void probe() {
getDeviceVersion();
}
/**
* Initialize the Gatt services
*/
private void initialize() {
getDeviceType();
getDeviceId();
getMtu();
sendBleCommand(new BleCommand(WRITE_DESCRIPTOR, UUID_MQTT_PROXY_TX, UUID_MQTT_PROXY_SERVICE));
sendBleCommand(new BleCommand(WRITE_DESCRIPTOR, UUID_MQTT_PROXY_TXLARGE, UUID_MQTT_PROXY_SERVICE));
sendBleCommand(new BleCommand(WRITE_DESCRIPTOR, UUID_NETWORK_TX, UUID_NETWORK_SERVICE));
sendBleCommand(new BleCommand(WRITE_DESCRIPTOR, UUID_NETWORK_TXLARGE, UUID_NETWORK_SERVICE));
}
private void enableService(final String serviceUuid, final boolean enable) {
byte[] ready = new byte[1];
if (enable) {
ready[0] = 1;
} else {
ready[0] = 0;
}
switch (serviceUuid) {
case UUID_NETWORK_SERVICE:
Log.i(TAG, (enable ? "Enabling" : "Disabling") + " Wifi provisioning");
sendBleCommand(new BleCommand(WRITE_CHARACTERISTIC, UUID_NETWORK_CONTROL, UUID_NETWORK_SERVICE, ready));
break;
case UUID_MQTT_PROXY_SERVICE:
if (mKeystore != null || mAWSCredential != null) {
Log.i(TAG, (enable ? "Enabling" : "Disabling") + " MQTT Proxy");
sendBleCommand(new BleCommand(WRITE_CHARACTERISTIC, UUID_MQTT_PROXY_CONTROL, UUID_MQTT_PROXY_SERVICE, ready));
}
break;
default:
Log.w(TAG, "Unknown service. Ignoring.");
}
}
private void processIncomingQueue() {
try {
mIncomingMutex.acquire();
while (mIncomingQueue.size() != 0) {
BleCommand bleCommand = mIncomingQueue.poll();
Log.d(TAG, "Processing incoming queue. size: " + mIncomingQueue.size());
byte[] responseBytes = bleCommand.getData();
String cUuid = bleCommand.getCharacteristicUuid();
switch (cUuid) {
case UUID_MQTT_PROXY_TX:
handleMqttTxMessage(responseBytes);
break;
case UUID_MQTT_PROXY_TXLARGE:
try {
mTxLargeObject.write(responseBytes);
sendBleCommand(new BleCommand(READ_CHARACTERISTIC,
UUID_MQTT_PROXY_TXLARGE, UUID_MQTT_PROXY_SERVICE));
} catch (IOException e) {
Log.e(TAG, "Failed to concatenate byte array.", e);
}
break;
case UUID_NETWORK_TX:
handleNwTxMessage(responseBytes);
break;
case UUID_NETWORK_TXLARGE:
try {
mTxLargeNw.write(responseBytes);
sendBleCommand(new BleCommand(READ_CHARACTERISTIC,
UUID_NETWORK_TXLARGE, UUID_NETWORK_SERVICE));
} catch (IOException e) {
Log.e(TAG, "Failed to concatenate byte array.", e);
}
break;
default:
Log.e(TAG, "Unknown characteristic " + cUuid);
}
}
mIncomingMutex.release();
} catch (InterruptedException e) {
Log.e(TAG, "Incoming mutex error, ", e);
}
}
private void registerBondStateCallback() {
mBondStateCallback = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BluetoothDevice.ACTION_BOND_STATE_CHANGED: {
int prev = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
int now = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
Log.d(TAG, "Bond state changed from " + prev + " to " + now);
/**
* If the state changed from bonding to bonded, then we have a valid bond created
* for the device.
* If discovery is not performed initiate discovery.
* If services are discovered start initialization by reading device version characteristic.
*/
if (prev == BluetoothDevice.BOND_BONDING && now == BluetoothDevice.BOND_BONDED) {
List<BluetoothGattService> services = mBluetoothGatt.getServices();
if (services == null || services.isEmpty()) {
discoverServices();
} else {
probe();
}
}
break;
}
default:
break;
}
}
};
final IntentFilter bondFilter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
mContext.registerReceiver(mBondStateCallback, bondFilter);
}
private void unRegisterBondStateCallback() {
if (mBondStateCallback != null) {
try {
mContext.unregisterReceiver(mBondStateCallback);
mBondStateCallback = null;
} catch (IllegalArgumentException ex) {
Log.w(TAG, "Caught exception while unregistering broadcast receiver" );
}
}
}
/**
* This is the callback for all BLE commands sent from SDK to device. The response of BLE
* command is included in the callback, together with the status code.
*/
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
Log.i(TAG, "BLE connection state changed: " + status + "; new state: "
+ AmazonFreeRTOSConstants.BleConnectionState.values()[newState]);
if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
int bondState = mBluetoothDevice.getBondState();
Log.i(TAG, "Connected to GATT server.");
mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_CONNECTED;
mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
// If the device is already bonded or will not bond we can call discoverServices() immediately
if (mBluetoothDevice.getBondState() != BOND_BONDING) {
discoverServices();
} else {
registerBondStateCallback();
}
} else {
Log.i(TAG, "Disconnected from GATT server due to error or peripheral initiated disconnect.");
mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_DISCONNECTED;
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) {
disconnectFromIot();
}
unRegisterBondStateCallback();
cleanUp();
mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
/**
* If auto reconnect is enabled, start a reconnect procedure in background
* using connect() method. Else close the GATT.
* Auto reconnect will be disabled when user initiates disconnect.
*/
if (!mGattAutoReconnect) {
gatt.close();
mBluetoothGatt = null;
} else {
mBluetoothGatt.connect();
}
}
}
@Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.i(TAG, "Discovered Ble gatt services successfully. Bonding state: "
+ mBluetoothDevice.getBondState());
describeGattServices(mBluetoothGatt.getServices());
/**
* Trigger bonding if needed, by reading device version characteristic, if bonding is not already
* in progress by the stack.
*/
if (mBluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDING) {
probe();
}
} else {
Log.e(TAG, "onServicesDiscovered received: " + status);
disconnect();
}
processNextBleCommand();
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
byte[] responseBytes = characteristic.getValue();
Log.d(TAG, "->->-> Characteristic changed for: "
+ uuidToName.get(characteristic.getUuid().toString())
+ " with data: " + bytesToHexString(responseBytes));
BleCommand incomingCommand = new BleCommand(NOTIFICATION,
characteristic.getUuid().toString(),
characteristic.getService().getUuid().toString(), responseBytes);
mIncomingQueue.add(incomingCommand);
if (!mRWinProgress) {
processIncomingQueue();
}
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
int status) {
Log.d(TAG, "onDescriptorWrite for characteristic: "
+ uuidToName.get(descriptor.getCharacteristic().getUuid().toString())
+ "; Status: " + (status == 0 ? "Success" : status));
processNextBleCommand();
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
Log.i(TAG, "onMTUChanged : " + mtu + " status: " + (status == 0 ? "Success" : status));
mMtu = mtu;
mMaxPayloadLen = Math.max(mMtu - 3, 0);
// The BLE service should be initialized at this stage
if (mBleConnectionState == BleConnectionState.BLE_INITIALIZING) {
mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_INITIALIZED;
mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
}
enableService(UUID_NETWORK_SERVICE, true);
enableService(UUID_MQTT_PROXY_SERVICE, true);
processNextBleCommand();
}
@Override
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
mRWinProgress = false;
Log.d(TAG, "->->-> onCharacteristicRead status: " + (status == 0 ? "Success. " : status));
if (status == BluetoothGatt.GATT_SUCCESS) {
// On the first successful read we enable the services
if (mBleConnectionState == BleConnectionState.BLE_CONNECTED) {
Log.d(TAG, "GATT services initializing...");
mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_INITIALIZING;
mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
initialize();
}
byte[] responseBytes = characteristic.getValue();
Log.d(TAG, "->->-> onCharacteristicRead: " + bytesToHexString(responseBytes));
switch (characteristic.getUuid().toString()) {
case UUID_MQTT_PROXY_TXLARGE:
try {
mTxLargeObject.write(responseBytes);
if (responseBytes.length < mMaxPayloadLen) {
byte[] largeMessage = mTxLargeObject.toByteArray();
Log.d(TAG, "MQTT Large object received from device successfully: "
+ bytesToHexString(largeMessage));
handleMqttTxMessage(largeMessage);
mTxLargeObject.reset();
} else {
sendBleCommand(new BleCommand(READ_CHARACTERISTIC,
UUID_MQTT_PROXY_TXLARGE, UUID_MQTT_PROXY_SERVICE));
}
} catch (IOException e) {
Log.e(TAG, "Failed to concatenate byte array.", e);
}
break;
case UUID_NETWORK_TXLARGE:
try {
mTxLargeNw.write(responseBytes);
if (responseBytes.length < mMaxPayloadLen) {
byte[] largeMessage = mTxLargeNw.toByteArray();
Log.d(TAG, "NW Large object received from device successfully: "
+ bytesToHexString(largeMessage));
handleNwTxMessage(largeMessage);
mTxLargeNw.reset();
} else {
sendBleCommand(new BleCommand(READ_CHARACTERISTIC,
UUID_NETWORK_TXLARGE, UUID_NETWORK_SERVICE));
}
} catch (IOException e) {
Log.e(TAG, "Failed to concatenate byte array.", e);
}
break;
case UUID_DEVICE_MTU:
Mtu currentMtu = new Mtu();
currentMtu.mtu = new String(responseBytes);
Log.i(TAG, "Default MTU is set to: " + currentMtu.mtu);
try {
mMtu = Integer.parseInt(currentMtu.mtu);
mMaxPayloadLen = Math.max(mMtu - 3, 0);
if (mDeviceInfoCallback != null) {
mDeviceInfoCallback.onObtainMtu(mMtu);
}
setMtu(mMtu);
} catch (NumberFormatException e) {
Log.e(TAG, "Cannot parse default MTU value.");
}
break;
case UUID_IOT_ENDPOINT:
BrokerEndpoint currentEndpoint = new BrokerEndpoint();
currentEndpoint.brokerEndpoint = new String(responseBytes);
Log.i(TAG, "Current broker endpoint is set to: "
+ currentEndpoint.brokerEndpoint);
if (mDeviceInfoCallback != null) {
mDeviceInfoCallback.onObtainBrokerEndpoint(currentEndpoint.brokerEndpoint);
}
break;
case UUID_DEVICE_VERSION:
Version currentVersion = new Version();
currentVersion.version = new String(responseBytes);
if (!currentVersion.version.isEmpty()) {
mAmazonFreeRTOSLibVersion = currentVersion.version;
}
Log.i(TAG, "Ble software version on device is: " + currentVersion.version);
if (mDeviceInfoCallback != null) {
mDeviceInfoCallback.onObtainDeviceSoftwareVersion(currentVersion.version);
}
break;
case UUID_DEVICE_PLATFORM:
String platform = new String(responseBytes);
if (!platform.isEmpty()) {
mAmazonFreeRTOSDeviceType = platform;
}
Log.i(TAG, "Device type is: " + mAmazonFreeRTOSDeviceType);
break;
case UUID_DEVICE_ID:
String devId = new String(responseBytes);
if (!devId.isEmpty()) {
mAmazonFreeRTOSDeviceId = devId;
}
Log.i(TAG, "Device id is: " + mAmazonFreeRTOSDeviceId);
break;
default:
Log.w(TAG, "Unknown characteristic read. ");
}
}
processIncomingQueue();
processNextBleCommand();
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
mRWinProgress = false;
byte[] value = characteristic.getValue();
Log.d(TAG, "onCharacteristicWrite for: "
+ uuidToName.get(characteristic.getUuid().toString())
+ "; status: " + (status == 0 ? "Success" : status) + "; value: " + bytesToHexString(value));
if (Arrays.equals(mValueWritten, value)) {
processIncomingQueue();
processNextBleCommand();
} else {
Log.e(TAG, "values don't match!");
}
}
};
/**
* Handle mqtt messages received from device.
*
* @param message message received from device.
*/
private void handleMqttTxMessage(byte[] message) {
MessageType messageType = new MessageType();
if (!messageType.decode(message)) {
return;
}
Log.i(TAG, "Handling Mqtt Message type : " + messageType.type);
switch (messageType.type) {
case MQTT_MSG_CONNECT:
final Connect connect = new Connect();
if (connect.decode(message)) {
connectToIoT(connect);
}
break;
case MQTT_MSG_SUBSCRIBE:
final Subscribe subscribe = new Subscribe();
if (subscribe.decode(message)) {
Log.d(TAG, subscribe.toString());
subscribeToIoT(subscribe);
/*
Currently, because the IoT part of aws mobile sdk for Android
does not provide suback callback when subscribe is successful,
we create a fake suback message and send to device as a workaround.
Wait for 0.5 sec so that the subscribe is complete. Potential bug:
Message is received from the subscribed topic before suback
is sent to device.
*/
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
sendSubAck(subscribe);
}
}, 500);
}
break;
case MQTT_MSG_UNSUBSCRIBE:
final Unsubscribe unsubscribe = new Unsubscribe();
if (unsubscribe.decode(message)) {
unsubscribeToIoT(unsubscribe);
/*
TODO: add unsuback support in Aws Mobile sdk
*/
sendUnsubAck(unsubscribe);
}
break;
case MQTT_MSG_PUBLISH:
final Publish publish = new Publish();
if (publish.decode(message)) {
mMessageId = publish.getMsgID();
publishToIoT(publish);
}
break;
case MQTT_MSG_DISCONNECT:
disconnectFromIot();
break;
case MQTT_MSG_PUBACK:
/*
AWS Iot SDK currently sends pub ack back to cloud without waiting
for pub ack from device.
*/
final Puback puback = new Puback();
if (puback.decode(message)) {
Log.w(TAG, "Received mqtt pub ack from device. MsgID: " + puback.msgID);
}
break;
case MQTT_MSG_PINGREQ:
PingResp pingResp = new PingResp();
byte[] pingRespBytes = pingResp.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, pingRespBytes);
break;
default:
Log.e(TAG, "Unknown mqtt message type: " + messageType.type);
}
}
private void handleNwTxMessage(byte[] message) {
MessageType messageType = new MessageType();
if (!messageType.decode(message)) {
return;
}
Log.i(TAG, "Handling Network Message type : " + messageType.type);
switch (messageType.type) {
case LIST_NETWORK_RESP:
ListNetworkResp listNetworkResp = new ListNetworkResp();
if (listNetworkResp.decode(message) && mNetworkConfigCallback != null) {
Log.d(TAG, listNetworkResp.toString());
mNetworkConfigCallback.onListNetworkResponse(listNetworkResp);
}
break;
case SAVE_NETWORK_RESP:
SaveNetworkResp saveNetworkResp = new SaveNetworkResp();
if (saveNetworkResp.decode(message) && mNetworkConfigCallback != null) {
mNetworkConfigCallback.onSaveNetworkResponse(saveNetworkResp);
}
break;
case EDIT_NETWORK_RESP:
EditNetworkResp editNetworkResp = new EditNetworkResp();
if (editNetworkResp.decode(message) && mNetworkConfigCallback != null) {
mNetworkConfigCallback.onEditNetworkResponse(editNetworkResp);
}
break;
case DELETE_NETWORK_RESP:
DeleteNetworkResp deleteNetworkResp = new DeleteNetworkResp();
if (deleteNetworkResp.decode(message) && mNetworkConfigCallback != null) {
mNetworkConfigCallback.onDeleteNetworkResponse(deleteNetworkResp);
}
break;
default:
Log.e(TAG, "Unknown network message type: " + messageType.type);
}
}
private void connectToIoT(final Connect connect) {
if (mMqttConnectionState == AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) {
Log.w(TAG, "Already connected to IOT, sending connack to device again.");
sendConnAck();
return;
}
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) {
Log.w(TAG, "Previous connection is active, please retry or disconnect mqtt first.");
return;
}
mIotMqttManager = new AWSIotMqttManager(connect.clientID, connect.brokerEndpoint);
Map<String, String> userMetaData = new HashMap<>();
userMetaData.put("AFRSDK", "Android");
//userMetaData.put("AFRSDKVersion", AMAZONFREERTOS_SDK_VERSION);
userMetaData.put("AFRLibVersion", mAmazonFreeRTOSLibVersion);
userMetaData.put("Platform", mAmazonFreeRTOSDeviceType);
userMetaData.put("AFRDevID", mAmazonFreeRTOSDeviceId);
mIotMqttManager.updateUserMetaData(userMetaData);
AWSIotMqttClientStatusCallback mqttClientStatusCallback = new AWSIotMqttClientStatusCallback() {
@Override
public void onStatusChanged(AWSIotMqttClientStatus status, Throwable throwable) {
Log.i(TAG, "mqtt connection status changed to: " + status);
switch (status) {
case Connected:
mMqttConnectionState = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected;
//sending connack
if (isBLEConnected() && mBluetoothGatt != null) {
sendConnAck();
} else {
Log.e(TAG, "Cannot send CONNACK because BLE connection is: " + mBleConnectionState);
}
break;
case Connecting:
case Reconnecting:
mMqttConnectionState = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connecting;
break;
case ConnectionLost:
mMqttConnectionState = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected;
break;
default:
Log.e(TAG, "Unknown mqtt connection state: " + status);
}
}
};
if (mKeystore != null) {
Log.i(TAG, "Connecting to IoT using KeyStore: " + connect.brokerEndpoint);
mIotMqttManager.connect(mKeystore, mqttClientStatusCallback);
} else {
Log.i(TAG, "Connecting to IoT using AWS credential: " + connect.brokerEndpoint);
mIotMqttManager.connect(mAWSCredential, mqttClientStatusCallback);
}
}
private void disconnectFromIot() {
if (mIotMqttManager != null) {
try {
mIotMqttManager.disconnect();
mMqttConnectionState = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected;
} catch (Exception e) {
Log.e(TAG, "Mqtt disconnect error: ", e);
}
}
}
private void subscribeToIoT(final Subscribe subscribe) {
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) {
Log.e(TAG, "Cannot subscribe because mqtt state is not connected.");
return;
}
for (int i = 0; i < subscribe.topics.size(); i++) {
try {
String topic = subscribe.topics.get(i);
Log.i(TAG, "Subscribing to IoT on topic : " + topic);
final int QoS = subscribe.qoSs.get(i);
AWSIotMqttQos qos = (QoS == 0 ? AWSIotMqttQos.QOS0 : AWSIotMqttQos.QOS1);
mIotMqttManager.subscribeToTopic(topic, qos, new AWSIotMqttNewMessageCallback() {
@Override
public void onMessageArrived(final String topic, final byte[] data) {
String message = new String(data, StandardCharsets.UTF_8);
Log.i(TAG, " Message arrived on topic: " + topic);
Log.v(TAG, " Message: " + message);
Publish publish = new Publish(
MQTT_MSG_PUBLISH,
topic,
mMessageId,
QoS,
data
);
publishToDevice(publish);
}
});
} catch (Exception e) {
Log.e(TAG, "Subscription error.", e);
}
}
}
private void unsubscribeToIoT(final Unsubscribe unsubscribe) {
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) {
Log.e(TAG, "Cannot unsubscribe because mqtt state is not connected.");
return;
}
for (int i = 0; i < unsubscribe.topics.size(); i++) {
try {
String topic = unsubscribe.topics.get(i);
Log.i(TAG, "UnSubscribing to IoT on topic : " + topic);
mIotMqttManager.unsubscribeTopic(topic);
} catch (Exception e) {
Log.e(TAG, "Unsubscribe error.", e);
}
}
}
private void publishToIoT(final Publish publish) {
if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) {
Log.e(TAG, "Cannot publish message to IoT because mqtt connection state is not connected.");
return;
}
AWSIotMqttMessageDeliveryCallback deliveryCallback = new AWSIotMqttMessageDeliveryCallback() {
@Override
public void statusChanged(MessageDeliveryStatus messageDeliveryStatus, Object o) {
Log.d(TAG, "Publish msg delivery status: " + messageDeliveryStatus.toString());
if (messageDeliveryStatus == MessageDeliveryStatus.Success && publish.getQos() == 1) {
sendPubAck(publish);
}
}
};
try {
String topic = publish.getTopic();
byte[] data = publish.getPayload();
Log.i(TAG, "Sending mqtt message to IoT on topic: " + topic
+ " message: " + new String(data)
+ " MsgID: " + publish.getMsgID());
mIotMqttManager.publishData(data, topic, AWSIotMqttQos.values()[publish.getQos()],
deliveryCallback, null);
} catch (Exception e) {
Log.e(TAG, "Publish error.", e);
}
}
private void sendConnAck() {
Connack connack = new Connack();
connack.type = MQTT_MSG_CONNACK;
connack.status = AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected.ordinal();
byte[] connackBytes = connack.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, connackBytes);
}
private boolean isBLEConnected() {
return mBleConnectionState == BleConnectionState.BLE_CONNECTED ||
mBleConnectionState == BleConnectionState.BLE_INITIALIZED ||
mBleConnectionState == BleConnectionState.BLE_INITIALIZING;
}
private void sendSubAck(final Subscribe subscribe) {
if (!isBLEConnected() && mBluetoothGatt != null) {
Log.e(TAG, "Cannot send SUB ACK to BLE device because BLE connection state" +
" is not connected");
return;
}
Log.i(TAG, "Sending SUB ACK back to device.");
Suback suback = new Suback();
suback.type = MQTT_MSG_SUBACK;
suback.msgID = subscribe.msgID;
suback.status = subscribe.qoSs.get(0);
byte[] subackBytes = suback.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, subackBytes);
}
private void sendUnsubAck(final Unsubscribe unsubscribe) {
if (!isBLEConnected() && mBluetoothGatt != null) {
Log.e(TAG, "Cannot send Unsub ACK to BLE device because BLE connection state" +
" is not connected");
return;
}
Log.i(TAG, "Sending Unsub ACK back to device.");
Unsuback unsuback = new Unsuback();
unsuback.type = MQTT_MSG_UNSUBACK;
unsuback.msgID = unsubscribe.msgID;
byte[] unsubackBytes = unsuback.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, unsubackBytes);
}
private void sendPubAck(final Publish publish) {
if (!isBLEConnected() && mBluetoothGatt != null) {
Log.e(TAG, "Cannot send PUB ACK to BLE device because BLE connection state" +
" is not connected");
return;
}
Log.i(TAG, "Sending PUB ACK back to device. MsgID: " + publish.getMsgID());
Puback puback = new Puback();
puback.type = MQTT_MSG_PUBACK;
puback.msgID = publish.getMsgID();
byte[] pubackBytes = puback.encode();
sendDataToDevice(UUID_MQTT_PROXY_SERVICE, UUID_MQTT_PROXY_RX, UUID_MQTT_PROXY_RXLARGE, pubackBytes);
}