BLEのキャラクタリスティックの操作

次のステップとして、キャラクタリスティックの操作や通知の有効化を行うことで、BLEデバイスとの双方向通信を実現できます。以下に、具体的な手順とコード例を説明します。


1. キャラクタリスティックの操作

キャラクタリスティックは、BLEデバイスとデータをやり取りするためのインターフェースです。以下の操作が可能です:

  • 読み取り: キャラクタリスティックからデータを読み取る。
  • 書き込み: キャラクタリスティックにデータを書き込む。

(1) キャラクタリスティックの読み取り

キャラクタリスティックからデータを読み取るには、readメソッドを使用します。

void readCharacteristic(BluetoothCharacteristic characteristic) async {
  List<int> value = await characteristic.read();
  print("Characteristic value: $value");
}

(2) キャラクタリスティックへの書き込み

キャラクタリスティックにデータを書き込むには、writeメソッドを使用します。

void writeCharacteristic(BluetoothCharacteristic characteristic, List<int> value) async {
  await characteristic.write(value);
  print("Characteristic value written: $value");
}


2. 通知(Notification)の有効化

通知を有効にすると、BLEデバイスからのデータをリアルタイムで受信できます。通知を有効にするには、以下の手順を実行します。

(1) 通知の有効化

キャラクタリスティックの通知を有効にするには、setNotifyValueメソッドを使用します。

void setNotification(BluetoothCharacteristic characteristic) async {
  await characteristic.setNotifyValue(true);
  characteristic.value.listen((value) {
    print("Notification received: $value");
  });
}

(2) 通知の無効化

通知を無効にするには、setNotifyValueメソッドにfalseを渡します。

void disableNotification(BluetoothCharacteristic characteristic) async {
  await characteristic.setNotifyValue(false);
  print("Notification disabled");
}


3. 具体的な実装例

以下は、サービスとキャラクタリスティックを探索し、通知を有効にしてデータを受信する例です。

void discoverServices(BluetoothDevice device) async {
  List<BluetoothService> services = await device.discoverServices();
  setState(() {
    this.services = services;
  });

  for (BluetoothService service in services) {
    print("Service UUID: ${service.uuid}");
    for (BluetoothCharacteristic characteristic in service.characteristics) {
      print("Characteristic UUID: ${characteristic.uuid}");

      // 特定のキャラクタリスティックに対して通知を有効にする
      if (characteristic.uuid.toString() == "19b10001-e8f2-537e-4f6c-d104768a1214") {
        await characteristic.setNotifyValue(true);
        characteristic.value.listen((value) {
          print("Notification received: $value");
        });
      }
    }
  }
}


4. UIの更新

受信したデータをUIに反映するには、setStateを使用して状態を更新します。

String receivedData = "";


Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('BLE Client'),
    ),
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("Status: $status"),
          if (connectedDevice != null) Text("Connected to: ${connectedDevice!.name}"),
          if (services.isNotEmpty) Text("Services discovered: ${services.length}"),
          Text("Received Data: $receivedData"),
        ],
      ),
    ),
  );
}

通知を受信したときにsetStateを呼び出してUIを更新します。

characteristic.value.listen((value) {
  setState(() {
    receivedData = String.fromCharCodes(value); // 受信データを文字列に変換
  });
  print("Notification received: $value");
});


5. データのフォーマット

BLEデバイスから受信したデータはList<int>形式です。これを適切な形式(文字列、数値など)に変換して使用します。

(1) 文字列に変換

String dataString = String.fromCharCodes(value);
print("Received string: $dataString");

(2) 数値に変換

int dataInt = value[0]; // 最初のバイトを数値として解釈
print("Received integer: $dataInt");


6. エラーハンドリング

BLE操作中にエラーが発生する可能性があるため、適切にエラーハンドリングを行います。

try {
  List<int> value = await characteristic.read();
  print("Characteristic value: $value");
} catch (e) {
  print("Failed to read characteristic: $e");
}


7. デバイスの切断

デバイスとの接続を切断するには、disconnectメソッドを使用します。

void disconnectDevice() async {
  if (connectedDevice != null) {
    await connectedDevice!.disconnect();
    setState(() {
      connectedDevice = null;
      status = "Disconnected";
    });
  }
}

タイトルとURLをコピーしました