24

Bluetooth を検出して接続できます。

ソースコード - -

Bluetooth 経由でリモート デバイスに接続します。

//Get the device by its serial number
 bdDevice = mBluetoothAdapter.getRemoteDevice(blackBox);

 //for ble connection
 bdDevice.connectGatt(getApplicationContext(), true, mGattCallback);

ステータスの Gatt コールバック:

 private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    //Connection established
    if (status == BluetoothGatt.GATT_SUCCESS
        && newState == BluetoothProfile.STATE_CONNECTED) {

        //Discover services
        gatt.discoverServices();

    } else if (status == BluetoothGatt.GATT_SUCCESS
        && newState == BluetoothProfile.STATE_DISCONNECTED) {

        //Handle a disconnect event

    }
    }

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

    //Now we can start reading/writing characteristics

    }
};

リモート BLE デバイスにコマンドを送信したいのですが、その方法がわかりません。

コマンドが BLE デバイスに送信されると、BLE デバイスは、アプリケーションが受信できるブロードキャスト データによって応答します。

4

2 に答える 2

15

BLE デバイスに接続してサービスを検出するときは、このプロセスをいくつかのステップに分割する必要があります。

  1. gattServicesで利用onServicesDiscoveredできるディスプレイcallback

  2. 特性を書き込めるかどうかを確認するには、 BluetoothGattCharacteristic PROPERTIES
    を確認します - BLE ハードウェアで PROPERTY_WRITE を有効にする必要があり、多くの時間を無駄にしていることに気づきませんでした。

  3. 特性を記述するとき、ハードウェアは操作を明示的に示すために何らかのアクションを実行しますか (私の場合、私は LED を点灯させていました)

BluetoothGattCharacteristicmWriteCharacteristicであると仮定し ます PROPERTY を確認する部分は次のようになります。

if (((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) |
     (charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) > 0) {
 // writing characteristic functions
 mWriteCharacteristic = characteristic;
  }

そして、あなたの特徴を書くために:

// "str" is the string or character you want to write
byte[] strBytes = str.getBytes();
byte[] bytes = activity.mWriteCharacteristic.getValue();  
YourActivity.this.mWriteCharacteristic.setValue(bytes);
YourActivity.this.writeCharacteristic(YourActivity.this.mWriteCharacteristic);  

これらは、正確に実装する必要があるコードの有用な部分です。

基本的なデモのみの実装については、この github プロジェクトを参照してください。

于 2014-05-01T09:53:10.520 に答える