4
5

More than 3 years have passed since last update.

M5StackとFlutterと通信してみた

Posted at

はじめに

以前投稿したM5StackとiOS端末と通信してみたをFlutter版にしました。

サンプルコードとしてgithubにアップしてありますので参考にしてください。

BluetoothLEについては前回の記事を参考にしてください。

実装ポイント

実装のポイントを記載します。

ペリフェラルスキャン

startScanを実行するとペリフェラルスキャンします。
r.device.nameでローカルネームを参照してターゲットデバイス確認しています。

  void scanDevices() {
    // Start scanning
    _flutterBlue.startScan(timeout: Duration(seconds: _timeout));
    // Listen to scan results
    var subscription = _flutterBlue.scanResults.listen((results) async {
      // do something with scan results
      for (ScanResult r in results) {
        print('${r.device.name} found! rssi: ${r.rssi}');
        if (r.device.name == _connectToLocalName) {
          //デバイスを発見したのでここでデバイス情報を保持する
          if (_device == null) {
            _device = r.device;
            notifyListeners();
            await connect();
            break;
          }
        }
      }
    });
    // Stop scanning
    _flutterBlue.stopScan();
  }

サービスのスキャン

サービススキャンして必要なサービスをwritenotifyをつないでいます。

    List<BluetoothService> services = await _device.discoverServices();
    services.forEach((service) async {
      // do something with service
      service.characteristics.forEach((characteristic) async {
        if (characteristic.properties.write) {
          _writeCharacteristic = characteristic;
          print('write');
        } else if (characteristic.properties.notify) {
          _notifyCharacteristic = characteristic;
          await _notifyCharacteristic.setNotifyValue(true);
          _notifyCharacteristic.value.listen((value) {
            // do something with new value
            receiveRaw = value;
            receiveString = utf8.decode(value);
            print('recevied:${receiveString}');
            notifyListeners();
          });
          print('notify');
        }
      });
    });

最後に

すっごく簡単な記事で恐縮ですが、Peripheral側のパッケージflutter_ble_peripheralは開発中で、今のところ逆は簡単に実現できないようです。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5