org.mockito.Answers#android.bluetooth.BluetoothGatt源码实例Demo

下面列出了org.mockito.Answers#android.bluetooth.BluetoothGatt 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Android-nRF-Toolbox   文件: BleManager.java
private boolean internalEnableIndications(final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null)
		return false;

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

	gatt.setCharacteristicNotification(characteristic, true);
	final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
	if (descriptor != null) {
		descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
源代码2 项目: beacons-android   文件: EddystoneGattServer.java
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
    super.onConnectionStateChange(device, status, newState);

    if (newState == BluetoothGatt.STATE_DISCONNECTED) {
        log(device + " has disconnected");
        if (device.equals(mEddystoneGattService.getConnectedOwner())) {
            log("Owner disconnected, stopping GATT server");
            mEddystoneGattService.onOwnerDisconnected();
            close();
        }
    }
    else if (newState == BluetoothGatt.STATE_CONNECTED) {
        log(device + " has connected");
        if (mEddystoneGattService.getConnectedOwner() != null) {
            // don't allow a second client to connect at the same time
            log(device + " tried to connect, but owner is active. Disconnecting.");
            mGattServer.cancelConnection(device);
        }
    }
}
 
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        connectionState = STATE_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                BleService.this.gatt.discoverServices());
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        connectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
源代码4 项目: WheelLogAndroid   文件: BluetoothLeService.java
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    super.onServicesDiscovered(gatt, status);
    Timber.i("onServicesDiscovered called");
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Timber.i("onServicesDiscovered called, status == BluetoothGatt.GATT_SUCCESS");
        boolean recognisedWheel = WheelData.getInstance().detectWheel(BluetoothLeService.this);
        if (recognisedWheel) {
            mConnectionState = STATE_CONNECTED;
            broadcastConnectionUpdate(mConnectionState);

        } else
            disconnect();
        return;
    }
    Timber.i("onServicesDiscovered called, status == BluetoothGatt.GATT_FAILURE");
}
 
源代码5 项目: IoT-Firstep   文件: BluetoothLeService.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        broadcastUpdate(intentAction);
        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) {
        intentAction = ACTION_GATT_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
源代码6 项目: sony-smartband-open-api   文件: BtBridge.java
@Override
// TODO: maybe here we should set status == CONNECTED
public void onServicesDiscovered( BluetoothGatt gatt, int status ) {
    if( status != BluetoothGatt.GATT_SUCCESS ) {
        Log.e( CLASS, "onServicesDiscovered: Status != SUCCESS: status=" + status );
        return;
    }
    mGatt = gatt;

    List<BluetoothGattService> services = gatt.getServices();
    Log.d( CLASS, "onServicesDiscovered: services=" + services.size() );

    for( BtBridgeListener listener : mListeners ) {
        listener.onServicesDiscovered( services );
    }
}
 
源代码7 项目: easyble-x   文件: MainActivity.java
@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        device = getIntent().getParcelableExtra("device");
        setContentView(R.layout.activity_main);
        assignViews();
        initViews();
        //连接配置,举个例随意配置两项
        ConnectionConfiguration config = new ConnectionConfiguration();
        config.setConnectTimeoutMillis(10000);
        config.setRequestTimeoutMillis(1000);
        config.setAutoReconnect(false);
//        connection = EasyBLE.getInstance().connect(device, config, observer);//回调监听连接状态,设置此回调不影响观察者接收连接状态消息
        connection = EasyBLE.getInstance().connect(device, config);//观察者监听连接状态  
        connection.setBluetoothGattCallback(new BluetoothGattCallback() {
            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                Log.d("EasyBLE", "原始写入数据:" + StringUtils.toHex(characteristic.getValue()));
            }
        });
    }
 
源代码8 项目: xDrip-plus   文件: G5CollectionService.java
@Override
public void onCharacteristicWrite(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
    Log.e(TAG, "OnCharacteristic WRITE started: "
            + getUUIDName(characteristic.getUuid())
            + " status: " + getStatusName(status));
    //Log.e(TAG, "Write Status " + String.valueOf(status));
    //Log.e(TAG, "Characteristic " + String.valueOf(characteristic.getUuid()));

    if (enforceMainThread()) {
        Handler iHandler = new Handler(Looper.getMainLooper());
        iHandler.post(new Runnable() {
            @Override
            public void run() {
                processOnCharacteristicWrite(gatt, characteristic, status);
            }
        });
    } else {
        processOnCharacteristicWrite(gatt, characteristic, status);
    }


}
 
源代码9 项目: microbit   文件: DfuBaseService.java
private String readCharacteristicNoFailure(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
    if (mConnectionState != STATE_CONNECTED_AND_READY)
        return "not_ready";
    if (characteristic == null)
        return "unknown";
    logi("readCharacteristicNoFailure");
    gatt.readCharacteristic(characteristic);
    try {
        synchronized (mLock) {
            while ((!mRequestCompleted && mConnectionState == STATE_CONNECTED_AND_READY && mError == 0 && !mAborted) || mPaused)
                mLock.wait();
        }
    } catch (final InterruptedException e) {
        loge("Sleeping interrupted", e);
    }

    if (mAborted)
        return "unknown";

    if (mError != 0)
        return "unknown";

    if (mConnectionState != STATE_CONNECTED_AND_READY)
        return "unknown";
    return characteristic.getStringValue(0);
}
 
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    Log.d(TAG, "characteristic wrote " + status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG, "Wrote a characteristic successfully " + characteristic.getUuid());
        if (mAuthenticationCharacteristic.getUuid().equals(characteristic.getUuid())) {
            state_authSucess = true;
            gatt.readCharacteristic(mHeartBeatCharacteristic);
        }
    } else if ((status & BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) != 0 || (status & BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION) != 0) {
        if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
            device = gatt.getDevice();
            state_authInProgress = true;
            bondDevice();
        } else {
            Log.e(TAG, "The phone is trying to read from paired device without encryption. Android Bug? Have the dexcom forget whatever device it was previously paired to");
        }
    } else {
        Log.e(TAG, "Unknown error writing Characteristic");
    }
}
 
源代码11 项目: bitgatt   文件: GattServerDisconnectTransaction.java
@Override
public void onServerConnectionStateChange(BluetoothDevice device, int status, int newState) {
    Timber.d("[%s] Gatt State %s, Disconnect Reason : %s", getDevice(), GattStatus.values()[status].name(),
            GattDisconnectReason.getReasonForCode(newState));
    TransactionResult.Builder builder = new TransactionResult.Builder().transactionName(getName());
    builder.responseStatus(GattDisconnectReason.getReasonForCode(status).ordinal());
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            getGattServer().setState(GattState.DISCONNECTED);
            builder.gattState(getGattServer().getGattState())
                    .resultStatus(TransactionResult.TransactionResultStatus.SUCCESS);
            callCallbackWithTransactionResultAndRelease(callback, builder.build());
        } else if (newState == BluetoothProfile.STATE_CONNECTED) {
            getGattServer().setState(GattState.CONNECTED);
            builder.gattState(getGattServer().getGattState())
                    .resultStatus(TransactionResult.TransactionResultStatus.FAILURE);
            callCallbackWithTransactionResultAndRelease(callback, builder.build());
        }
    } else {
        builder.gattState(getGattServer().getGattState())
                .resultStatus(TransactionResult.TransactionResultStatus.FAILURE);
        callCallbackWithTransactionResultAndRelease(callback, builder.build());
    }
}
 
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;
        broadcastUpdate(intentAction);
        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) {
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
源代码13 项目: Bluefruit_LE_Connect_Android   文件: BleManager.java
/**
 * Call to private Android method 'refresh'
 * This method does actually clear the cache from a bluetooth device. But the problem is that we don't have access to it. But in java we have reflection, so we can access this method.
 * http://stackoverflow.com/questions/22596951/how-to-programmatically-force-bluetooth-low-energy-service-discovery-on-android
 */
public boolean refreshDeviceCache() {
    try {
        BluetoothGatt localBluetoothGatt = mGatt;
        Method localMethod = localBluetoothGatt.getClass().getMethod("refresh");
        if (localMethod != null) {
            boolean result = (Boolean) localMethod.invoke(localBluetoothGatt);
            if (result) {
                Log.d(TAG, "Bluetooth refresh cache");
            }
            return result;
        }
    } catch (Exception localException) {
        Log.e(TAG, "An exception occurred while refreshing device");
    }
    return false;
}
 
源代码14 项目: EasyBle   文件: BleGattImpl.java
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        String address = gatt.getDevice().getAddress();
        String serviceUuid = characteristic.getService().getUuid().toString();
        String characteristicUuid = characteristic.getUuid().toString();
        OperationIdentify identify = getOperationIdentifyFromMap(mWriteCallbackMap, address, serviceUuid, characteristicUuid);
        if (identify == null) {
            return;
        }
        final BleWriteCallback callback = mWriteCallbackMap.get(identify);
        final BleDevice device = getBleDeviceFromMap(address, mConnectCallbackMap);
        final byte[] data = characteristic.getValue();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onWriteSuccess(data, device);
                }
            }
        });
    }
}
 
源代码15 项目: neatle   文件: WriteCommandTest.java
@Test
public void testInputSourceClosesOnError() 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()).thenThrow(new IOException());

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

    writeCommand.execute(device, operationCommandObserver, gatt);
    writeCommand.onCharacteristicWrite(gatt, gattCharacteristic, BluetoothGatt.GATT_SUCCESS);

    verify(inputSource).close();
}
 
源代码16 项目: SensorTag-CC2650   文件: MainActivity.java
void onConnect() {
	if (mNumDevs > 0) {

		int connState = mBluetoothManager.getConnectionState(mBluetoothDevice,
		    BluetoothGatt.GATT);

		switch (connState) {
		case BluetoothGatt.STATE_CONNECTED:
			mBluetoothLeService.disconnect(null);
			break;
		case BluetoothGatt.STATE_DISCONNECTED:
			boolean ok = mBluetoothLeService.connect(mBluetoothDevice.getAddress());
			if (!ok) {
				setError("Connect failed");
			}
			break;
		default:
			setError("Device busy (connecting/disconnecting)");
			break;
		}
	}
}
 
@Override
  public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
  	byte[] data = characteristic.getValue();
  	int bmp = data[1] & 0xFF; // To unsign the value
  	DataHandler.getInstance().cleanInput(bmp);
Log.v("H7ConnectThread", "Data received from HR "+bmp);
  }
 
@Override
public void onServiceConnected(final ComponentName name, final IBinder service) {
    final UpdateService.ServiceBinder binder = mBinder = (UpdateService.ServiceBinder) service;
    final int state = binder.getState();
    Log.v(TAG, "Connection state on rotation: " + state);
    switch (state) {
        case UpdateService.STATE_DISCONNECTED:
            binder.connect();
            break;
        case UpdateService.STATE_CONNECTED:
            if (!hasOptionsMenu()) {
                setHasOptionsMenu(true);
                getActivity().invalidateOptionsMenu();
            }
            mConnectButton.setText(R.string.action_disconnect);
            final Integer lockState = binder.getLockState();
            if (lockState != null) {
                updateUiForBeacons(BluetoothGatt.STATE_CONNECTED, lockState);
            }
            switch(lockState){
                case UNLOCKED:
                case UNLOCKED_AUTOMATIC_RELOCK_DISABLED:
                    readCharacteristicsOnRotation(binder);
                    break;
            }
            break;
        case UpdateService.STATE_CONNECTING:
        case UpdateService.STATE_DISCOVERING_SERVICES:
            if(mConnectionProgressDialog != null) {
                mConnectionProgressDialog.setTitle(getString(R.string.prog_dialog_connect_title));
                mConnectionProgressDialog.setMessage(getString(R.string.prog_dialog_connect_message));
                mConnectionProgressDialog.show();
            }
            break;

    }
}
 
源代码19 项目: blessed-android   文件: BluetoothPeripheral.java
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
    long timePassed = SystemClock.elapsedRealtime() - connectTimestamp;
    cancelConnectionTimer();
    final int previousState = state;
    state = newState;

    if (status == GATT_SUCCESS) {
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                successfullyConnected(device.getBondState(), timePassed);
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                successfullyDisconnected(previousState);
                break;
            case BluetoothProfile.STATE_DISCONNECTING:
                Timber.i("peripheral is disconnecting");
                break;
            case BluetoothProfile.STATE_CONNECTING:
                Timber.i("peripheral is connecting");
            default:
                Timber.e("unknown state received");
                break;
        }
    } else {
        connectionStateChangeUnsuccessful(status, previousState, newState, timePassed);
    }
}
 
源代码20 项目: SweetBlue   文件: P_Task_BatteryLevel.java
public void onCharacteristicRead(BluetoothGatt gatt, UUID uuid, byte[] value, int gattStatus)
{
    getManager().ASSERT(getDevice().layerManager().gattEquals(gatt));

    if( false == this.isForCharacteristic(uuid) )  return;

    onCharacteristicOrDescriptorRead(gatt, uuid, value, gattStatus, BleDevice.ReadWriteListener.Type.READ);
}
 
源代码21 项目: neatle   文件: SubscribeCommandTest.java
@Test
public void testOnDescriptorWriteFail() {
    setupDescriptorSuccess();

    subscribeCommand.execute(device, operationCommandObserver, gatt);
    subscribeCommand.onDescriptorWrite(gatt, gattDescriptor, BluetoothGatt.GATT_FAILURE);
    verifyCommandFail(subscribeCommand, BluetoothGatt.GATT_FAILURE);
}
 
源代码22 项目: blessed-android   文件: BluetoothPeripheral.java
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
    final byte[] value = copyOf(characteristic.getValue());
    callbackHandler.post(new Runnable() {
        @Override
        public void run() {
            peripheralCallback.onCharacteristicUpdate(BluetoothPeripheral.this, value, characteristic, GATT_SUCCESS);
        }
    });
}
 
源代码23 项目: blessed-android   文件: BluetoothPeripheral.java
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, final int rssi, final int status) {
    callbackHandler.post(new Runnable() {
        @Override
        public void run() {
            peripheralCallback.onReadRemoteRssi(BluetoothPeripheral.this, rssi, status);
        }
    });
    completedCommand();
}
 
源代码24 项目: RxAndroidBle   文件: ConnectOperation.java
private SingleTransformer<BluetoothGatt, BluetoothGatt> wrapWithTimeoutWhenNotAutoconnecting() {
    return new SingleTransformer<BluetoothGatt, BluetoothGatt>() {
        @Override
        public Single<BluetoothGatt> apply(Single<BluetoothGatt> bluetoothGattSingle) {
            return autoConnect
                    ? bluetoothGattSingle
                    : bluetoothGattSingle
                    .timeout(connectTimeout.timeout, connectTimeout.timeoutTimeUnit, connectTimeout.timeoutScheduler,
                            prepareConnectionTimeoutError());
        }
    };
}
 
源代码25 项目: SweetBlue   文件: P_ReliableWriteManager.java
public void onReliableWriteCompleted_unsolicited(final BluetoothGatt gatt, final int gattStatus)
{
	final BleDevice.ReadWriteListener listener = m_listener;
	m_listener = null;

	final BleDevice.ReadWriteListener.Status status = Utils.isSuccess(gattStatus) ? BleDevice.ReadWriteListener.Status.SUCCESS : BleDevice.ReadWriteListener.Status.REMOTE_GATT_FAILURE;
	final BleDevice.ReadWriteListener.ReadWriteEvent e = newEvent(status, gattStatus, /*solicited=*/false);

	m_device.invokeReadWriteCallback(listener, e);
}
 
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);

    currentAction = null;
    execute(gatt);
}
 
源代码27 项目: BLEService   文件: PeripheralActivity.java
public void uiSuccessfulWrite(final BluetoothGatt gatt,
           					  final BluetoothDevice device,
           					  final BluetoothGattService service,
           					  final BluetoothGattCharacteristic ch,
           					  final String description)
{
	runOnUiThread(new Runnable() {
		@Override
		public void run() {
			Toast.makeText(getApplicationContext(), "Writing to " + description + " was finished successfully!", Toast.LENGTH_LONG).show();
		}
	});
}
 
源代码28 项目: bleYan   文件: BaseBleService.java
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
	final byte[] data = descriptor.getValue();
	BleLog.i(TAG, "onCharacteristicRead: " + HexUtil.encodeHexStr(data));
	UUID uuid = descriptor.getUuid();

	sendBleMessage(BleConstants.MSG_BLE_ID_DESCRIPTOR_READ, status, data, uuid);
	onNextWrite();
}
 
源代码29 项目: neatle   文件: Device.java
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    NeatleLogger.d("createCharacteristicRead");
    BluetoothGattCallback target;
    synchronized (lock) {
        target = currentCallback;
    }
    target.onCharacteristicRead(gatt, characteristic, status);
}
 
源代码30 项目: microbit   文件: BLEManager.java
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);

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

        if(inBleOp == OP_WRITE_CHARACTERISTIC) {
            if(DEBUG) {
                logi("BluetoothGattCallback.onCharacteristicWrite() :: inBleOp == OP_WRITE_CHARACTERISTIC");
            }

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

            lastCharacteristic = characteristic;
            callbackCompleted = true;
            locker.notify();
        }

        if(DEBUG) {
            logi("BluetoothGattCallback.onCharacteristicWrite() :: end");
        }
    }
}