複数のESP32を選択して受信するflutterコード

下記は成功した場合のコードです。

FlutterBluePlus flutterBlue = FlutterBluePlus();
List<BluetoothDevice> devices = [];
BluetoothDevice? connectedDevice;
String status = "Scanning...";
String receivedData = "";

@override
void initState() {
  super.initState();
  startScan();
}

Future<void> startScan() async {
  setState(() {
    status = "Scanning...";
    devices.clear();
    receivedData = ""; // 受信データをリセット
  });
  // 接続中のデバイスを切断
  if (connectedDevice != null) {
    await connectedDevice!.disconnect();
    setState(() {
      connectedDevice = null; // 接続中のデバイスをリセット
    });
  }
  // スキャンを停止
  await FlutterBluePlus.stopScan();
  // キャッシュをクリア
  flutterBlue = FlutterBluePlus();
  // 少し遅延を追加
  await Future.delayed(Duration(seconds: 1));
  // スキャンを開始
  FlutterBluePlus.startScan(timeout: Duration(seconds: 10));

  // スキャン結果をリッスン
  FlutterBluePlus.scanResults.listen((results) {
    for (ScanResult result in results) {
      // 重複チェック
      if (!devices.any((device) => device.id == result.device.id)) {
        setState(() {
          devices.add(result.device);
        });
      }
    }
  });
}

void stopScan() {
  FlutterBluePlus.stopScan();
}

void connectToDevice(BluetoothDevice device) async {
  setState(() {
    status = "Connecting...";
  });

  // 既に接続中のデバイスがあれば切断
  if (connectedDevice != null) {
    await connectedDevice!.disconnect();
  }

  await device.connect();
  setState(() {
    connectedDevice = device;
    status = "Connected to ${device.name ?? device.id.toString()}";
  });

  discoverServices(device);
}

void discoverServices(BluetoothDevice device) async {
  try {
    List<BluetoothService> services = await device.discoverServices();
    for (BluetoothService service in services) {
      for (BluetoothCharacteristic characteristic in service.characteristics) {
        // TXキャラクタリスティックに対して通知を有効にする
        if (characteristic.uuid.toString().toLowerCase() == "6e400003-b5a3-f393-e0a9-e50e24dcca9e") {
          await characteristic.setNotifyValue(true);
          characteristic.value.listen((value) {
            setState(() {
              receivedData = String.fromCharCodes(value);
            });
            print("Notification received: $value");
          });
        }
      }
    }
  } catch (e) {
    print("Error discovering services: $e");
  }
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('BLE Device Selector'),
    ),
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("Status: $status"),
          if (connectedDevice != null) Text("Connected to: ${connectedDevice!.name ?? connectedDevice!.id.toString()}"),
          Text("Received Data: $receivedData"),
          Expanded(
            child: ListView.builder(
              itemCount: devices.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(devices[index].name ?? "Unknown Device (${devices[index].id})"),
                  subtitle: Text(devices[index].id.toString()),
                  onTap: () => connectToDevice(devices[index]),
                );
              },
            ),
          ),
          ElevatedButton(
            onPressed: startScan,
            child: Text("Rescan"),
          ),
        ],
      ),
    ),
  );
}
タイトルとURLをコピーしました