import 'dart:async'; import 'dart:typed_data'; import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart'; /// Wraps flutter_bluetooth_serial for SPP/RFCOMM Classic BT. class BtService { BluetoothConnection? _connection; final StreamController _rawFrameController = StreamController.broadcast(); bool get isConnected => _connection?.isConnected ?? false; Stream get rawStream => _rawFrameController.stream; Future> getPairedDevices() async { return FlutterBluetoothSerial.instance.getBondedDevices(); } Future connect(BluetoothDevice device) async { if (_connection != null) { await disconnect(); } _connection = await BluetoothConnection.toAddress(device.address); _connection!.input!.listen( (Uint8List data) { if (!_rawFrameController.isClosed) { _rawFrameController.add(data); } }, onDone: () { _rawFrameController.addError('BT connection closed'); }, onError: (Object e) { _rawFrameController.addError(e); }, ); } Future write(Uint8List data) async { if (_connection?.isConnected ?? false) { _connection!.output.add(data); await _connection!.output.allSent; } } Future disconnect() async { await _connection?.close(); _connection = null; } void dispose() { disconnect(); _rawFrameController.close(); } }