classic_bluetooth_transport.dart 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import 'dart:async';
  2. import 'package:flutter/foundation.dart';
  3. import 'package:flutter/services.dart';
  4. class ClassicBluetoothDevice {
  5. const ClassicBluetoothDevice({required this.address, this.name = ''});
  6. final String address;
  7. final String name;
  8. }
  9. enum ClassicBluetoothEventType { connected, disconnected, error }
  10. class ClassicBluetoothEvent {
  11. const ClassicBluetoothEvent({
  12. required this.type,
  13. this.address,
  14. this.code,
  15. this.message,
  16. this.explicitDisconnect = false,
  17. });
  18. final ClassicBluetoothEventType type;
  19. final String? address;
  20. final String? code;
  21. final String? message;
  22. final bool explicitDisconnect;
  23. }
  24. /// Android's paired-device RFCOMM transport. Subscribe before calling [connect]
  25. /// so incoming binary data and connection changes cannot be missed.
  26. class ClassicBluetoothTransport {
  27. ClassicBluetoothTransport();
  28. final MethodChannel _methodChannel = const MethodChannel('mebarista/classic');
  29. final EventChannel _eventChannel = const EventChannel(
  30. 'mebarista/classic/events',
  31. );
  32. final _received = StreamController<List<int>>.broadcast();
  33. final _events = StreamController<ClassicBluetoothEvent>.broadcast();
  34. var _ready = Completer<void>();
  35. StreamSubscription<dynamic>? _subscription;
  36. Future<void>? _streamRestart;
  37. int _streamGeneration = 0;
  38. int _connectionGeneration = 0;
  39. Object? _streamError;
  40. bool _disposed = false;
  41. Future<void>? _disposeFuture;
  42. bool get isSupported =>
  43. !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
  44. Stream<List<int>> get received => _received.stream;
  45. Stream<ClassicBluetoothEvent> get events => _events.stream;
  46. Stream<ClassicBluetoothEvent> get connectionEvents => events;
  47. Future<void> _listenNative() async {
  48. if (_streamRestart case final restart?) {
  49. await restart;
  50. return;
  51. }
  52. if (_streamError != null) {
  53. final restart = _restartNativeStream();
  54. _streamRestart = restart;
  55. try {
  56. await restart;
  57. } finally {
  58. _streamRestart = null;
  59. }
  60. } else if (_subscription == null) {
  61. _subscribeNative();
  62. }
  63. }
  64. Future<void> _restartNativeStream() async {
  65. _streamGeneration++;
  66. await _subscription?.cancel();
  67. _checkAvailable();
  68. _subscription = null;
  69. _streamError = null;
  70. _ready = Completer<void>();
  71. _subscribeNative();
  72. }
  73. void _subscribeNative() {
  74. final generation = ++_streamGeneration;
  75. _subscription = _eventChannel.receiveBroadcastStream().listen(
  76. (dynamic value) {
  77. if (generation == _streamGeneration) _onNativeEvent(value);
  78. },
  79. onError: (Object error) {
  80. if (generation == _streamGeneration) _onNativeError(error);
  81. },
  82. onDone: () {
  83. if (generation == _streamGeneration) {
  84. _onNativeError(
  85. PlatformException(
  86. code: 'event_stream_closed',
  87. message: 'Bluetooth event stream closed.',
  88. ),
  89. );
  90. }
  91. },
  92. );
  93. }
  94. void _onNativeEvent(dynamic value) {
  95. if (_disposed || value is! Map) return;
  96. final type = value['type'];
  97. if (type == 'ready') {
  98. if (!_ready.isCompleted) _ready.complete();
  99. return;
  100. }
  101. if (type == 'data') {
  102. final bytes = value['bytes'];
  103. if (bytes is List) {
  104. _received.add(List<int>.unmodifiable(bytes.cast<int>()));
  105. }
  106. return;
  107. }
  108. final eventType = switch (type) {
  109. 'connected' => ClassicBluetoothEventType.connected,
  110. 'disconnected' => ClassicBluetoothEventType.disconnected,
  111. 'error' => ClassicBluetoothEventType.error,
  112. _ => null,
  113. };
  114. if (eventType == null) return;
  115. _events.add(
  116. ClassicBluetoothEvent(
  117. type: eventType,
  118. address: value['address'] as String?,
  119. code: value['code'] as String?,
  120. message: value['message'] as String?,
  121. explicitDisconnect: value['explicit'] == true,
  122. ),
  123. );
  124. }
  125. void _onNativeError(Object error) {
  126. if (_disposed) return;
  127. _streamError = error;
  128. // Complete normally, then throw in the waiting operation. This avoids an
  129. // unhandled Future error when no connection operation is pending.
  130. if (!_ready.isCompleted) _ready.complete();
  131. _events.add(
  132. ClassicBluetoothEvent(
  133. type: ClassicBluetoothEventType.error,
  134. code: error is PlatformException ? error.code : 'event_stream_error',
  135. message: error is PlatformException
  136. ? error.message
  137. : 'Bluetooth event stream unavailable.',
  138. ),
  139. );
  140. }
  141. void _checkAvailable() {
  142. if (_disposed) throw StateError('Bluetooth transport has been disposed.');
  143. if (!isSupported) {
  144. throw PlatformException(
  145. code: 'unsupported',
  146. message: 'Bluetooth Classic is supported only on Android.',
  147. );
  148. }
  149. }
  150. Future<T?> _invoke<T>(String method, [Object? arguments]) async {
  151. try {
  152. return await _methodChannel.invokeMethod<T>(method, arguments);
  153. } on MissingPluginException {
  154. throw PlatformException(
  155. code: 'unsupported',
  156. message: 'Android Bluetooth Classic transport is unavailable.',
  157. );
  158. }
  159. }
  160. Future<List<ClassicBluetoothDevice>> listBondedDevices() async {
  161. _checkAvailable();
  162. final devices = await _invoke<List<dynamic>>('listBondedDevices');
  163. return (devices ?? []).map((dynamic value) {
  164. final device = value as Map;
  165. return ClassicBluetoothDevice(
  166. address: device['address'] as String,
  167. name: device['name'] as String? ?? '',
  168. );
  169. }).toList();
  170. }
  171. Future<void> connect(String address) async {
  172. _checkAvailable();
  173. final generation = ++_connectionGeneration;
  174. await _listenNative();
  175. _checkConnectionAttempt(generation);
  176. await _ready.future.timeout(
  177. const Duration(seconds: 5),
  178. onTimeout: () {
  179. final error = PlatformException(
  180. code: 'event_stream_unavailable',
  181. message: 'Android Bluetooth event stream did not become ready.',
  182. );
  183. _onNativeError(error);
  184. throw error;
  185. },
  186. );
  187. _checkConnectionAttempt(generation);
  188. if (_streamError case final error?) throw error;
  189. await _invoke<void>('connect', {'address': address});
  190. }
  191. void _checkConnectionAttempt(int generation) {
  192. _checkAvailable();
  193. if (generation != _connectionGeneration) {
  194. throw StateError('Bluetooth connection attempt has been canceled.');
  195. }
  196. }
  197. Future<void> write(List<int> bytes) async {
  198. _checkAvailable();
  199. if (bytes.any((byte) => byte < 0 || byte > 255)) {
  200. throw ArgumentError.value(bytes, 'bytes', 'Must contain unsigned bytes.');
  201. }
  202. await _invoke<void>('write', {'bytes': Uint8List.fromList(bytes)});
  203. }
  204. Future<void> disconnect() async {
  205. _connectionGeneration++;
  206. _checkAvailable();
  207. await _invoke<void>('disconnect');
  208. }
  209. Future<void> dispose() => _disposeFuture ??= _dispose();
  210. Future<void> _dispose() async {
  211. _connectionGeneration++;
  212. _disposed = true;
  213. if (!_ready.isCompleted) _ready.complete();
  214. try {
  215. if (isSupported && _subscription != null) {
  216. await _invoke<void>('disconnect');
  217. }
  218. } on PlatformException catch (error) {
  219. if (error.code != 'unsupported') rethrow;
  220. } finally {
  221. await _subscription?.cancel();
  222. await _received.close();
  223. await _events.close();
  224. }
  225. }
  226. }