connect method
Initiates a connection to a BLE peripheral and returns a Stream representing the connection state.
Implementation
@override
Future<Stream<BleConnectionState>> connect({
required String deviceAddress,
}) async {
// Reuse existing controller if one exists, or create a new one This ensures that both connect() and
// observeConnectionState() can share the same stream
final StreamController<BleConnectionState> controller =
_connectionControllers.putIfAbsent(
deviceAddress,
StreamController<BleConnectionState>.broadcast,
);
// Simulate the connection process with state changes
final BleConnectionState initialState =
_connectionStates[deviceAddress] ?? BleConnectionState.disconnected;
// Emit the initial state
controller.add(initialState);
// Simulate connection after a short delay
Future<void>.delayed(const Duration(milliseconds: 50), () {
if (!controller.isClosed) {
_connectionStates[deviceAddress] = BleConnectionState.connected;
controller.add(BleConnectionState.connected);
}
});
return controller.stream;
}