Peripheral.java 29.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 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
/*
 * Copyright (C) 2015 The Telink Bluetooth Light Project
 *
 */
package com.telink.bluetooth;

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.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;

import com.telink.util.Arrays;

import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Peripheral extends BluetoothGattCallback {

    public static final int CONNECTION_PRIORITY_BALANCED = 0;
    public static final int CONNECTION_PRIORITY_HIGH = 1;
    public static final int CONNECTION_PRIORITY_LOW_POWER = 2;

    private static final int CONN_STATE_IDLE = 1;
    private static final int CONN_STATE_CONNECTING = 2;
    private static final int CONN_STATE_CONNECTED = 4;
    private static final int CONN_STATE_DISCONNECTING = 8;
    private static final int CONN_STATE_CLOSED = 16;

    private static final int RSSI_UPDATE_TIME_INTERVAL = 2000;

    protected final Queue<CommandContext> mInputCommandQueue = new ConcurrentLinkedQueue<>();
    protected final Queue<CommandContext> mOutputCommandQueue = new ConcurrentLinkedQueue<>();
    protected final Map<String, CommandContext> mNotificationCallbacks = new ConcurrentHashMap<>();

    protected final Handler mTimeoutHandler = new Handler(Looper.getMainLooper());
    protected final Handler mRssiUpdateHandler = new Handler(Looper.getMainLooper());
    protected final Handler mDelayHandler = new Handler(Looper.getMainLooper());
    protected final Runnable mRssiUpdateRunnable = new RssiUpdateRunnable();
    protected final Runnable mCommandTimeoutRunnable = new CommandTimeoutRunnable();
    protected final Runnable mCommandDelayRunnable = new CommandDelayRunnable();

    private final Object mStateLock = new Object();
    private final Object mProcessLock = new Object();

    protected BluetoothDevice device;
    protected BluetoothGatt gatt;
    protected int rssi;
    protected byte[] scanRecord;
    protected String name;
    protected String mac;
    protected byte[] macBytes;
    protected int type;
    protected List<BluetoothGattService> mServices;

    protected Boolean processing = false;

    protected boolean monitorRssi;
    protected int updateIntervalMill = 5 * 1000;
    protected int commandTimeoutMill = 10 * 1000;
    protected long lastTime;
    private int mConnState = CONN_STATE_IDLE;

    public Peripheral(BluetoothDevice device, byte[] scanRecord, int rssi) {

        this.device = device;
        this.scanRecord = scanRecord;
        this.rssi = rssi;

        this.name = device.getName();
        this.mac = device.getAddress();
        this.type = device.getType();
    }

    /********************************************************************************
     * Public API
     *******************************************************************************/

    public BluetoothDevice getDevice() {
        return this.device;
    }

    public String getDeviceName() {
        return this.name;
    }

    public String getMacAddress() {
        return this.mac;
    }

    public List<BluetoothGattService> getServices() {
        return mServices;
    }

    public byte[] getMacBytes() {

        if (this.macBytes == null) {
            String[] strArray = this.getMacAddress().split(":");
            int length = strArray.length;
            this.macBytes = new byte[length];

            for (int i = 0; i < length; i++) {
                this.macBytes[i] = (byte) (Integer.parseInt(strArray[i], 16) & 0xFF);
            }

            Arrays.reverse(this.macBytes, 0, length - 1);
        }

        return this.macBytes;
    }

    public int getType() {
        return this.type;
    }

    public int getRssi() {
        return this.rssi;
    }

    public boolean isConnected() {
        synchronized (this.mStateLock) {
            return this.mConnState == CONN_STATE_CONNECTED;
        }
    }

    public void connect(Context context) {

        synchronized (this.mStateLock) {
            this.lastTime = 0;
            if (this.mConnState == CONN_STATE_IDLE) {
                TelinkLog.d("connect " + this.getDeviceName() + " -- "
                        + this.getMacAddress());
                this.mConnState = CONN_STATE_CONNECTING;
                this.gatt = this.device.connectGatt(context, false, this);
                if (this.gatt == null) {
                    this.disconnect();
                    this.mConnState = CONN_STATE_IDLE;
                    this.onDisconnect();
                }
            }
        }
    }

    public void disconnect() {

        synchronized (this.mStateLock) {
            if (this.mConnState != CONN_STATE_CONNECTING && this.mConnState != CONN_STATE_CONNECTED)
                return;
        }

        TelinkLog.d("disconnect " + this.getDeviceName() + " -- "
                + this.getMacAddress());

        this.clear();

        synchronized (this.mStateLock) {
            if (this.gatt != null) {
                int connState = this.mConnState;
                if (connState == CONN_STATE_CONNECTED) {
                    this.gatt.disconnect();
                    this.mConnState = CONN_STATE_DISCONNECTING;
                } else {
                    this.gatt.disconnect();
                    this.gatt.close();
                    this.mConnState = CONN_STATE_CLOSED;
                }
            } else {
                this.mConnState = CONN_STATE_IDLE;
            }
        }
    }

    private void clear() {
        this.processing = false;
        this.stopMonitoringRssi();
        this.cancelCommandTimeoutTask();
        this.mInputCommandQueue.clear();
        this.mOutputCommandQueue.clear();
        this.mNotificationCallbacks.clear();
        this.mDelayHandler.removeCallbacksAndMessages(null);
    }

    public boolean sendCommand(Command.Callback callback, Command command) {

        synchronized (this.mStateLock) {
            if (this.mConnState != CONN_STATE_CONNECTED)
                return false;
        }

        CommandContext commandContext = new CommandContext(callback, command);
        this.postCommand(commandContext);

        return true;
    }

    public final void startMonitoringRssi(int interval) {

        this.monitorRssi = true;

        if (interval <= 0)
            this.updateIntervalMill = RSSI_UPDATE_TIME_INTERVAL;
        else
            this.updateIntervalMill = interval;
    }

    public final void stopMonitoringRssi() {
        this.monitorRssi = false;
        this.mRssiUpdateHandler.removeCallbacks(this.mRssiUpdateRunnable);
        this.mRssiUpdateHandler.removeCallbacksAndMessages(null);
    }

    public final boolean requestConnectionPriority(int connectionPriority) {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && this.gatt.requestConnectionPriority(connectionPriority);
    }

    /********************************************************************************
     * Protected API
     *******************************************************************************/

    protected void onConnect() {
        //this.requestConnectionPriority(CONNECTION_PRIORITY_BALANCED);
        this.enableMonitorRssi(this.monitorRssi);
    }

    protected void onDisconnect() {
        this.enableMonitorRssi(false);
    }

    protected void onServicesDiscovered(List<BluetoothGattService> services) {
    }

    protected void onNotify(byte[] data, UUID serviceUUID,
                            UUID characteristicUUID, Object tag) {
    }

    protected void onRssiChanged() {
    }

    protected void enableMonitorRssi(boolean enable) {

        if (enable) {
            this.mRssiUpdateHandler.removeCallbacks(this.mRssiUpdateRunnable);
            this.mRssiUpdateHandler.postDelayed(this.mRssiUpdateRunnable, this.updateIntervalMill);
        } else {
            this.mRssiUpdateHandler.removeCallbacks(this.mRssiUpdateRunnable);
            this.mRssiUpdateHandler.removeCallbacksAndMessages(null);
        }
    }

    /********************************************************************************
     * Command Handler API
     *******************************************************************************/

    private void postCommand(CommandContext commandContext) {
        TelinkLog.d("postCommand");
        if (commandContext.command.delay < 0) {
            synchronized (this.mOutputCommandQueue) {
                this.mOutputCommandQueue.add(commandContext);
                this.processCommand(commandContext);
            }
            return;
        }

        this.mInputCommandQueue.add(commandContext);
        synchronized (this.mProcessLock) {
            if (!this.processing) {
                this.processCommand();
            }
        }
    }

    private void processCommand() {
        TelinkLog.d("processing : " + this.processing);

        CommandContext commandContext;
        Command.CommandType commandType;

        synchronized (mInputCommandQueue) {
            if (this.mInputCommandQueue.isEmpty())
                return;
            commandContext = this.mInputCommandQueue.poll();
        }

        if (commandContext == null)
            return;

        commandType = commandContext.command.type;

        if (commandType != Command.CommandType.ENABLE_NOTIFY && commandType != Command.CommandType.DISABLE_NOTIFY) {
            synchronized (mOutputCommandQueue) {
                this.mOutputCommandQueue.add(commandContext);
            }

            synchronized (this.mProcessLock) {
                if (!this.processing)
                    this.processing = true;
            }
        }

        int delay = commandContext.command.delay;
        if (delay > 0) {
            long currentTime = System.currentTimeMillis();
            if (lastTime == 0 || (currentTime - lastTime) >= delay)
                this.processCommand(commandContext);
            else
                this.mDelayHandler.postDelayed(this.mCommandDelayRunnable, delay);
        } else {
            this.processCommand(commandContext);
        }
    }

    synchronized private void processCommand(CommandContext commandContext) {

        Command command = commandContext.command;
        Command.CommandType commandType = command.type;

        TelinkLog.d("processCommand : " + command.toString());

        switch (commandType) {
            case READ:
                this.postCommandTimeoutTask();
                this.readCharacteristic(commandContext, command.serviceUUID,
                        command.characteristicUUID);
                break;
            case WRITE:
                this.postCommandTimeoutTask();
                this.writeCharacteristic(commandContext, command.serviceUUID,
                        command.characteristicUUID,
                        BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
                        command.data);
                break;
            case WRITE_NO_RESPONSE:
                this.postCommandTimeoutTask();
                this.writeCharacteristic(commandContext, command.serviceUUID,
                        command.characteristicUUID,
                        BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE,
                        command.data);
                break;
            case ENABLE_NOTIFY:
                this.enableNotification(commandContext, command.serviceUUID,
                        command.characteristicUUID);
                break;
            case DISABLE_NOTIFY:
                this.disableNotification(commandContext, command.serviceUUID,
                        command.characteristicUUID);
                break;
        }
    }

    private void commandCompleted() {

        TelinkLog.d("commandCompleted");

        synchronized (this.mProcessLock) {
            if (this.processing)
                this.processing = false;
        }

        this.processCommand();
    }

    private void commandSuccess(CommandContext commandContext, Object data) {
        TelinkLog.d("commandSuccess");
        this.lastTime = System.currentTimeMillis();
        if (commandContext != null) {

            Command command = commandContext.command;
            Command.Callback callback = commandContext.callback;
            commandContext.clear();

            if (callback != null) {
                callback.success(this, command,
                        data);
            }
        }
    }

    private void commandSuccess(Object data) {
        CommandContext commandContext;
        commandContext = this.mOutputCommandQueue.poll();
        this.commandSuccess(commandContext, data);
    }

    private void commandError(CommandContext commandContext, String errorMsg) {
        TelinkLog.d("commandError");
        this.lastTime = System.currentTimeMillis();
        if (commandContext != null) {

            Command command = commandContext.command;
            Command.Callback callback = commandContext.callback;
            commandContext.clear();

            if (callback != null) {
                callback.error(this, command,
                        errorMsg);
            }
        }
    }

    private void commandError(String errorMsg) {
        CommandContext commandContext;
        commandContext = this.mOutputCommandQueue.poll();
        this.commandError(commandContext, errorMsg);
    }

    private boolean commandTimeout(CommandContext commandContext) {
        TelinkLog.d("commandTimeout");
        this.lastTime = System.currentTimeMillis();
        if (commandContext != null) {
            Command command = commandContext.command;
            Command.Callback callback = commandContext.callback;
            commandContext.clear();

            if (callback != null) {
                return callback.timeout(this, command);
            }
        }

        return false;
    }

    private void postCommandTimeoutTask() {

        if (this.commandTimeoutMill <= 0)
            return;

        this.mTimeoutHandler.removeCallbacksAndMessages(null);
        this.mTimeoutHandler.postDelayed(this.mCommandTimeoutRunnable, this.commandTimeoutMill);
    }

    private void cancelCommandTimeoutTask() {
        this.mTimeoutHandler.removeCallbacksAndMessages(null);
    }

    /********************************************************************************
     * Private API
     *******************************************************************************/

    private void readCharacteristic(CommandContext commandContext,
                                    UUID serviceUUID, UUID characteristicUUID) {

        boolean success = true;
        String errorMsg = "";

        BluetoothGattService service = this.gatt.getService(serviceUUID);

        if (service != null) {

            BluetoothGattCharacteristic characteristic = service
                    .getCharacteristic(characteristicUUID);

            if (characteristic != null) {

                if (!this.gatt.readCharacteristic(characteristic)) {
                    success = false;
                    errorMsg = "read characteristic error";
                }

            } else {
                success = false;
                errorMsg = "read characteristic error";
            }
        } else {
            success = false;
            errorMsg = "service is not offered by the remote device";
        }

        if (!success) {
            this.commandError(errorMsg);
            this.commandCompleted();
        }
    }

    private void writeCharacteristic(CommandContext commandContext,
                                     UUID serviceUUID, UUID characteristicUUID, int writeType,
                                     byte[] data) {

        boolean success = true;
        String errorMsg = "";

        BluetoothGattService service = this.gatt.getService(serviceUUID);

        if (service != null) {
            BluetoothGattCharacteristic characteristic = this
                    .findWritableCharacteristic(service, characteristicUUID,
                            writeType);
            if (characteristic != null) {

                characteristic.setValue(data);
                characteristic.setWriteType(writeType);

                if (!this.gatt.writeCharacteristic(characteristic)) {
                    success = false;
                    errorMsg = "write characteristic error";
                }

            } else {
                success = false;
                errorMsg = "no characteristic";
            }
        } else {
            success = false;
            errorMsg = "service is not offered by the remote device";
        }

        if (!success) {
            this.commandError(errorMsg);
            this.commandCompleted();
        }
    }

    private void enableNotification(CommandContext commandContext,
                                    UUID serviceUUID, UUID characteristicUUID) {

        boolean success = true;
        String errorMsg = "";

        BluetoothGattService service = this.gatt.getService(serviceUUID);

        if (service != null) {

            BluetoothGattCharacteristic characteristic = this
                    .findNotifyCharacteristic(service, characteristicUUID);

            if (characteristic != null) {

                if (!this.gatt.setCharacteristicNotification(characteristic,
                        true)) {
                    success = false;
                    errorMsg = "enable notification error";
                } else {
                    String key = this.generateHashKey(serviceUUID,
                            characteristic);
                    this.mNotificationCallbacks.put(key, commandContext);
                }

            } else {
                success = false;
                errorMsg = "no characteristic";
            }

        } else {
            success = false;
            errorMsg = "service is not offered by the remote device";
        }

        if (!success) {
            this.commandError(commandContext, errorMsg);
        }

        this.commandCompleted();
    }

    private void disableNotification(CommandContext commandContext,
                                     UUID serviceUUID, UUID characteristicUUID) {

        boolean success = true;
        String errorMsg = "";

        BluetoothGattService service = this.gatt.getService(serviceUUID);

        if (service != null) {

            BluetoothGattCharacteristic characteristic = this
                    .findNotifyCharacteristic(service, characteristicUUID);

            if (characteristic != null) {

                String key = this.generateHashKey(serviceUUID, characteristic);
                this.mNotificationCallbacks.remove(key);

                if (!this.gatt.setCharacteristicNotification(characteristic,
                        false)) {
                    success = false;
                    errorMsg = "disable notification error";
                }

            } else {
                success = false;
                errorMsg = "no characteristic";
            }

        } else {
            success = false;
            errorMsg = "service is not offered by the remote device";
        }

        if (!success) {
            this.commandError(commandContext, errorMsg);
        }

        this.commandCompleted();
    }

    private BluetoothGattCharacteristic findWritableCharacteristic(
            BluetoothGattService service, UUID characteristicUUID, int writeType) {

        BluetoothGattCharacteristic characteristic = null;

        int writeProperty = BluetoothGattCharacteristic.PROPERTY_WRITE;

        if (writeType == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE) {
            writeProperty = BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE;
        }

        List<BluetoothGattCharacteristic> characteristics = service
                .getCharacteristics();

        for (BluetoothGattCharacteristic c : characteristics) {
            if ((c.getProperties() & writeProperty) != 0
                    && characteristicUUID.equals(c.getUuid())) {
                characteristic = c;
                break;
            }
        }

        return characteristic;
    }

    private BluetoothGattCharacteristic findNotifyCharacteristic(
            BluetoothGattService service, UUID characteristicUUID) {

        BluetoothGattCharacteristic characteristic = null;

        List<BluetoothGattCharacteristic> characteristics = service
                .getCharacteristics();

        for (BluetoothGattCharacteristic c : characteristics) {
            if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0
                    && characteristicUUID.equals(c.getUuid())) {
                characteristic = c;
                break;
            }
        }

        if (characteristic != null)
            return characteristic;

        for (BluetoothGattCharacteristic c : characteristics) {
            if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0
                    && characteristicUUID.equals(c.getUuid())) {
                characteristic = c;
                break;
            }
        }

        return characteristic;
    }

    private String generateHashKey(BluetoothGattCharacteristic characteristic) {
        return this.generateHashKey(characteristic.getService().getUuid(),
                characteristic);
    }

    private String generateHashKey(UUID serviceUUID,
                                   BluetoothGattCharacteristic characteristic) {
        return String.valueOf(serviceUUID) + "|" + characteristic.getUuid()
                + "|" + characteristic.getInstanceId();
    }

    /********************************************************************************
     * Implements BluetoothGattCallback API
     *******************************************************************************/

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                        int newState) {
        TelinkLog.d("onConnectionStateChange  status :" + status + " state : "
                + newState);

        if (newState == BluetoothGatt.STATE_CONNECTED) {

            synchronized (this.mStateLock) {
                this.mConnState = CONN_STATE_CONNECTED;
            }

            if (this.gatt == null || !this.gatt.discoverServices()) {
                TelinkLog.d("remote service discovery has been stopped status = "
                        + newState);

                this.disconnect();

            } else {
                this.onConnect();
            }

        } else {

            synchronized (this.mStateLock) {
                TelinkLog.d("Close");

                if (this.gatt != null) {
                    this.gatt.close();
                    this.mConnState = CONN_STATE_CLOSED;
                }

                this.clear();
                this.mConnState = CONN_STATE_IDLE;
                this.onDisconnect();
            }
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(gatt, characteristic);

        String key = this.generateHashKey(characteristic);
        CommandContext commandContext = this.mNotificationCallbacks.get(key);

        if (commandContext != null) {

            this.onNotify(characteristic.getValue(),
                    commandContext.command.serviceUUID,
                    commandContext.command.characteristicUUID,
                    commandContext.command.tag);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicRead(gatt, characteristic, status);

        this.cancelCommandTimeoutTask();

        if (status == BluetoothGatt.GATT_SUCCESS) {
            byte[] data = characteristic.getValue();
            this.commandSuccess(data);
        } else {
            this.commandError("read characteristic failed");
        }

        this.commandCompleted();
    }

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt,
                                      BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);

        this.cancelCommandTimeoutTask();

        if (status == BluetoothGatt.GATT_SUCCESS) {
            this.commandSuccess(null);
        } else {
            this.commandError("write characteristic fail");
        }

        TelinkLog.d("onCharacteristicWrite newStatus : " + status);

        this.commandCompleted();
    }

    @Override
    public void onDescriptorRead(BluetoothGatt gatt,
                                 BluetoothGattDescriptor descriptor, int status) {
        super.onDescriptorRead(gatt, descriptor, status);

        this.cancelCommandTimeoutTask();

        if (status == BluetoothGatt.GATT_SUCCESS) {
            byte[] data = descriptor.getValue();
            this.commandSuccess(data);
        } else {
            this.commandError("read description failed");
        }

        this.commandCompleted();
    }

    @Override
    public void onDescriptorWrite(BluetoothGatt gatt,
                                  BluetoothGattDescriptor descriptor, int status) {
        super.onDescriptorWrite(gatt, descriptor, status);

        this.cancelCommandTimeoutTask();

        if (status == BluetoothGatt.GATT_SUCCESS) {
            this.commandSuccess(null);
        } else {
            this.commandError("write description failed");
        }

        this.commandCompleted();
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);

        if (status == BluetoothGatt.GATT_SUCCESS) {
            List<BluetoothGattService> services = gatt.getServices();
            this.mServices = services;
            this.onServicesDiscovered(services);
        } else {
            TelinkLog.d("Service discovery failed");
            this.disconnect();
        }
    }

    @Override
    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
        super.onReadRemoteRssi(gatt, rssi, status);

        if (status == BluetoothGatt.GATT_SUCCESS) {

            if (rssi != this.rssi) {
                this.rssi = rssi;
                this.onRssiChanged();
            }
        }
    }

    @Override
    public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
        super.onMtuChanged(gatt, mtu, status);

        TelinkLog.d("mtu changed : " + mtu);
    }

    @Override
    public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
        super.onReliableWriteCompleted(gatt, status);
    }

    private final class CommandContext {

        public Command command;
        public Command.Callback callback;
        public long time;

        public CommandContext(Command.Callback callback, Command command) {
            this.callback = callback;
            this.command = command;
        }

        public void clear() {
            this.command = null;
            this.callback = null;
        }
    }

    private final class RssiUpdateRunnable implements Runnable {

        @Override
        public void run() {

            if (!monitorRssi)
                return;

            if (!isConnected())
                return;

            if (gatt != null)
                gatt.readRemoteRssi();

            mRssiUpdateHandler.postDelayed(mRssiUpdateRunnable, updateIntervalMill);
        }
    }

    private final class CommandTimeoutRunnable implements Runnable {

        @Override
        public void run() {

            synchronized (mOutputCommandQueue) {

                CommandContext commandContext = mOutputCommandQueue.peek();

                if (commandContext != null) {

                    Command command = commandContext.command;
                    Command.Callback callback = commandContext.callback;

                    boolean retry = commandTimeout(commandContext);

                    if (retry) {
                        commandContext.command = command;
                        commandContext.callback = callback;
                        processCommand(commandContext);
                    } else {
                        mOutputCommandQueue.poll();
                        commandCompleted();
                    }
                }
            }
        }
    }

    private final class CommandDelayRunnable implements Runnable {

        @Override
        public void run() {
            synchronized (mOutputCommandQueue) {
                CommandContext commandContext = mOutputCommandQueue.peek();
                processCommand(commandContext);
            }
        }
    }

    private final class ConnectTimeoutRunnable implements Runnable {

        @Override
        public void run() {

        }
    }
}