import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; class ClassicBluetoothDevice { const ClassicBluetoothDevice({required this.address, this.name = ''}); final String address; final String name; } enum ClassicBluetoothEventType { connected, disconnected, error } class ClassicBluetoothEvent { const ClassicBluetoothEvent({ required this.type, this.address, this.code, this.message, this.explicitDisconnect = false, }); final ClassicBluetoothEventType type; final String? address; final String? code; final String? message; final bool explicitDisconnect; } /// Android's paired-device RFCOMM transport. Subscribe before calling [connect] /// so incoming binary data and connection changes cannot be missed. class ClassicBluetoothTransport { ClassicBluetoothTransport(); final MethodChannel _methodChannel = const MethodChannel('mebarista/classic'); final EventChannel _eventChannel = const EventChannel( 'mebarista/classic/events', ); final _received = StreamController>.broadcast(); final _events = StreamController.broadcast(); var _ready = Completer(); StreamSubscription? _subscription; Future? _streamRestart; int _streamGeneration = 0; int _connectionGeneration = 0; Object? _streamError; bool _disposed = false; Future? _disposeFuture; bool get isSupported => !kIsWeb && defaultTargetPlatform == TargetPlatform.android; Stream> get received => _received.stream; Stream get events => _events.stream; Stream get connectionEvents => events; Future _listenNative() async { if (_streamRestart case final restart?) { await restart; return; } if (_streamError != null) { final restart = _restartNativeStream(); _streamRestart = restart; try { await restart; } finally { _streamRestart = null; } } else if (_subscription == null) { _subscribeNative(); } } Future _restartNativeStream() async { _streamGeneration++; await _subscription?.cancel(); _checkAvailable(); _subscription = null; _streamError = null; _ready = Completer(); _subscribeNative(); } void _subscribeNative() { final generation = ++_streamGeneration; _subscription = _eventChannel.receiveBroadcastStream().listen( (dynamic value) { if (generation == _streamGeneration) _onNativeEvent(value); }, onError: (Object error) { if (generation == _streamGeneration) _onNativeError(error); }, onDone: () { if (generation == _streamGeneration) { _onNativeError( PlatformException( code: 'event_stream_closed', message: 'Bluetooth event stream closed.', ), ); } }, ); } void _onNativeEvent(dynamic value) { if (_disposed || value is! Map) return; final type = value['type']; if (type == 'ready') { if (!_ready.isCompleted) _ready.complete(); return; } if (type == 'data') { final bytes = value['bytes']; if (bytes is List) { _received.add(List.unmodifiable(bytes.cast())); } return; } final eventType = switch (type) { 'connected' => ClassicBluetoothEventType.connected, 'disconnected' => ClassicBluetoothEventType.disconnected, 'error' => ClassicBluetoothEventType.error, _ => null, }; if (eventType == null) return; _events.add( ClassicBluetoothEvent( type: eventType, address: value['address'] as String?, code: value['code'] as String?, message: value['message'] as String?, explicitDisconnect: value['explicit'] == true, ), ); } void _onNativeError(Object error) { if (_disposed) return; _streamError = error; // Complete normally, then throw in the waiting operation. This avoids an // unhandled Future error when no connection operation is pending. if (!_ready.isCompleted) _ready.complete(); _events.add( ClassicBluetoothEvent( type: ClassicBluetoothEventType.error, code: error is PlatformException ? error.code : 'event_stream_error', message: error is PlatformException ? error.message : 'Bluetooth event stream unavailable.', ), ); } void _checkAvailable() { if (_disposed) throw StateError('Bluetooth transport has been disposed.'); if (!isSupported) { throw PlatformException( code: 'unsupported', message: 'Bluetooth Classic is supported only on Android.', ); } } Future _invoke(String method, [Object? arguments]) async { try { return await _methodChannel.invokeMethod(method, arguments); } on MissingPluginException { throw PlatformException( code: 'unsupported', message: 'Android Bluetooth Classic transport is unavailable.', ); } } Future> listBondedDevices() async { _checkAvailable(); final devices = await _invoke>('listBondedDevices'); return (devices ?? []).map((dynamic value) { final device = value as Map; return ClassicBluetoothDevice( address: device['address'] as String, name: device['name'] as String? ?? '', ); }).toList(); } Future connect(String address) async { _checkAvailable(); final generation = ++_connectionGeneration; await _listenNative(); _checkConnectionAttempt(generation); await _ready.future.timeout( const Duration(seconds: 5), onTimeout: () { final error = PlatformException( code: 'event_stream_unavailable', message: 'Android Bluetooth event stream did not become ready.', ); _onNativeError(error); throw error; }, ); _checkConnectionAttempt(generation); if (_streamError case final error?) throw error; await _invoke('connect', {'address': address}); } void _checkConnectionAttempt(int generation) { _checkAvailable(); if (generation != _connectionGeneration) { throw StateError('Bluetooth connection attempt has been canceled.'); } } Future write(List bytes) async { _checkAvailable(); if (bytes.any((byte) => byte < 0 || byte > 255)) { throw ArgumentError.value(bytes, 'bytes', 'Must contain unsigned bytes.'); } await _invoke('write', {'bytes': Uint8List.fromList(bytes)}); } Future disconnect() async { _connectionGeneration++; _checkAvailable(); await _invoke('disconnect'); } Future dispose() => _disposeFuture ??= _dispose(); Future _dispose() async { _connectionGeneration++; _disposed = true; if (!_ready.isCompleted) _ready.complete(); try { if (isSupported && _subscription != null) { await _invoke('disconnect'); } } on PlatformException catch (error) { if (error.code != 'unsupported') rethrow; } finally { await _subscription?.cancel(); await _received.close(); await _events.close(); } } }