Java 类android.bluetooth.BluetoothGatt 实例源码

项目:neatle    文件:ReadCommand.java   
@Override
protected void start(Connection connection, BluetoothGatt gatt) {
    BluetoothGattService service = gatt.getService(serviceUUID);
    if (service != null) {
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
        if (characteristic != null) {
            NeatleLogger.d("Reading characteristics " + characteristicUUID);
            if (gatt.readCharacteristic(characteristic)) {
                return;
            }
            NeatleLogger.d("Read failed" + characteristicUUID);
        } else {
            NeatleLogger.e("Could not find characteristics " + characteristicUUID);
        }
    } else {
        NeatleLogger.e("Could not find service " + serviceUUID);
    }

    finish(CommandResult.createErrorResult(characteristicUUID, BluetoothGatt.GATT_FAILURE));
}
项目:Make-A-Pede-Android-App    文件:BluetoothLeService.java   
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_CONNECTED;
        connectionState = STATE_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        Log.i(TAG, "Attempting to start service discovery:" + bluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_DISCONNECTED;
        connectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
项目:boohee_v5.6    文件:QNBleHelper.java   
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (this.mGatt != gatt) {
        this.mGatt = gatt;
    }
    if (newState == 2) {
        QNLog.log("连接设备成功");
        this.qnDecoder = null;
        this.mGatt.discoverServices();
    } else if (newState == 0) {
        this.mGatt.close();
        this.uiHandler.post(new 1 (this));
        this.qnDecoder = null;
    } else {
        gatt.disconnect();
        QNLog.error("连接状态异常:", Integer.valueOf(status));
        this.uiHandler.post(new 2 (this));
        if (this.bleCallback != null) {
            this.bleCallback.onCompete(5);
        }
    }
}
项目:Bluetooth_BLE    文件:BleGattCallback.java   
/**
 * 相当于一个监听器, 当蓝牙设备有数据返回时执行
 *
 * @param gatt
 * @param characteristic
 */
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    Log.e(TAG, "onCharacteristicChanged 返回数据: " + Arrays.toString(characteristic.getValue()));
    Message message = new Message();
    message.what = Constant.RESULT_DATA;
    message.obj = characteristic.getValue();
    handler.sendMessage(message);
    //回调
    onCharacteristicRefresh(gatt, characteristic);
}
项目:react-native-blue-manager    文件:Peripheral.java   
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);

    if (writeCallback != null) {

        if (writeQueue.size() > 0){
            byte[] data = writeQueue.get(0);
            writeQueue.remove(0);
            doWrite(characteristic, data);
        } else {

            if (status == BluetoothGatt.GATT_SUCCESS) {
                writeCallback.invoke();
            } else {
                Log.e(LOG_TAG, "Error onCharacteristicWrite:" + status);
                writeCallback.invoke("Error writing status: " + status);
            }

            writeCallback = null;
        }
    }else
        Log.e(LOG_TAG, "No callback on write");
}
项目:TrainAppTFG    文件:BluetoothLeService.java   
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    Log.d("BLUETOOTH", "Estado de conexión bluetooth: " + (newState == BluetoothProfile.STATE_CONNECTED ? "Connected" : "Disconnected"));

    if(newState == BluetoothProfile.STATE_CONNECTED){
        //setState(State.CONNECTED);
        mBluetoothGatt.discoverServices();
    }
    else{
        //setState(State.IDDLE);
        //TODO Realizar todas las tareas necesarias cuando se desconecte la pulsera
        Log.d("BLUETOOTH", "Se ha desconectado el dispostivo bluetooth");
    }
}
项目:TrainAppTFG    文件:BluetoothLeService.java   
private boolean obtenerCaracteristicasDescriptoresAccelGyroCC2650(BluetoothGatt gatt){
    boolean todoCorrecto = false;

    BluetoothGattService acelerometroService = gatt.getService(UUID_MOVEMENT_SERVICE);
    if(acelerometroService != null){
        this.movementCharacteristic = acelerometroService.getCharacteristic(UUID_MOVEMENT_DATA);
        this.movementConf = acelerometroService.getCharacteristic(UUID_MOVEMENT_CONF);
        this.movementPeriod = acelerometroService.getCharacteristic(UUID_MOVEMENT_PERIOD);

        if(movementCharacteristic != null && movementConf != null){
            this.config = movementCharacteristic.getDescriptor(UUID_CCC);
            todoCorrecto = true;
        }
    }

    return todoCorrecto;
}
项目:Bluetooth_BLE    文件:LiteBluetooth.java   
/**
  * Clears the device cache. After uploading new hello4 the DFU target will have other services than before.
  * 清除设备缓存。 在上传新的hello4之后,DFU目标将具有比以前更多的服务。
  */
 public boolean refreshDeviceCache() {
     /*
      * There is a refresh() method in BluetoothGatt class but for now it's hidden. We will call it using reflections.
      * 使用反射调用
*/
     try {
         final Method refresh = BluetoothGatt.class.getMethod("refresh");
         if (refresh != null) {
             final boolean success = (Boolean) refresh.invoke(getBluetoothGatt());
             Log.i(TAG, "Refreshing result: " + success);
             return success;
         }
     } catch (Exception e) {
         Log.e(TAG, "An exception occured while refreshing device", e);
     }
     return false;
 }
项目:UDOOBluLib-android    文件:UdooBluService.java   
/**
 * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported asynchronously through the
 * {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} callback.
 *
 * @param characteristic The characteristic to read from.
 */
public void readCharacteristic(final String mac, final BluetoothGattCharacteristic characteristic) {
    try {
        voidBlockingQueue.put(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                BluetoothGatt bluetoothGatt = checkAndGetGattItem(mac);
                boolean success = false;
                if (bluetoothGatt != null && characteristic != null) {
                    success = bluetoothGatt.readCharacteristic(characteristic);
                }
                return success;
            }
        });

    } catch (InterruptedException e) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "readCharacteristic: " + e.getMessage());
    }
}
项目:blefun-androidthings    文件:GattClient.java   
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        boolean connected = false;

        BluetoothGattService service = gatt.getService(SERVICE_UUID);
        if (service != null) {
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_COUNTER_UUID);
            if (characteristic != null) {
                gatt.setCharacteristicNotification(characteristic, true);

                BluetoothGattDescriptor descriptor = characteristic.getDescriptor(DESCRIPTOR_CONFIG);
                if (descriptor != null) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    connected = gatt.writeDescriptor(descriptor);
                }
            }
        }
        mListener.onConnected(connected);
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
}
项目:Bluetooth_BLE    文件:LiteBleConnector.java   
/**
 * 处理向特征码写入数据的回调
 * @param bleCallback
 */
private void handleCharacteristicWriteCallback(final BleCharactCallback bleCallback) {
    if (bleCallback != null) {
        // 添加连接回调到LiteBluetooth的回调集合中
        listenAndTimer(bleCallback, MSG_WRIATE_CHA, new BluetoothGattCallback() {
            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt,
                                              BluetoothGattCharacteristic characteristic, int status) {
                handler.removeMessages(MSG_WRIATE_CHA, this);
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    bleCallback.onSuccess(characteristic);
                } else {
                    bleCallback.onFailure(new GattException(status));
                }
            }
        });
    }
}
项目:UDOOBluLib-android    文件:UdooBluService.java   
/**
 * Disconnects an existing connection or cancel a pending connection. The disconnection result is reported asynchronously through the
 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} callback.
 */
public void disconnect(String address) {
    if (mBtAdapter == null) {
        Log.w(TAG, "disconnect: BluetoothAdapter not initialized");
        return;
    }
    final BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
    int connectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    BluetoothGatt bluetoothGatt = checkAndGetGattItem(address);
    if (bluetoothGatt != null) {
        Log.i(TAG, "disconnect");
        if (connectionState != BluetoothProfile.STATE_DISCONNECTED) {
            bluetoothGatt.disconnect();
        } else {
            Log.w(TAG, "Attempt to disconnect in state: " + connectionState);
        }
    }
}
项目:Android-DFU-App    文件:BleManager.java   
@Override
public final void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
    final String data = ParserUtils.parse(characteristic);

    if (isBatteryLevelCharacteristic(characteristic)) {
        Logger.i(mLogSession, "Notification received from " + characteristic.getUuid() + ", value: " + data);
        final int batteryValue = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        Logger.a(mLogSession, "Battery level received: " + batteryValue + "%");
        mCallbacks.onBatteryValueReceived(batteryValue);
    } else {
        final BluetoothGattDescriptor cccd = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
        final boolean notifications = cccd == null || cccd.getValue() == null || cccd.getValue().length != 2 || cccd.getValue()[0] == 0x01;

        if (notifications) {
            Logger.i(mLogSession, "Notification received from " + characteristic.getUuid() + ", value: " + data);
            onCharacteristicNotified(gatt, characteristic);
        } else { // indications
            Logger.i(mLogSession, "Indication received from " + characteristic.getUuid() + ", value: " + data);
            onCharacteristicIndicated(gatt, characteristic);
        }
    }
}
项目:Android-DFU-App    文件:TemplateManager.java   
@Override
protected void onCharacteristicNotified(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
    // TODO this method is called when a notification has been received
    // This method may be removed from this class if not required

    if (mLogSession != null)
        Logger.a(mLogSession, TemplateParser.parse(characteristic));

    int value;
    final int flags = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
    if ((flags & 0x01) > 0) {
        value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 1);
    } else {
        value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
    }
    //This will send callback to the Activity when new value is received from HR device
    mCallbacks.onSampleValueReceived(value);
}
项目:AndroidMuseumBleManager    文件:BluetoothConnectInterface.java   
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
    Logger.i("onServicesDiscovered status=" + GattError.parseConnectionError(status));
    if (status == BluetoothGatt.GATT_SUCCESS) {
        //start subscribe data
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onDiscoverServicesSuccess(gatt);
                if (gatt != null){
                    startSubscribe(gatt);
                }
            }
        });
    }else {
        Logger.e("onServicesDiscovered fail!");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onDiscoverServicesFail(gatt);
            }
        });
    }
    if (getBluetoothGattCallback() != null) getBluetoothGattCallback().onServicesDiscovered(gatt, status);
}
项目:neatle    文件:Device.java   
private void discoverDevice() {
    boolean isScanning = false;

    do {
        if (adapter == null || adapter.getState() != BluetoothAdapter.STATE_ON) {
            isScanning = false;
            break;
        }

        //FIXME: Switch to non-deprecated method.
        if (!adapter.startLeScan(discoverCallback)) {
            isScanning = true;
            break;
        }
    } while (false);

    if (isScanning) {
        NeatleLogger.e("Failed to start device discovery. Failing connection attempt");
        connectionFailed(BluetoothGatt.GATT_FAILURE);
    } else {
        handler.postDelayed(discoverWatchdog, DISCOVER_DEVICE_TIMEOUT);
    }
}
项目:neatle    文件:WriteCommandTest.java   
@Test
public void testOnCharacteristicWriteNextChunk() throws IOException {
    when(gatt.getService(eq(serviceUUID))).thenReturn(gattService);
    when(gattService.getCharacteristic(characteristicUUID)).thenReturn(gattCharacteristic);
    when(gatt.writeCharacteristic(eq(gattCharacteristic))).thenReturn(true);
    InputSource inputSource = Mockito.mock(InputSource.class);
    when(inputSource.nextChunk()).thenReturn(new byte[]{12, 21});

    writeCommand = new WriteCommand(
            serviceUUID,
            characteristicUUID,
            BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
            inputSource,
            commandObserver);

    writeCommand.execute(device, operationCommandObserver, gatt);

    writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS);
    verify(commandObserver, times(0)).finished(any(Command.class), any(CommandResult.class));
    verify(operationCommandObserver, times(0)).finished(any(Command.class), any(CommandResult.class));
}
项目:BLE-PEPS    文件:BluetoothLeClass.java   
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        if(mOnConnectListener!=null)
            mOnConnectListener.onConnect(gatt);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        if(mOnDisconnectListener!=null)
            mOnDisconnectListener.onDisconnect(gatt);
        Log.i(TAG, "Disconnected from GATT server.");
    }

    if(mOnConnectStatusChangedListener!=null)
        mOnConnectStatusChangedListener.onConnectStatusChanged(gatt,status,newState);
        Log.i(TAG, "Changed");

}
项目:Android-DFU-App    文件:GattError.java   
/**
 * Converts the connection status given by the {@link android.bluetooth.BluetoothGattCallback#onConnectionStateChange(BluetoothGatt, int, int)} to error name.
 * @param error the status number
 * @return the error name as stated in the gatt_api.h file
 */
public static String parseConnectionError(final int error) {
    switch (error) {
        case BluetoothGatt.GATT_SUCCESS:
            return "SUCCESS";
        case 0x01:
            return "GATT CONN L2C FAILURE";
        case 0x08:
            return "GATT CONN TIMEOUT";
        case 0x13:
            return "GATT CONN TERMINATE PEER USER";
        case 0x16:
            return "GATT CONN TERMINATE LOCAL HOST";
        case 0x3E:
            return "GATT CONN FAIL ESTABLISH";
        case 0x22:
            return "GATT CONN LMP TIMEOUT";
        case 0x0100:
            return "GATT CONN CANCEL ";
        case 0x0085:
            return "GATT ERROR"; // Device not reachable
        default:
            return "UNKNOWN (" + error + ")";
    }
}
项目:AndroidMuseumBleManager    文件:ConnectRequestQueue.java   
@Override
protected void onDeviceDisconnect(BluetoothGatt gatt, int errorState) {
    Logger.e( "Disconnected from GATT server address:" + gatt.getDevice().getAddress());
    //可以不关闭,以便重用,因为在连接connect的时候可以快速连接
    if (!mBluetoothUtils.isBluetoothIsEnable()){
        //关闭所有的设备
        closeAll();
    }else {
        close(gatt.getDevice().getAddress());//防止出现status 133
    }
}
项目:BLE-PEPS    文件:BluetoothLeClass.java   
@Override
public void onReadRemoteRssi(BluetoothGatt gatt,
                             int rssi,
                             int status) {
    if (mOnDataAvailableListener!=null)
        mOnDataAvailableListener.onReadRemoteRssi(gatt, rssi, status);
}
项目:Android-DFU-App    文件:ProximityManager.java   
@Override
public void onCharacteristicWriteRequest(final BluetoothDevice device, final int requestId, final BluetoothGattCharacteristic characteristic, final boolean preparedWrite,
                                         final boolean responseNeeded, final int offset, final byte[] value) {
    Logger.d(mLogSession, "[Server callback] Write request to characteristic " + characteristic.getUuid()
            + " (requestId=" + requestId + ", prepareWrite=" + preparedWrite + ", responseNeeded=" + responseNeeded + ", offset=" + offset + ", value=" + ParserUtils.parse(value) + ")");
    final String writeType = !responseNeeded ? "WRITE NO RESPONSE" : "WRITE COMMAND";
    Logger.i(mLogSession, "[Server] " + writeType + " request for characteristic " + characteristic.getUuid() + " received, value: " + ParserUtils.parse(value));

    if (offset == 0) {
        characteristic.setValue(value);
    } else {
        final byte[] currentValue = characteristic.getValue();
        final byte[] newValue = new byte[currentValue.length + value.length];
        System.arraycopy(currentValue, 0, newValue, 0, currentValue.length);
        System.arraycopy(value, 0, newValue, offset, value.length);
        characteristic.setValue(newValue);
    }

    if (!preparedWrite && value != null && value.length == 1) { // small validation
        if (value[0] != NO_ALERT[0]) {
            Logger.a(mLogSession, "[Server] Immediate alarm request received: " + AlertLevelParser.parse(characteristic));
            mCallbacks.onAlarmTriggered();
        } else {
            Logger.a(mLogSession, "[Server] Immediate alarm request received: OFF");
            mCallbacks.onAlarmStopped();
        }
    }

    Logger.d(mLogSession, "server.sendResponse(GATT_SUCCESS, offset=" + offset + ", value=" + ParserUtils.parse(value) + ")");
    mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, null);
    Logger.v(mLogSession, "[Server] Response sent");
}
项目:Android-DFU-App    文件:RSCManager.java   
@Override
public boolean isRequiredServiceSupported(final BluetoothGatt gatt) {
    final BluetoothGattService service = gatt.getService(RUNNING_SPEED_AND_CADENCE_SERVICE_UUID);
    if (service != null) {
        mRSCMeasurementCharacteristic = service.getCharacteristic(RSC_MEASUREMENT_CHARACTERISTIC_UUID);
    }
    return mRSCMeasurementCharacteristic != null;
}
项目:microbit    文件:DfuBaseService.java   
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
    // Notify waiting thread
    logi("onServicesDiscovered() :: Start");
    if (status == BluetoothGatt.GATT_SUCCESS) {
        logi("onServicesDiscovered() :: Services discovered");
        mConnectionState = STATE_CONNECTED_AND_READY;
    } else {
        loge("onServicesDiscovered() :: Service discovery error: " + status);
        mError = ERROR_CONNECTION_MASK | status;
    }
    synchronized (mLock) {
        mLock.notifyAll();
    }
}
项目:neatle    文件:SubscribeCommandTest.java   
@Test
public void testOnError() {
    setupDescriptorSuccess();
    subscribeCommand.execute(device, operationCommandObserver, gatt);

    subscribeCommand.onError(BluetoothGatt.GATT_FAILURE);
    verifyCommandFail(subscribeCommand, BluetoothGatt.GATT_FAILURE);
}
项目:blefun-androidthings    文件:GattClient.java   
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        Log.i(TAG, "Connected to GATT client. Attempting to start service discovery");
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        Log.i(TAG, "Disconnected from GATT client");
        mListener.onConnected(false);
    }
}
项目:Android-DFU-App    文件:ProximityManager.java   
@Override
public void onExecuteWrite(final BluetoothDevice device, final int requestId, final boolean execute) {
    Logger.d(mLogSession, "[Server callback] Execute write request (requestId=" + requestId + ", execute=" + execute + ")");
    // This method is not supported
    Logger.w(mLogSession, "[Server] Operation not supported");
    Logger.d(mLogSession, "[Server] server.sendResponse(GATT_REQUEST_NOT_SUPPORTED)");
    mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, 0, null);
    Logger.v(mLogSession, "[Server] Response sent");
}
项目:UDOOBluLib-android    文件:UdooBluService.java   
public boolean isNotificationEnabled(String mac, BluetoothGattCharacteristic characteristic) {
    BluetoothGatt bluetoothGatt = checkAndGetGattItem(mac);
    boolean result = false;
    if (bluetoothGatt != null) {
        BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(GattInfo.CLIENT_CHARACTERISTIC_CONFIG);
        if (clientConfig != null) {
            result = clientConfig.getValue() == BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
        }
    }
    return result;
}
项目:Bluetooth_BLE    文件:BluetoothUtil.java   
/**
 * 关闭GATT连接
 * @param gatt
 */
public static void closeBluetoothGatt(BluetoothGatt gatt) {
    if (gatt != null) {
        gatt.disconnect();
        refreshDeviceCache(gatt);
        gatt.close();
    }
}
项目:microbit    文件:DfuBaseService.java   
/**
 * <p>
 * Writes the Soft Device, Bootloader and Application image sizes to the characteristic. Soft Device and Bootloader update is supported since Soft Device s110 v7.0.0.
 * Sizes of SD, BL and App are uploaded as 3x UINT32 even though some of them may be 0s. F.e. if only App is being updated the data will be <0x00000000, 0x00000000, [App size]>
 * </p>
 * <p>
 * This method is SYNCHRONOUS and wait until the {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} will be called or the connection state will
 * change from {@link #STATE_CONNECTED_AND_READY}. If connection state will change, or an error will occur, an exception will be thrown.
 * </p>
 *
 * @param gatt                the GATT device
 * @param characteristic      the characteristic to write to. Should be the DFU PACKET
 * @param softDeviceImageSize the Soft Device image size in bytes
 * @param bootloaderImageSize the Bootloader image size in bytes
 * @param appImageSize        the Application image size in bytes
 * @throws DeviceDisconnectedException
 * @throws DfuException
 * @throws UploadAbortedException
 */
private void writeImageSize(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int softDeviceImageSize,
                            final int bootloaderImageSize, final int appImageSize) throws DeviceDisconnectedException, DfuException, UploadAbortedException {

    mReceivedData = null;
    mError = 0;
    mImageSizeSent = false;

    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
    characteristic.setValue(new byte[12]);
    characteristic.setValue(softDeviceImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 0);
    characteristic.setValue(bootloaderImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 4);
    characteristic.setValue(appImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 8);
    sendLogBroadcast(LOG_LEVEL_VERBOSE, "Writing to characteristic " + characteristic.getUuid());
    sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")");
    gatt.writeCharacteristic(characteristic);

    // We have to wait for confirmation
    try {
        synchronized (mLock) {
            while ((!mImageSizeSent && mConnectionState == STATE_CONNECTED_AND_READY && mError == 0 && !mAborted) || mPaused)
                mLock.wait();
        }
    } catch (final InterruptedException e) {
        loge("Sleeping interrupted", e);
    }

    if (mAborted)
        throw new UploadAbortedException();

    if (mError != 0)
        throw new DfuException("Unable to write Image Sizes", mError);

    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to write Image Sizes", mConnectionState);
}
项目:Android-DFU-App    文件:ProximityManager.java   
@Override
public void onDescriptorWriteRequest(final BluetoothDevice device, final int requestId, final BluetoothGattDescriptor descriptor, final boolean preparedWrite,
                                     final boolean responseNeeded, final int offset, final byte[] value) {
    Logger.d(mLogSession, "[Server callback] Write request to descriptor " + descriptor.getUuid()
            + " (requestId=" + requestId + ", prepareWrite=" + preparedWrite + ", responseNeeded=" + responseNeeded + ", offset=" + offset + ", value=" + ParserUtils.parse(value) + ")");
    Logger.i(mLogSession, "[Server] READ request for descriptor " + descriptor.getUuid() + " received");
    // This method is not supported
    Logger.w(mLogSession, "[Server] Operation not supported");
    Logger.d(mLogSession, "[Server] server.sendResponse(GATT_REQUEST_NOT_SUPPORTED)");
    mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, offset, null);
    Logger.v(mLogSession, "[Server] Response sent");
}
项目:microbit    文件:DfuBaseService.java   
private void gattConnect(final BluetoothGatt gatt) {
    try {
        if (gatt.connect()) {
            synchronized (mLock) {
                while (mConnectionState != STATE_CONNECTED_AND_READY && mError == 0) {
                    mLock.wait(30 * 1000); //Wait only 30 seconds. TODO Check this again
                }
            }
        }
    } catch (final InterruptedException e) {
        e.printStackTrace();
        loge("Sleeping interrupted", e);
    }

}
项目:AndroidMuseumBleManager    文件:BluetoothConnectInterface.java   
/**
 * start subscribe data, add data to subscribe list before invoke this method
 * <p>You should invoke this method after onServicesDiscovered, otherwise can not find service<p/>
 * @param bluetoothGatt
 * @return boolean is success start read or write character
 */
public boolean startSubscribe(BluetoothGatt bluetoothGatt){
    if (bluetoothGatt == null){
        Logger.e("Fail to subscribe, BluetoothGatt is null");
        return false;
    }
    boolean isSuccess = subscribe(bluetoothGatt.getDevice().getAddress());
    mOpratorQueue.start(bluetoothGatt);
    return isSuccess;
}
项目:microbit    文件:BLEManager.java   
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    super.onDescriptorWrite(gatt, descriptor, status);

    synchronized(locker) {
        if(DEBUG) {
            logi("BluetoothGattCallback.onDescriptorWrite() :: start : status = " + status);
        }

        if(inBleOp == OP_WRITE_DESCRIPTOR) {
            if(DEBUG) {
                logi("BluetoothGattCallback.onDescriptorWrite() :: inBleOp == OP_WRITE_DESCRIPTOR");
            }

            if(status == BluetoothGatt.GATT_SUCCESS) {
                error = BLE_ERROR_OK;
            } else {
                error = BLE_ERROR_FAIL;
            }

            lastDescriptor = descriptor;
            callbackCompleted = true;
            locker.notify();
        }

        if(DEBUG) {
            logi("BluetoothGattCallback.onDescriptorWrite() :: end");
        }
    }
}
项目:Android-DFU-App    文件:BleManager.java   
/**
 * Writes the characteristic value to the given characteristic.
 *
 * @param characteristic the characteristic to write to
 * @return true if request has been sent
 */
protected final boolean writeCharacteristic(final BluetoothGattCharacteristic characteristic) {
    final BluetoothGatt gatt = mBluetoothGatt;
    if (gatt == null || characteristic == null)
        return false;

    // Check characteristic property
    final int properties = characteristic.getProperties();
    if ((properties & (BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) == 0)
        return false;

    Logger.v(mLogSession, "Writing characteristic " + characteristic.getUuid() + " (" + getWriteType(characteristic.getWriteType()) + ")");
    Logger.d(mLogSession, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")");
    return gatt.writeCharacteristic(characteristic);
}
项目:neatle    文件:ReadAllCommand.java   
@Override
protected void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
    if (status != BluetoothGatt.GATT_SUCCESS) {
        finish(CommandResult.createErrorResult(null, status));
    } else {
        if (observer != null) {
            observer.characteristicRead(CommandResult.createCharacteristicRead(characteristic, status));
        }
        readNext(gatt);
    }
}
项目:neatle    文件:ReadCommand.java   
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (!characteristic.getUuid().equals(characteristicUUID)) {
        NeatleLogger.e("Got a read request for a unknown characteristic");
        return;
    }

    CommandResult result = CommandResult.createCharacteristicRead(characteristic, status);
    NeatleLogger.d("Read: " + result);
    finish(result);
}
项目:Sense-Hub-Android-Things    文件:TitagSensorEntity.java   
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if(status == BluetoothGatt.GATT_SUCCESS){
        if(characteristic.getUuid().equals(UUID_TITAG_GET_BATTERY)){
            byte[] mValue = characteristic.getValue();
            int mBattery = new Byte(mValue[0]).intValue();
            setBattery(mBattery);
            byte[] mHumidityValue = {mValue[0]};
            mGattnTitagTempHumidityService.getCharacteristic(UUID_TITAG_ENABLE_AIR_TEMP_HUMIDITY).setValue(mHumidityValue);
            gatt.writeCharacteristic(mGattnTitagTempHumidityService.getCharacteristic(UUID_TITAG_ENABLE_AIR_TEMP_HUMIDITY));
        }
    }
}
项目:mesh-core-on-android    文件:JniCallbacks.java   
@Override
public void onMtuChanged (BluetoothGatt gatt, int mtu, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        mGattMtu = mtu;
        gatt.discoverServices();
    }
}
项目:UDOOBluLib-android    文件:UdooBluService.java   
/**
 * Retrieves a list of supported GATT services on the connected device with @address.
 * This should be invoked only after {@code BluetoothGatt#discoverServices()} completes
 * successfully.
 *
 * @return A {@code List} of supported services.
 */
public List<BluetoothGattService> getSupportedGattServices(String mac) {
    List<BluetoothGattService> list = new ArrayList<>();

    if (mBluetoothGatts.containsKey(mac)) {
        BluetoothGatt bluetoothGatt = mBluetoothGatts.get(mac);
        if (bluetoothGatt != null)
            list = bluetoothGatt.getServices();
    }

    return list;
}