connect method
Connect to a printer device
Implementation
Future<bool> connect(Printer device) async {
if (device.connectionType == ConnectionType.USB) {
if (Platform.isWindows) {
// Windows USB connection - device is already available, no connection needed
return true;
} else {
return FlutterThermalPrinterPlatform.instance.connect(device);
}
} else if (device.connectionType == ConnectionType.BLE) {
try {
if (device.address == null) {
log('Device address is null');
return false;
}
final isConnected =
(await UniversalBle.getConnectionState(device.address!) ==
BleConnectionState.connected);
if (isConnected) {
log('Device ${device.name} is already connected');
return true;
}
log('Connecting to BLE device ${device.name} at ${device.address}');
// Connect using universal_ble for all platforms including Windows
await device.connect();
// Wait a moment to establish connection
await Future.delayed(const Duration(seconds: 10));
return (await UniversalBle.getConnectionState(device.address!) ==
BleConnectionState.connected);
} catch (e) {
log('Failed to connect to BLE device: $e');
return false;
}
}
return false;
}