| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251 |
- 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<List<int>>.broadcast();
- final _events = StreamController<ClassicBluetoothEvent>.broadcast();
- var _ready = Completer<void>();
- StreamSubscription<dynamic>? _subscription;
- Future<void>? _streamRestart;
- int _streamGeneration = 0;
- int _connectionGeneration = 0;
- Object? _streamError;
- bool _disposed = false;
- Future<void>? _disposeFuture;
- bool get isSupported =>
- !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
- Stream<List<int>> get received => _received.stream;
- Stream<ClassicBluetoothEvent> get events => _events.stream;
- Stream<ClassicBluetoothEvent> get connectionEvents => events;
- Future<void> _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<void> _restartNativeStream() async {
- _streamGeneration++;
- await _subscription?.cancel();
- _checkAvailable();
- _subscription = null;
- _streamError = null;
- _ready = Completer<void>();
- _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<int>.unmodifiable(bytes.cast<int>()));
- }
- 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<T?> _invoke<T>(String method, [Object? arguments]) async {
- try {
- return await _methodChannel.invokeMethod<T>(method, arguments);
- } on MissingPluginException {
- throw PlatformException(
- code: 'unsupported',
- message: 'Android Bluetooth Classic transport is unavailable.',
- );
- }
- }
- Future<List<ClassicBluetoothDevice>> listBondedDevices() async {
- _checkAvailable();
- final devices = await _invoke<List<dynamic>>('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<void> 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<void>('connect', {'address': address});
- }
- void _checkConnectionAttempt(int generation) {
- _checkAvailable();
- if (generation != _connectionGeneration) {
- throw StateError('Bluetooth connection attempt has been canceled.');
- }
- }
- Future<void> write(List<int> bytes) async {
- _checkAvailable();
- if (bytes.any((byte) => byte < 0 || byte > 255)) {
- throw ArgumentError.value(bytes, 'bytes', 'Must contain unsigned bytes.');
- }
- await _invoke<void>('write', {'bytes': Uint8List.fromList(bytes)});
- }
- Future<void> disconnect() async {
- _connectionGeneration++;
- _checkAvailable();
- await _invoke<void>('disconnect');
- }
- Future<void> dispose() => _disposeFuture ??= _dispose();
- Future<void> _dispose() async {
- _connectionGeneration++;
- _disposed = true;
- if (!_ready.isCompleted) _ready.complete();
- try {
- if (isSupported && _subscription != null) {
- await _invoke<void>('disconnect');
- }
- } on PlatformException catch (error) {
- if (error.code != 'unsupported') rethrow;
- } finally {
- await _subscription?.cancel();
- await _received.close();
- await _events.close();
- }
- }
- }
|