2025-11-04 14:58:51 +07:00

121 lines
3.4 KiB
Dart

import 'dart:developer';
import 'package:dartz/dartz.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:injectable/injectable.dart';
import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart';
import '../../../domain/printer/printer.dart';
@Injectable(as: IPrinterRepository)
class PrinterRepository implements IPrinterRepository {
final _logName = 'PrinterRepository';
PrinterRepository();
@override
Future<Either<PrinterFailure, bool>> connectBluetooth(
String macAddress,
) async {
try {
bool isConnected = await PrintBluetoothThermal.connectionStatus;
if (isConnected) {
log("Already connected to Bluetooth printer", name: _logName);
return right(true);
}
bool connected = await PrintBluetoothThermal.connect(
macPrinterAddress: macAddress,
);
if (connected) {
log(
"Successfully connected to Bluetooth printer: $macAddress",
name: _logName,
);
} else {
FirebaseCrashlytics.instance.recordError(
'Failed to connect to Bluetooth printer',
null,
reason: 'Failed to connect to Bluetooth printe',
information: [
'function: connectBluetoothPrinter(String macAddress)',
'macAddress: $macAddress',
],
);
log(
"Failed to connect to Bluetooth printer: $macAddress",
name: _logName,
);
}
return right(connected);
} catch (e, stackTrace) {
FirebaseCrashlytics.instance.recordError(
e,
stackTrace,
reason: 'Error connecting to Bluetooth printer',
information: [
'function: connectBluetoothPrinter(String macAddress)',
'Printer: Bluetooth printer',
'macAddress: $macAddress',
],
);
log("Error connecting to Bluetooth printer", name: _logName, error: e);
return left(
PrinterFailure.dynamicErrorMessage(
'Error connecting to Bluetooth printer',
),
);
}
}
@override
Future<Either<PrinterFailure, bool>> disconectBluetooth() async {
try {
bool result = await PrintBluetoothThermal.disconnect;
log("Bluetooth printer disconnected: $result", name: _logName);
return right(result);
} catch (e) {
log("Error disconnecting Bluetooth printer", error: e, name: _logName);
return left(
PrinterFailure.dynamicErrorMessage(
'Error disconnecting Bluetooth printer',
),
);
}
}
@override
Future<Either<PrinterFailure, List<BluetoothInfo>>>
getPairedBluetoothDevices() async {
try {
final result = await PrintBluetoothThermal.pairedBluetooths;
log("Paired Bluetooth devices: $result", name: _logName);
return right(result);
} catch (e) {
log("Error getting paired Bluetooth devices", name: _logName, error: e);
return left(
PrinterFailure.dynamicErrorMessage(
'Error getting paired Bluetooth devices',
),
);
}
}
@override
Future<Either<PrinterFailure, bool>> isBluetoothEnabled() async {
try {
final result = await PrintBluetoothThermal.bluetoothEnabled;
return right(result);
} catch (e) {
log("Error checking Bluetooth status", name: _logName, error: e);
return left(
PrinterFailure.dynamicErrorMessage('Error checking Bluetooth status'),
);
}
}
}