123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360 |
- import 'dart:async';
- import 'package:amap_flutter_location/amap_location_option.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- import 'package:lszlgl/base/base_lifecycle_state.dart';
- import '../../drfit/database.dart';
- import '../../drfit/model_factory.dart';
- import '../../main.dart';
- import '../../plugin/bluetooth_plugin.dart';
- import '../../service/print_service.dart';
- import '../../utils/location_utils.dart';
- import '../home/home_page.dart';
- import 'dart:ui' as ui;
- class PrintPageArgs {
- /// 二维码数据
- Uint8List? bytes;
- List<String>? textList;
- String? numCode ;
- String? urlCode;
- List<PrintPageArgs>? printList; // 批量打印用
- PrintPageArgs({ this.bytes, this.textList, this.numCode,this.urlCode,this.printList});
- @override
- String toString() {
- return {'bytes': bytes}.toString();
- }
- }
- /// 电子签名
- class PrintPage extends StatefulWidget {
- final PrintPageArgs args;
- const PrintPage({
- super.key,
- required this.args,
- });
- @override
- State<PrintPage> createState() => _PrintPageState();
- }
- class _PrintPageState extends BaseLifecycleState<PrintPage> {
- late List<ServiceModel> serviceList;
- late List<BlueDeviceInfo> deviceList;
- late List<String> deviceMacList;
- String scanDeviceState = '';
- StreamSubscription? locationListener;
- StreamSubscription? onReceiveDataStreamListener;
- StreamSubscription? onDeviceStateStreamListener;
- String phoneAddress = '';
- @override
- void initState() {
- super.initState();
- serviceList = [
- ServiceModel(name: '搜索', icon: imgBleSearch, onTap: () => startScan()),
- ServiceModel(name: '打印', icon: imgBlePrint, onTap: (){
- if(widget.args.printList !=null ){
- startPrintList();
- }else{
- startPrint();
- }
- }),
- ];
- deviceList = [];
- deviceMacList = [];
- PrintService.hasBluetoothConnectDevice().then((result) {
- if(result == false) {
- PrintService.connectedDeviceList = [];
- PrintService.connectedDeviceMacList = [];
- }
- });
- getLocation();
- }
- void startPrintList() async{
- if(PrintService.connectedDeviceList.last.deviceName.contains("BTP")) {
- MyNavigator.showLoading(msg: '打印中...');
- for (PrintPageArgs arg in widget.args.printList!) {
- await PrintService.startBluetoothPrintBarCodeWithText(arg.urlCode!, arg.numCode!, arg.textList!);
- await Future.delayed(const Duration(seconds: 6));
- }
- MyNavigator.dismissLoading();
- MyNavigator.showToast('打印完成');
- }else{
- MyNavigator.showToast('暂时只支持BTP型号批量打印');
- }
- }
- /// 去打印
- Future<void> startPrint() async {
- int targetWidth = 560;
- if(PrintService.connectedDeviceList.last.deviceName.contains("BTP-UP321")) {
- targetWidth = 500;
- }
- final codec = await ui.instantiateImageCodec(
- widget.args.bytes!,
- targetHeight: 590, // 640
- targetWidth: targetWidth, // 560
- );
- final smallImage = (await codec.getNextFrame()).image;
- ByteData? smallBytes = await smallImage.toByteData(format: ui.ImageByteFormat.png);
- Uint8List? smallUint8List = smallBytes?.buffer.asUint8List();
- MyNavigator.showLoading(msg: '打印中...');
- if(PrintService.connectedDeviceList.last.deviceName.contains("BTP")) {
- await PrintService.startBluetoothPrintBitMapAndText(smallUint8List!, widget.args.textList!);
- } else {
- await PrintService.startBluetoothPrintBitMap(smallUint8List!);
- await PrintService.startBluetoothPrintText(widget.args.textList!);
- }
- MyNavigator.dismiss();
- MyNavigator.showToast('打印成功');
- }
- /// 去搜索
- Future<void> startScan() async {
- setState(() {
- deviceList = [];
- deviceMacList = [];
- });
- await PrintService.startBluetoothDiscovery();
- }
- Future<int> savaToSqlite(BlueDeviceInfo deviceInfo) async {
- DeviceInfoTableCompanion tableCompanion = await ModelFactory.convertToTSlideComp(deviceInfo.deviceMac, deviceInfo.deviceName, phoneAddress);
- return await database.deviceInfoTableDao.addOneDeviceComp(tableCompanion);
- }
- /// 去连接
- Future<void> startConnect(BlueDeviceInfo deviceInfo) async {
- if(deviceInfo.connectStateStr.contains('未配对')) {
- MyNavigator.showLoading(msg: '配对中...');
- await PrintService.startBluetoothPair(deviceInfo);
- } else if(deviceInfo.connectStateStr.contains('已配对')) {
- MyNavigator.showLoading(msg: '连接中...');
- int connectResult = await PrintService.startBluetoothConnect(deviceInfo);
- if(connectResult == 0) { // 连接成功
- MyNavigator.dismiss();
- MyNavigator.showToast('连接成功');
- deviceInfo.connectSuccess();
- //addOneSlideComp
- if(deviceMacList.contains(deviceInfo.deviceMac)) {
- setState(() {
- deviceMacList.removeWhere((element) => element == deviceInfo.deviceMac);
- deviceList.removeWhere((element) => element.deviceMac == deviceInfo.deviceMac);
- });
- }
- setState(() {
- PrintService.connectedDeviceMacList.add(deviceInfo.deviceMac);
- PrintService.connectedDeviceList.add(deviceInfo);
- });
- await savaToSqlite(deviceInfo); // 保存记录到数据库
- database.savaBleDataToServer(); // 同步记录到服务器
- } else {
- MyNavigator.dismiss();
- MyNavigator.showToast('连接失败');
- }
- } else if(deviceInfo.connectStateStr.contains('断开')) {
- int connectResult = await PrintService.endBluetoothConnect(deviceInfo);
- if(connectResult == 0) { // 断开成功
- deviceInfo.disConnectSuccess();
- if(PrintService.connectedDeviceMacList.contains(deviceInfo.deviceMac)) {
- setState(() {
- PrintService.connectedDeviceMacList.removeWhere((element) => element == deviceInfo.deviceMac);
- PrintService.connectedDeviceList.removeWhere((element) => element.deviceMac == deviceInfo.deviceMac);
- });
- }
- setState(() {
- deviceMacList.add(deviceInfo.deviceMac);
- deviceList.add(deviceInfo);
- });
- }
- }
- }
- void getLocation() async {
- bool granted = await LocationUtils.checkLocationAvailable();
- if (!granted) {
- return;
- }
- LocationUtils.setLocationOption(AMapLocationOption(onceLocation: true));
- LocationUtils.startLocation();
- }
- void initLocation() {
- locationListener = LocationUtils.onLocationChanged().listen((value) async {
- phoneAddress = value['address'] as String;
- });
- }
- @override
- void onInit() {
- onReceiveDataStreamListener = BluetoothPlugin.instance.onReceiveDataStream.listen((deviceInfo) {
- if(deviceInfo != null) {
- if(deviceMacList.contains(deviceInfo.deviceMac)) {
- setState(() {
- deviceMacList.removeWhere((element) => element == deviceInfo.deviceMac);
- deviceList.removeWhere((element) => element.deviceMac == deviceInfo.deviceMac);
- });
- }
- setState(() {
- // 只显示支持的打印机
- if(deviceInfo.deviceName.contains('BTP') || deviceInfo.deviceName.contains('B3S') || deviceInfo.deviceName.contains('A8')) {
- deviceMacList.add(deviceInfo.deviceMac);
- deviceList.add(deviceInfo);
- }
- });
- }
- });
- onDeviceStateStreamListener = BluetoothPlugin.instance.onDeviceStateStream.listen((deviceState) {
- if(deviceState == DeviceState.pairEnd) {
- MyNavigator.dismiss();
- }
- setState(() {
- scanDeviceState = deviceState ?? "";
- });
- });
- initLocation();
- }
- @override
- void onDestroy() {
- LocationUtils.stopLocation();
- LocationUtils.destroy();
- locationListener?.cancel();
- onDeviceStateStreamListener?.cancel();
- onReceiveDataStreamListener?.cancel();
- }
- @override
- Widget build(BuildContext context) {
- return myScaffold(
- child: Column(
- children: [
- myAppBar(title: '打印二维码'),
- const SizedBox(height: 18),
- buildServiceItem(serviceList[0]),
- Offstage(
- offstage: PrintService.connectedDeviceList.isEmpty,
- child: const Text('已连接打印机'),
- ),
- ...List.generate(
- PrintService.connectedDeviceList.length,
- (index) => buildDeviceItem(PrintService.connectedDeviceList[index]),
- ).toList(),
- Offstage(
- offstage: deviceList.isEmpty,
- child: const Text('可用打印机'),
- ),
- ...List.generate(
- deviceList.length,
- (index) => buildDeviceItem(deviceList[index]),
- ).toList(),
- Offstage(
- offstage: PrintService.connectedDeviceList.isEmpty,
- child: buildServiceItem(serviceList[1]),
- )
- ],
- ),
- );
- }
- Widget buildServiceItem(ServiceModel service) {
- return GestureDetector(
- onTap: service.onTap,
- child: Container(
- margin: const EdgeInsets.only(left: 12, right: 12, bottom: 22),
- padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 40),
- clipBehavior: Clip.hardEdge,
- decoration: BoxDecoration(
- borderRadius: const BorderRadius.all(Radius.circular(12)),
- boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), offset: const Offset(0, 5), blurRadius: 4)],
- image: const DecorationImage(image: AssetImage(imgHomeListBg), fit: BoxFit.fill),
- ),
- child: Row(
- children: [
- Image.asset(service.icon, height: 64),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- "${service.name}${(service.name.contains('搜索')&&scanDeviceState == DeviceState.scanStart) ? "中..." : ""}",
- textAlign: TextAlign.center,
- style: const TextStyle(color: Color(0xFF333333), fontSize: 20, fontWeight: FontWeight.w500),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- );
- }
- Widget buildDeviceItem(BlueDeviceInfo deviceInfo) {
- return GestureDetector(
- onTap: () {
- // 连接
- startConnect(deviceInfo);
- },
- child: Container(
- margin: const EdgeInsets.only(left: 12, right: 12, bottom: 22),
- padding: const EdgeInsets.symmetric(vertical: 10),
- clipBehavior: Clip.hardEdge,
- decoration: BoxDecoration(
- borderRadius: const BorderRadius.all(Radius.circular(12)),
- boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), offset: const Offset(0, 5), blurRadius: 4)],
- image: const DecorationImage(image: AssetImage(imgHomeListBg), fit: BoxFit.fill),
- ),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceAround,
- children: [
- Text(
- deviceInfo.deviceName,
- textAlign: TextAlign.center,
- style: const TextStyle(color: Color(0xFF333333), fontSize: 15, fontWeight: FontWeight.w500),
- ),
- Text(
- deviceInfo.connectStateStr,
- textAlign: TextAlign.center,
- style: const TextStyle(color: Color(0xFF333333), fontSize: 15, fontWeight: FontWeight.w500),
- ),
- ],
- ),
- ),
- );
- }
- }
|