8. BLE

Connecting to DualGY521_M5Stamp with universal_ble

Goals of this chapter

1

Scan nearby devices

Works on any PC

2

Real sensor

Sending commands and parsing data

3

Switching

Measure with the selected device

Choosing a package

Package License Supported OS
universal_ble BSD-3 (free) Android / iOS / macOS / Windows / Linux / Web
flutter_blue_plus 2.x Custom (paid for commercial use) Android / iOS / macOS, etc.

flutter_blue_plus licensing

Since 2.0, for-profit organizations need a paid license even for development and evaluation. This course uses universal_ble.

flutter pub add universal_ble

DualGY521_M5Stamp specification

Item Details
Device name DualGY521_M5Stamp
Service / characteristic One. Used both for writing commands and for data notifications
Start / stop measuring Write 0x01, 0x00 / 0x01, 0x01
Measurement data 52 bytes notified at 100Hz (next slide)
Pairing PIN 123456 (encrypted link)

Measurement data (52 bytes)

byte Content Type
0-1 Identifier 0x01, 0x01 —
2-3 Packet number uint16
4-15 Sensor 1 acceleration x, y, z [g] float32 ×3
16-27 Sensor 1 angular velocity x, y, z [dps] float32 ×3
28-39 Sensor 2 acceleration float32 ×3
40-51 Sensor 2 angular velocity float32 ×3
  • All little-endian. String responses such as device info arrive on the same notification, so tell them apart by shape

Permission settings

macOS / iOS — Info.plist

<key>NSBluetoothAlwaysUsageDescription</key>
<string>センサと通信するためにBluetoothを使用します。</string>

macOS — *.entitlements (Debug and Release)

<key>com.apple.security.device.bluetooth</key>
<true/>
android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
                 android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" />

Scanning for nearby devices

lib/service/imu/ble_scanner.dart
import 'dart:async';

import 'package:universal_ble/universal_ble.dart';

// Scan nearby BLE devices for a fixed time and return them (named ones only)
class BleScanner {
  Future<List<BleDevice>> scan({Duration duration = const Duration(seconds: 3)}) async {
    final found = <String, BleDevice>{};
    final sub = UniversalBle.scanStream.listen((device) {
      if ((device.name ?? '').isNotEmpty) found[device.deviceId] = device;
    });
    try {
      await UniversalBle.startScan(); // permission requests are handled automatically too
      await Future.delayed(duration);
    } finally {
      await UniversalBle.stopScan();
      await sub.cancel();
    }
    return found.values.toList()
      ..sort((a, b) => (b.rssi ?? -999).compareTo(a.rssi ?? -999)); // strongest signal first
  }
}

Parsing the data

lib/service/imu/imu_packet.dart
import 'dart:typed_data';

import 'package:motion_app/service/imu/imu_device.dart';

// Parsing of the measurement data (52 bytes) that DualGY521_M5Stamp sends at 100Hz
//   0-1  : identifier 0x01, 0x01
//   2-3  : packet number (uint16)
//   4-15 : sensor 1 acceleration x,y,z (float32 ×3, g)
//   16-27: sensor 1 angular velocity x,y,z (float32 ×3, dps)
//   28-39: sensor 2 acceleration
//   40-51: sensor 2 angular velocity
// All little-endian
abstract final class ImuPacket {
  static const int length = 52;

  // null if it isn't measurement data (string responses such as device info arrive on the same notification)
  static ImuSample? tryParse(Uint8List bytes) {
    if (bytes.length != length || bytes[0] != 0x01 || bytes[1] != 0x01) {
      return null;
    }
    final data = ByteData.sublistView(bytes);
    Vec3 vec(int offset) => Vec3(
          data.getFloat32(offset, Endian.little),
          data.getFloat32(offset + 4, Endian.little),
          data.getFloat32(offset + 8, Endian.little),
        );
    return ImuSample(
      count: data.getUint16(2, Endian.little),
      acc1: vec(4),
      gyro1: vec(16),
      acc2: vec(28),
      gyro2: vec(40),
    );
  }
}
  • Keeping it a pure function separate from communication lets you test it without hardware (Chapter 11)

The real sensor

lib/service/imu/dual_gy521_device.dart
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:universal_ble/universal_ble.dart';
import 'package:motion_app/service/imu/imu_device.dart';
import 'package:motion_app/service/imu/imu_packet.dart';

// DualGY521_M5Stamp (two 6-axis sensors, BLE)
// A single characteristic is used both for writing commands and for notifying measurement data
class DualGy521Device implements ImuDevice {
  DualGy521Device(this.deviceId);

  final String deviceId;
  static final _service =
      BleUuidParser.string('4fafc201-1fb5-459e-8fcc-c5c9c331914b');
  static final _chara =
      BleUuidParser.string('beb5483e-36e1-4688-b7f5-ea07361b26a8');
  static final _startCommand = Uint8List.fromList([0x01, 0x00]); // start continuous measurement
  static final _stopCommand = Uint8List.fromList([0x01, 0x01]); // stop continuous measurement

  final _controller = StreamController<ImuSample>.broadcast();
  StreamSubscription<Uint8List>? _valueSub;
  bool _connected = false;

  @override
  Stream<ImuSample> get samples => _controller.stream;

  @override
  Future<void> start() async {
    if (!_connected) {
      await UniversalBle.connect(deviceId);
      await UniversalBle.discoverServices(deviceId); // required before enabling notifications
      if (Platform.isAndroid) {
        // Enlarge the transfer size (MTU) so 52 bytes arrive in one go (automatic on iOS/macOS)
        await UniversalBle.requestMtu(deviceId, 128);
      }
      _valueSub = UniversalBle.characteristicValueStream(deviceId, _chara)
          .listen(_onValue);
      // The link is encrypted, so the first time enter the PIN (123456) in the OS pairing dialog
      await UniversalBle.subscribeNotifications(deviceId, _service, _chara);
      _connected = true;
    }
    await UniversalBle.write(deviceId, _service, _chara, _startCommand);
  }

  void _onValue(Uint8List value) {
    final sample = ImuPacket.tryParse(value);
    if (sample != null) _controller.add(sample);
  }

  @override
  Future<void> stop() async {
    if (!_connected) return;
    await UniversalBle.write(deviceId, _service, _chara, _stopCommand);
  }

  @override
  Future<void> dispose() async {
    await _valueSub?.cancel();
    if (_connected) await UniversalBle.disconnect(deviceId);
    await _controller.close();
  }
}

Key points of universal_ble

  • Commands (connect, discover, enable notifications, write) are queued and executed in order automatically
  • Every command has a default 10-second timeout
  • discoverServices is required before receiving notifications
  • To receive 52 bytes in one go, Android enlarges the transfer size with requestMtu (automatic on iOS/macOS)
  • The OS pairing dialog appears the first time; enter PIN 123456

Switching between fake and real

lib/provider/providers.dart
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/domain/save_session_usecase.dart';
import 'package:motion_app/infrastructure/database/app_database.dart';
import 'package:motion_app/repository/session/session_repository.dart';
import 'package:motion_app/repository/user/user_repository.dart';
import 'package:motion_app/service/imu/ble_scanner.dart';
import 'package:motion_app/service/imu/dual_gy521_device.dart';
import 'package:motion_app/service/imu/fake_imu_device.dart';
import 'package:motion_app/service/imu/imu_device.dart';

part 'providers.g.dart';

@Riverpod(keepAlive: true)
AppDatabase appDatabase(Ref ref) {
  final db = AppDatabase();
  ref.onDispose(db.close);
  return db;
}

@Riverpod(keepAlive: true)
UserRepository userRepository(Ref ref) =>
    UserRepository(ref.watch(appDatabaseProvider));

@Riverpod(keepAlive: true)
SessionRepository sessionRepository(Ref ref) =>
    SessionRepository(ref.watch(appDatabaseProvider));

// BLE device ID of the sensor to use. null means use the fake sensor
@Riverpod(keepAlive: true)
class SelectedBleDevice extends _$SelectedBleDevice {
  @override
  String? build() => null;

  void select(String? deviceId) => state = deviceId;
}

// 6-axis sensor. BLE if a device is selected, otherwise the fake
@Riverpod(keepAlive: true)
ImuDevice imuDevice(Ref ref) {
  final deviceId = ref.watch(selectedBleDeviceProvider);
  final ImuDevice device =
      deviceId == null ? FakeImuDevice() : DualGy521Device(deviceId);
  ref.onDispose(device.dispose);
  return device;
}

@Riverpod(keepAlive: true)
BleScanner bleScanner(Ref ref) => BleScanner();

// Make sensor data subscribable through Riverpod
@riverpod
Stream<ImuSample> imuSample(Ref ref) => ref.watch(imuDeviceProvider).samples;

@Riverpod(keepAlive: true)
SaveSessionUseCase saveSessionUseCase(Ref ref) => SaveSessionUseCase(
      sessionRepository: ref.watch(sessionRepositoryProvider),
    );
  • ref.watch(selectedBleDeviceProvider) → when the selection changes, the sensor is recreated too

Device screen

lib/ui/device/view/device_page.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/ui/device/view_model/device_view_model.dart';

class DevicePage extends ConsumerWidget {
  const DevicePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(deviceViewModelProvider);
    final notifier = ref.read(deviceViewModelProvider.notifier);
    final selectedId = ref.watch(selectedBleDeviceProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('デバイス')),
      floatingActionButton: FloatingActionButton.extended(
        icon: const Icon(Icons.bluetooth_searching),
        label: Text(state.isScanning ? '検索中...' : '検索'),
        onPressed: state.isScanning ? null : notifier.scan,
      ),
      body: RadioGroup<String?>(
        groupValue: selectedId,
        onChanged: notifier.select,
        child: ListView(
          children: [
            const RadioListTile<String?>(
              value: null,
              title: Text('偽物のセンサ(実機なし)'),
            ),
            if (state.errorMessage != null)
              ListTile(title: Text(state.errorMessage!)),
            for (final device in state.devices)
              RadioListTile<String?>(
                value: device.deviceId,
                title: Text(device.name ?? ''),
                subtitle: Text('${device.deviceId}  RSSI ${device.rssi ?? '-'}'),
              ),
          ],
        ),
      ),
    );
  }
}

Device screen ViewModel

lib/ui/device/view_model/device_view_model.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:universal_ble/universal_ble.dart';

part 'device_view_model.g.dart';
part 'device_view_model.freezed.dart';

@freezed
abstract class DeviceState with _$DeviceState {
  const factory DeviceState({
    @Default([]) List<BleDevice> devices,
    @Default(false) bool isScanning,
    String? errorMessage,
  }) = _DeviceState;
}

@riverpod
class DeviceViewModel extends _$DeviceViewModel {
  @override
  DeviceState build() => const DeviceState();

  Future<void> scan() async {
    state = state.copyWith(isScanning: true, errorMessage: null);
    try {
      final devices = await ref.read(bleScannerProvider).scan();
      state = state.copyWith(devices: devices, isScanning: false);
    } catch (e) {
      state = state.copyWith(isScanning: false, errorMessage: '$e');
    }
  }

  void select(String? deviceId) =>
      ref.read(selectedBleDeviceProvider.notifier).select(deviceId);
}

Add it to the router

lib/router/router.dart
import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/ui/device/view/device_page.dart';
import 'package:motion_app/ui/home/view/home_page.dart';
import 'package:motion_app/ui/measurement/view/measurement_page.dart';
import 'package:motion_app/ui/user_detail/view/user_detail_page.dart';
import 'package:motion_app/ui/user_list/view/user_list_page.dart';

part 'router.g.dart';

// Keep paths as constants to prevent typos in strings
abstract final class Routes {
  static const home = '/';
  static const users = '/users';
  static const device = '/device';
  static String userDetail(String userId) => '/users/$userId';
  static String measurement(String userId) => '/users/$userId/measure';
}

@Riverpod(keepAlive: true)
GoRouter router(Ref ref) {
  return GoRouter(
    initialLocation: Routes.home,
    routes: [
      GoRoute(
        path: Routes.home,
        builder: (context, state) => const HomePage(),
        routes: [
          GoRoute(
            path: 'device',
            builder: (context, state) => const DevicePage(),
          ),
          GoRoute(
            path: 'users', // child routes have no leading /
            builder: (context, state) => const UserListPage(),
            routes: [
              GoRoute(
                path: ':userId',
                builder: (context, state) => UserDetailPage(
                  userId: state.pathParameters['userId']!,
                ),
                routes: [
                  GoRoute(
                    path: 'measure',
                    builder: (context, state) => MeasurementPage(
                      userId: state.pathParameters['userId']!,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    ],
  );
}

Add “Device” to the home screen

lib/ui/home/view/home_page.dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:motion_app/router/router.dart';

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Motion Note')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          Card(
            child: ListTile(
              leading: const Icon(Icons.people),
              title: const Text('ユーザー'),
              trailing: const Icon(Icons.chevron_right),
              onTap: () => context.push(Routes.users),
            ),
          ),
          Card(
            child: ListTile(
              leading: const Icon(Icons.bluetooth),
              title: const Text('デバイス'),
              trailing: const Icon(Icons.chevron_right),
              onTap: () => context.push(Routes.device),
            ),
          ),
        ],
      ),
    );
  }
}

Checkpoint

CHECK 0 / 4