I am trying to connect to a microcontroller (MCU) using Bluetooth Low Energy (BLE), but I am not able to connect. Earlier, I was able to connect with the MCU but after a few updates from flutterflow I am not able to connect with the MCU.
What I am doing specifically to my use case is I am scanning a QR code which consists of the Mac Address and service UUID. I am routing this data of Mac address to connect with BLE.
Connecting to a Microcontroller using Bluetooth (BLE).
Custom Code
I am using the flutter_Blue_Plus library to create custom actions in order to connect with the MCU. This is my code to connect with the MCU.
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
Future<bool> connectDeviceUsingQR(String jsonString) async {
try {
// Parse the JSON string
final Map<String, dynamic> decodedJson = jsonDecode(jsonString);
final String? deviceId = decodedJson['deviceId'];
final String? serviceUuid = decodedJson['serviceUuid'];
if (deviceId == null || serviceUuid == null) {
debugPrint('Error: deviceId or serviceUuid is missing');
return false;
}
// Get the Bluetooth device using its ID
final device = BluetoothDevice.fromId(deviceId);
bool hasWriteCharacteristic = false;
// Attempt to connect to the device with a timeout
try {
if (!await device.isConnected) {
await device.connect().timeout(
const Duration(seconds: 2),
onTimeout: () {
debugPrint('Error: Connection timed out');
throw Exception('Connection timed out');
},
);
}
} catch (e) {
debugPrint('Error connecting to device: $e');
return false;
}
// Discover services and characteristics
final services = await device.discoverServices();
for (var service in services) {
if (service.uuid.toString() == serviceUuid) {
// Match with provided UUID
for (var characteristic in service.characteristics) {
if (characteristic.properties.write) {
hasWriteCharacteristic = true;
debugPrint('Found writable characteristic: ${characteristic.uuid}');
}
}
}
}
return hasWriteCharacteristic;
} catch (e) {
debugPrint('Unexpected error: $e');
return false;
}
}
Please suggest me what can be done?
Yes
4