I am trying to connect to my Raspberry Pi 4 bluetooth from a Flutter app.
However, the flutter app is not even recognizing the Raspberry Pi 4 bluetooth.
This is the app screen which only shows the earphone.
App Interface showing the available bluetooth devices
This is my phone’s bluetooth control screen which shows both the Pi – nil
and my local PC.
New Pair Screen
Ans this is my code –
import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'dart:async';
class ConnectDeviceScreen extends StatefulWidget {
@override
_BluetoothModuleState createState() => _BluetoothModuleState();
}
class _BluetoothModuleState extends State<ConnectDeviceScreen> {
final FlutterReactiveBle _ble = FlutterReactiveBle();
List<DiscoveredDevice> _devices = [];
StreamSubscription<DiscoveredDevice>? _scanSubscription;
StreamSubscription<ConnectionStateUpdate>? _connectionSubscription;
bool _isScanning = false;
@override
void initState() {
super.initState();
_checkBleStatus();
}
void _checkBleStatus() {
_ble.statusStream.listen((status) {
print('BLE status: $status');
if (status == BleStatus.ready) {
_startScan();
}
});
}
void _startScan() {
setState(() {
_isScanning = true;
_devices.clear();
});
_scanSubscription = _ble.scanForDevices(
withServices: [], // Empty list means scan for all devices
scanMode: ScanMode.lowLatency,
).listen(
(device) {
setState(() {
final knownDeviceIndex =
_devices.indexWhere((d) => d.id == device.id);
if (knownDeviceIndex >= 0) {
_devices[knownDeviceIndex] = device;
} else {
_devices.add(device);
}
});
},
onError: (Object error) {
print('Scanning failed: $error');
setState(() {
_isScanning = false;
});
},
);
// Stop scanning after 10 seconds
Timer(Duration(seconds: 60), () {
_stopScan();
});
}
void _stopScan() {
_scanSubscription?.cancel();
setState(() {
_isScanning = false;
});
}
Future<void> _connectToDevice(DiscoveredDevice device) async {
try {
print('Connecting to ${device.name}...');
_connectionSubscription = _ble
.connectToDevice(
id: device.id,
connectionTimeout: const Duration(seconds: 5),
)
.listen(
(connectionState) {
print('Connection state: ${connectionState.connectionState}');
if (connectionState.connectionState ==
DeviceConnectionState.connected) {
print('Connected to ${device.name}');
// Here you can perform operations like service discovery,
// reading/writing characteristics, etc.
// For example:
// _discoverServices(device.id);
}
},
onError: (Object error) {
print('Connection failed: $error');
},
);
} catch (e) {
print('Failed to connect: $e');
}
}
// Example of reading a characteristic
// You'll need to replace the UUIDs with your specific ones
Future<void> _readCharacteristic(String deviceId) async {
final characteristic = QualifiedCharacteristic(
serviceId: Uuid.parse("YOUR_SERVICE_UUID"),
characteristicId: Uuid.parse("YOUR_CHARACTERISTIC_UUID"),
deviceId: deviceId,
);
try {
final response = await _ble.readCharacteristic(characteristic);
print('Read characteristic: ${response}');
} catch (e) {
print('Error reading characteristic: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Bluetooth Devices')),
body: ListView.builder(
itemCount: _devices.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_devices[index].name),
subtitle: Text(_devices[index].id),
trailing: ElevatedButton(
child: Text('Connect'),
onPressed: () => _connectToDevice(_devices[index]),
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _isScanning ? _stopScan : _startScan,
child: Icon(_isScanning ? Icons.stop : Icons.search),
),
);
}
@override
void dispose() {
_scanSubscription?.cancel();
_connectionSubscription?.cancel();
super.dispose();
}
}
Why can’t the flutter app recognize the Raspberry Pi ? When I am connecting normally, using the default phone pairing method outside the flutter app, it connects fine with Pi.