76 lines
1.9 KiB
Dart
76 lines
1.9 KiB
Dart
import 'dart:typed_data';
|
|
|
|
import 'package:aman_kassa_flutter/core/base/base_service.dart';
|
|
import 'package:bluetooth_print/bluetooth_print.dart';
|
|
import 'package:bluetooth_print/bluetooth_print_model.dart';
|
|
|
|
|
|
|
|
class BluePrintService extends BaseService {
|
|
BluetoothPrint _bluetooth = BluetoothPrint.instance;
|
|
BluetoothDevice? _device;
|
|
|
|
Future<void> scan() async {
|
|
await _bluetooth.startScan(timeout: Duration(seconds: 4));
|
|
}
|
|
|
|
Future<void> stopScan() async {
|
|
await _bluetooth.stopScan();
|
|
}
|
|
|
|
Stream<List<BluetoothDevice>> get scanResult => _bluetooth.scanResults;
|
|
|
|
|
|
Stream<bool> get isScanning => _bluetooth.isScanning;
|
|
Stream<int> get state => _bluetooth.state;
|
|
set device(BluetoothDevice device) => _device = device;
|
|
|
|
|
|
Future<bool> connect() async {
|
|
bool response = false;
|
|
if (_device == null) {
|
|
response = false;
|
|
} else {
|
|
try {
|
|
await _bluetooth.connect(_device!);
|
|
await Future.delayed(Duration(seconds: 5));
|
|
response = true;
|
|
} catch (e) {
|
|
print('Error connect $e');
|
|
response = false;
|
|
}
|
|
}
|
|
return response;
|
|
}
|
|
|
|
Future<bool> disconnect() async {
|
|
bool response = false;
|
|
try {
|
|
await _bluetooth.disconnect();
|
|
response = true;
|
|
} catch (e) {
|
|
print('Error $e');
|
|
response = false;
|
|
}
|
|
return response;
|
|
}
|
|
|
|
Future<bool> printBytes(Uint8List bytes, { int chunkSizeBytes = 20, int queueSleepTimeMs = 20 }) async {
|
|
Map<String, dynamic> config = Map();
|
|
final len = bytes.length;
|
|
List<List<int>> chunks = [];
|
|
for (var i = 0; i < len; i += chunkSizeBytes) {
|
|
var end = (i + chunkSizeBytes < len) ? i + chunkSizeBytes : len;
|
|
chunks.add(bytes.sublist(i, end));
|
|
}
|
|
|
|
for (var i = 0; i < chunks.length; i += 1) {
|
|
await _bluetooth.rawBytes(config, chunks[i]);
|
|
await Future.delayed(Duration(milliseconds: queueSleepTimeMs));
|
|
}
|
|
|
|
|
|
return true;
|
|
}
|
|
}
|