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
 
package com.clj.fastble.conn;
 
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
 
import com.clj.fastble.bluetooth.BleBluetooth;
import com.clj.fastble.exception.GattException;
import com.clj.fastble.exception.OtherException;
import com.clj.fastble.exception.TimeoutException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
 
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
 
/**
 * Ble Device Connector.
 * be sure main thread
 */
public class BleConnector {
 
    private static final String TAG = BleConnector.class.getSimpleName();
    private static final String UUID_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR = "00002902-0000-1000-8000-00805f9b34fb";
 
    private static final int MSG_WRITE_CHA = 1;
    private static final int MSG_WRIATE_DES = 2;
    private static final int MSG_READ_CHA = 3;
    private static final int MSG_READ_DES = 4;
    private static final int MSG_READ_RSSI = 5;
    private static final int MSG_NOTIFY_CHA = 6;
    private static final int MSG_NOTIY_DES = 7;
    private static final int MSG_INDICATE_DES = 8;
 
    private BluetoothGatt bluetoothGatt;
    private BluetoothGattService service;
    private BluetoothGattCharacteristic characteristic;
    private BluetoothGattDescriptor descriptor;
    private BleBluetooth bleBluetooth;
    private static int timeOutMillis = 10000;
    private Handler handler = new MyHandler();
 
    private static final class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
 
            BleCallback call = (BleCallback) msg.obj;
            if (call != null) {
                call.onFailure(new TimeoutException());
            }
            msg.obj = null;
        }
    }
 
    public BleConnector(BleBluetooth bleBluetooth) {
        this.bleBluetooth = bleBluetooth;
        this.bluetoothGatt = bleBluetooth.getBluetoothGatt();
        this.handler = new Handler(Looper.getMainLooper());
    }
 
    public BleConnector(BleBluetooth bleBluetooth, BluetoothGattService service,
                        BluetoothGattCharacteristic characteristic, BluetoothGattDescriptor descriptor) {
        this(bleBluetooth);
        this.service = service;
        this.characteristic = characteristic;
        this.descriptor = descriptor;
    }
 
    public BleConnector(BleBluetooth bleBluetooth,
                        UUID serviceUUID, UUID charactUUID,
                        UUID descriptorUUID, UUID client_characteristic_conifgUUID) {
        this(bleBluetooth);
        withUUID(serviceUUID, charactUUID, descriptorUUID);
    }
 
    public BleConnector(BleBluetooth bleBluetooth,
                        String serviceUUID, String charactUUID,
                        String descriptorUUID, String client_characteristic_conifgUUID) {
        this(bleBluetooth);
        withUUIDString(serviceUUID, charactUUID, descriptorUUID);
    }
 
 
    public BleConnector withUUID(UUID serviceUUID, UUID charactUUID, UUID descriptorUUID) {
 
        if (serviceUUID != null && bluetoothGatt != null) {
            service = bluetoothGatt.getService(serviceUUID);
        }
 
        if (service != null && charactUUID != null) {
            characteristic = service.getCharacteristic(charactUUID);
        }
 
        if (characteristic != null && descriptorUUID != null) {
            descriptor = characteristic.getDescriptor(descriptorUUID);
        }
 
 
        return this;
    }
 
    public BleConnector withUUIDString(String serviceUUID, String charactUUID,
                                       String descriptorUUID) {
        return withUUID(formUUID(serviceUUID), formUUID(charactUUID), formUUID(descriptorUUID));
    }
 
    private UUID formUUID(String uuid) {
        return uuid == null ? null : UUID.fromString(uuid);
    }
 
 
 
 
    /*------------------------------- main operation ----------------------------------- */
 
 
    /**
     * notify
     */
    public boolean enableCharacteristicNotify(BleCharacterCallback bleCallback, String uuid_notify) {
 
        if (getCharacteristic() != null
                && (getCharacteristic().getProperties() | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            BleLog.w(TAG, "characteristic.getProperties():" + getCharacteristic().getProperties());
 
            System.out.println("chenqi enableCharacteristicNotify =>" + uuid_notify);
 
            handleCharacteristicNotificationCallback(bleCallback, uuid_notify);
 
            return setCharacteristicNotification(getBluetoothGatt(), getCharacteristic(), true, bleCallback);
 
        } else {
            if (bleCallback != null) {
                bleCallback.onFailure(new OtherException("this characteristic not support notify!"));
                bleCallback.onInitiatedResult(false);
            }
            return false;
        }
    }
 
    /**
     * stop notify
     */
    public boolean disableCharacteristicNotify() {
        if (getCharacteristic() != null
                && (getCharacteristic().getProperties() | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            BleLog.w(TAG, "characteristic.getProperties():" + getCharacteristic().getProperties());
 
            return setCharacteristicNotification(getBluetoothGatt(), getCharacteristic(), false, null);
        } else {
            return false;
        }
    }
 
    /**
     * notify setting
     */
    private boolean setCharacteristicNotification(BluetoothGatt gatt,
                                                  BluetoothGattCharacteristic characteristic,
                                                  boolean enable,
                                                  BleCharacterCallback bleCallback) {
        if (gatt == null || characteristic == null) {
            if (bleCallback != null) {
                bleCallback.onFailure(new OtherException("gatt or characteristic equal null"));
                bleCallback.onInitiatedResult(false);
            }
            return false;
        }
 
        boolean success = gatt.setCharacteristicNotification(characteristic, enable);
        BleLog.d(TAG, "setCharacteristicNotification: " + enable
                + "\nsuccess: " + success
                + "\ncharacteristic.getUuid(): " + characteristic.getUuid());
 
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(formUUID(UUID_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR));
        if (descriptor != null) {
            descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
                    BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
            boolean success2 = gatt.writeDescriptor(descriptor);
            if (bleCallback != null) {
                bleCallback.onInitiatedResult(success2);
            }
            return success2;
        }
        if (bleCallback != null) {
            bleCallback.onFailure(new OtherException("notify operation failed"));
            bleCallback.onInitiatedResult(false);
        }
        return false;
    }
 
    /**
     * indicate
     */
    public boolean enableCharacteristicIndicate(BleCharacterCallback bleCallback, String uuid_indicate) {
        if (getCharacteristic() != null
                && (getCharacteristic().getProperties() | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            BleLog.w(TAG, "characteristic.getProperties():" + getCharacteristic().getProperties());
 
            handleCharacteristicIndicationCallback(bleCallback, uuid_indicate);
 
            return setCharacteristicIndication(getBluetoothGatt(), getCharacteristic(), true, bleCallback);
 
        } else {
            if (bleCallback != null) {
                bleCallback.onFailure(new OtherException("this characteristic not support indicate!"));
            }
            return false;
        }
    }
 
 
    /**
     * stop indicate
     */
    public boolean disableCharacteristicIndicate() {
        if (getCharacteristic() != null
                && (getCharacteristic().getProperties() | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            BleLog.w(TAG, "characteristic.getProperties():" + getCharacteristic().getProperties());
 
            return setCharacteristicIndication(getBluetoothGatt(), getCharacteristic(), false, null);
 
        } else {
            return false;
        }
    }
 
    /**
     * indicate setting
     */
    private boolean setCharacteristicIndication(BluetoothGatt gatt,
                                                BluetoothGattCharacteristic characteristic,
                                                boolean enable,
                                                BleCharacterCallback bleCallback) {
        if (gatt == null || characteristic == null) {
            if (bleCallback != null) {
                bleCallback.onFailure(new OtherException("gatt or characteristic equal null"));
                bleCallback.onInitiatedResult(false);
            }
            return false;
        }
 
        boolean success = gatt.setCharacteristicNotification(characteristic, enable);
        BleLog.d(TAG, "setCharacteristicIndication:" + enable
                + "\nsuccess:" + success
                + "\ncharacteristic.getUuid():" + characteristic.getUuid());
 
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(formUUID(UUID_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR));
        if (descriptor != null) {
            descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE :
                    BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
            boolean success2 = gatt.writeDescriptor(descriptor);
            if (bleCallback != null) {
                bleCallback.onInitiatedResult(success2);
            }
            return success2;
        }
        if (bleCallback != null) {
            bleCallback.onFailure(new OtherException("indicate operation failed"));
            bleCallback.onInitiatedResult(false);
        }
        return false;
    }
 
 
    /**
     * write
     */
    public boolean writeCharacteristic(byte[] data, BleCharacterCallback bleCallback, String uuid_write) {
        if (data == null) {
            if (bleCallback != null) {
                bleCallback.onFailure(new OtherException("the data to be written is empty"));
                bleCallback.onInitiatedResult(false);
            }
            return false;
        }
 
        if (getCharacteristic() == null
                || (getCharacteristic().getProperties() & (BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) == 0) {
            if (bleCallback != null) {
                bleCallback.onFailure(new OtherException("this characteristic not support write!"));
                bleCallback.onInitiatedResult(false);
            }
            return false;
        }
 
        BleLog.d(TAG, getCharacteristic().getUuid()
                + "\ncharacteristic.getProperties():" + getCharacteristic().getProperties()
                + "\ncharacteristic.getValue(): " + Arrays.toString(getCharacteristic().getValue())
                + "\ncharacteristic write bytes: " + Arrays.toString(data)
                + "\nhex: " + HexUtil.encodeHexStr(data));
 
        handleCharacteristicWriteCallback(bleCallback, uuid_write);
        getCharacteristic().setValue(data);
        return handleAfterInitialed(getBluetoothGatt().writeCharacteristic(getCharacteristic()), bleCallback);
    }
 
    /**
     * read
     */
    public boolean readCharacteristic(BleCharacterCallback bleCallback, String uuid_read) {
        if (getCharacteristic() != null
                && (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
 
            BleLog.d(TAG, getCharacteristic().getUuid()
                    + "\ncharacteristic.getProperties(): " + getCharacteristic().getProperties()
                    + "\ncharacteristic.getValue(): " + Arrays.toString(getCharacteristic().getValue()));
 
            setCharacteristicNotification(getBluetoothGatt(), getCharacteristic(), false, bleCallback);
            handleCharacteristicReadCallback(bleCallback, uuid_read);
            return handleAfterInitialed(getBluetoothGatt().readCharacteristic(getCharacteristic()), bleCallback);
 
        } else {
            if (bleCallback != null) {
                bleCallback.onFailure(new OtherException("this characteristic not support read!"));
                bleCallback.onInitiatedResult(false);
            }
            return false;
        }
    }
 
    /**
     * rssi
     */
    public boolean readRemoteRssi(BleRssiCallback bleCallback) {
        handleRSSIReadCallback(bleCallback);
        return handleAfterInitialed(getBluetoothGatt().readRemoteRssi(), bleCallback);
    }
 
 
    /**************************************** handle call back ******************************************/
 
    /**
     * notify
     */
    private void handleCharacteristicNotificationCallback(final BleCharacterCallback bleCallback,
                                                          final String uuid_notify) {
        if (bleCallback != null) {
 
            listenAndTimer(bleCallback, MSG_NOTIFY_CHA, uuid_notify, new BluetoothGattCallback() {
                AtomicBoolean msgRemoved = new AtomicBoolean(false);
                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt,
                                                    BluetoothGattCharacteristic characteristic) {
                    if (!msgRemoved.getAndSet(true)) {
                        handler.removeMessages(MSG_NOTIFY_CHA, this);
                    }
 
                    System.out.println("chenqi Notify Hex ->" + BleBluetooth.dumpHex(characteristic.getValue()));
 
                    if (characteristic.getUuid().equals(UUID.fromString(uuid_notify))) {
                        bleCallback.onSuccess(characteristic);
                    }
                }
            });
 
 
        }
    }
 
    /**
     * indicate
     */
    private void handleCharacteristicIndicationCallback(final BleCharacterCallback bleCallback,
                                                        final String uuid_indicate) {
        if (bleCallback != null) {
 
            listenAndTimer(bleCallback, MSG_INDICATE_DES, uuid_indicate, new BluetoothGattCallback() {
                AtomicBoolean msgRemoved = new AtomicBoolean(false);
 
                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt,
                                                    BluetoothGattCharacteristic characteristic) {
                    System.out.println("chenqi Notify Hex indicate->" + BleBluetooth.dumpHex(characteristic.getValue()));
                    if (!msgRemoved.getAndSet(true)) {
                        handler.removeMessages(MSG_INDICATE_DES, this);
                    }
                    if (characteristic.getUuid().equals(UUID.fromString(uuid_indicate))) {
                        bleCallback.onSuccess(characteristic);
                    }
                }
            });
        }
    }
 
    /**
     * write
     */
    private void handleCharacteristicWriteCallback(final BleCharacterCallback bleCallback,
                                                   final String uuid_write) {
        if (bleCallback != null) {
 
            listenAndTimer(bleCallback, MSG_WRITE_CHA, uuid_write, new BluetoothGattCallback() {
                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt,
                                                  BluetoothGattCharacteristic characteristic, int status) {
                    handler.removeMessages(MSG_WRITE_CHA, this);
                    System.out.println("chenqi Notify Hex write->" + BleBluetooth.dumpHex(characteristic.getValue()));
 
 
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        if (characteristic.getUuid().equals(UUID.fromString(uuid_write))) {
                            bleCallback.onSuccess(characteristic);
                        }
                    } else {
                        bleCallback.onFailure(new GattException(status));
                    }
                }
            });
        }
    }
 
    /**
     * read
     */
    private void handleCharacteristicReadCallback(final BleCharacterCallback bleCallback,
                                                  final String uuid_read) {
        if (bleCallback != null) {
            listenAndTimer(bleCallback, MSG_READ_CHA, uuid_read, new BluetoothGattCallback() {
                AtomicBoolean msgRemoved = new AtomicBoolean(false);
 
                @Override
                public void onCharacteristicRead(BluetoothGatt gatt,
                                                 BluetoothGattCharacteristic characteristic, int status) {
                    System.out.println("chenqi Notify Hex indicate read->" + BleBluetooth.dumpHex(characteristic.getValue()));
 
                    if (!msgRemoved.getAndSet(true)) {
                        handler.removeMessages(MSG_READ_CHA, this);
                    }
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        if (characteristic.getUuid().equals(UUID.fromString(uuid_read))) {
                            bleCallback.onSuccess(characteristic);
                        }
                    } else {
                        bleCallback.onFailure(new GattException(status));
                    }
                }
            });
        }
    }
 
    /**
     * rssi
     */
    private void handleRSSIReadCallback(final BleRssiCallback bleCallback) {
 
        if (bleCallback != null) {
            listenAndTimer(bleCallback, MSG_READ_RSSI, BleBluetooth.READ_RSSI_KEY, new BluetoothGattCallback() {
                @Override
                public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
                    handler.removeMessages(MSG_READ_RSSI, this);
                    System.out.println("chenqi Notify Hex rssi->" + BleBluetooth.dumpHex(characteristic.getValue()));
 
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        bleCallback.onSuccess(rssi);
                    } else {
                        bleCallback.onFailure(new GattException(status));
                    }
                }
            });
        }
    }
 
    private boolean handleAfterInitialed(boolean initiated, BleCallback bleCallback) {
        if (bleCallback != null) {
            if (!initiated) {
                bleCallback.onFailure(new OtherException("write or read operation failed"));
            }
            bleCallback.onInitiatedResult(initiated);
        }
        return initiated;
    }
 
 
    /**
     * listen bleBluetooth gatt callback, and send a delayed message.
     */
    private void listenAndTimer(BleCallback bleCallback, int what, String uuid, BluetoothGattCallback callback) {
        bleCallback.setBluetoothGattCallback(callback);
        bleBluetooth.addGattCallback(uuid, callback);
        Message msg = handler.obtainMessage(what, bleCallback);
        handler.sendMessageDelayed(msg, timeOutMillis);
    }
 
 
 
    /*------------------------------- getter and setter ----------------------------------- */
 
 
    public BluetoothGatt getBluetoothGatt() {
        return bluetoothGatt;
    }
 
    public BleConnector setBluetoothGatt(BluetoothGatt bluetoothGatt) {
        this.bluetoothGatt = bluetoothGatt;
        return this;
    }
 
    public BluetoothGattService getService() {
        return service;
    }
 
    public BleConnector setService(BluetoothGattService service) {
        this.service = service;
        return this;
    }
 
    public BluetoothGattCharacteristic getCharacteristic() {
        return characteristic;
    }
 
    public BleConnector setCharacteristic(BluetoothGattCharacteristic characteristic) {
        this.characteristic = characteristic;
        return this;
    }
 
    public BluetoothGattDescriptor getDescriptor() {
        return descriptor;
    }
 
    public BleConnector setDescriptor(BluetoothGattDescriptor descriptor) {
        this.descriptor = descriptor;
        return this;
    }
 
    public int getTimeOutMillis() {
        return timeOutMillis;
    }
 
    public BleConnector setTimeOutMillis(int timeOutMillis) {
        this.timeOutMillis = timeOutMillis;
        return this;
    }
}