print_page.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import 'dart:async';
  2. import 'package:amap_flutter_location/amap_location_option.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter/services.dart';
  5. import 'package:lszlgl/base/base_lifecycle_state.dart';
  6. import '../../drfit/database.dart';
  7. import '../../drfit/model_factory.dart';
  8. import '../../main.dart';
  9. import '../../plugin/bluetooth_plugin.dart';
  10. import '../../service/print_service.dart';
  11. import '../../utils/location_utils.dart';
  12. import '../home/home_page.dart';
  13. import 'dart:ui' as ui;
  14. class PrintPageArgs {
  15. /// 二维码数据
  16. Uint8List? bytes;
  17. List<String>? textList;
  18. String? numCode ;
  19. String? urlCode;
  20. List<PrintPageArgs>? printList; // 批量打印用
  21. PrintPageArgs({ this.bytes, this.textList, this.numCode,this.urlCode,this.printList});
  22. @override
  23. String toString() {
  24. return {'bytes': bytes}.toString();
  25. }
  26. }
  27. /// 电子签名
  28. class PrintPage extends StatefulWidget {
  29. final PrintPageArgs args;
  30. const PrintPage({
  31. super.key,
  32. required this.args,
  33. });
  34. @override
  35. State<PrintPage> createState() => _PrintPageState();
  36. }
  37. class _PrintPageState extends BaseLifecycleState<PrintPage> {
  38. late List<ServiceModel> serviceList;
  39. late List<BlueDeviceInfo> deviceList;
  40. late List<String> deviceMacList;
  41. String scanDeviceState = '';
  42. StreamSubscription? locationListener;
  43. StreamSubscription? onReceiveDataStreamListener;
  44. StreamSubscription? onDeviceStateStreamListener;
  45. String phoneAddress = '';
  46. @override
  47. void initState() {
  48. super.initState();
  49. serviceList = [
  50. ServiceModel(name: '搜索', icon: imgBleSearch, onTap: () => startScan()),
  51. ServiceModel(name: '打印', icon: imgBlePrint, onTap: (){
  52. if(widget.args.printList !=null ){
  53. startPrintList();
  54. }else{
  55. startPrint();
  56. }
  57. }),
  58. ];
  59. deviceList = [];
  60. deviceMacList = [];
  61. PrintService.hasBluetoothConnectDevice().then((result) {
  62. if(result == false) {
  63. PrintService.connectedDeviceList = [];
  64. PrintService.connectedDeviceMacList = [];
  65. }
  66. });
  67. getLocation();
  68. }
  69. void startPrintList() async{
  70. if(PrintService.connectedDeviceList.last.deviceName.contains("BTP")) {
  71. MyNavigator.showLoading(msg: '打印中...');
  72. for (PrintPageArgs arg in widget.args.printList!) {
  73. await PrintService.startBluetoothPrintBarCodeWithText(arg.urlCode!, arg.numCode!, arg.textList!);
  74. await Future.delayed(const Duration(seconds: 6));
  75. }
  76. MyNavigator.dismissLoading();
  77. MyNavigator.showToast('打印完成');
  78. }else{
  79. MyNavigator.showToast('暂时只支持BTP型号批量打印');
  80. }
  81. }
  82. /// 去打印
  83. Future<void> startPrint() async {
  84. int targetWidth = 560;
  85. if(PrintService.connectedDeviceList.last.deviceName.contains("BTP-UP321")) {
  86. targetWidth = 500;
  87. }
  88. final codec = await ui.instantiateImageCodec(
  89. widget.args.bytes!,
  90. targetHeight: 590, // 640
  91. targetWidth: targetWidth, // 560
  92. );
  93. final smallImage = (await codec.getNextFrame()).image;
  94. ByteData? smallBytes = await smallImage.toByteData(format: ui.ImageByteFormat.png);
  95. Uint8List? smallUint8List = smallBytes?.buffer.asUint8List();
  96. MyNavigator.showLoading(msg: '打印中...');
  97. if(PrintService.connectedDeviceList.last.deviceName.contains("BTP")) {
  98. await PrintService.startBluetoothPrintBitMapAndText(smallUint8List!, widget.args.textList!);
  99. } else {
  100. await PrintService.startBluetoothPrintBitMap(smallUint8List!);
  101. await PrintService.startBluetoothPrintText(widget.args.textList!);
  102. }
  103. MyNavigator.dismiss();
  104. MyNavigator.showToast('打印成功');
  105. }
  106. /// 去搜索
  107. Future<void> startScan() async {
  108. setState(() {
  109. deviceList = [];
  110. deviceMacList = [];
  111. });
  112. await PrintService.startBluetoothDiscovery();
  113. }
  114. Future<int> savaToSqlite(BlueDeviceInfo deviceInfo) async {
  115. DeviceInfoTableCompanion tableCompanion = await ModelFactory.convertToTSlideComp(deviceInfo.deviceMac, deviceInfo.deviceName, phoneAddress);
  116. return await database.deviceInfoTableDao.addOneDeviceComp(tableCompanion);
  117. }
  118. /// 去连接
  119. Future<void> startConnect(BlueDeviceInfo deviceInfo) async {
  120. if(deviceInfo.connectStateStr.contains('未配对')) {
  121. MyNavigator.showLoading(msg: '配对中...');
  122. await PrintService.startBluetoothPair(deviceInfo);
  123. } else if(deviceInfo.connectStateStr.contains('已配对')) {
  124. MyNavigator.showLoading(msg: '连接中...');
  125. int connectResult = await PrintService.startBluetoothConnect(deviceInfo);
  126. if(connectResult == 0) { // 连接成功
  127. MyNavigator.dismiss();
  128. MyNavigator.showToast('连接成功');
  129. deviceInfo.connectSuccess();
  130. //addOneSlideComp
  131. if(deviceMacList.contains(deviceInfo.deviceMac)) {
  132. setState(() {
  133. deviceMacList.removeWhere((element) => element == deviceInfo.deviceMac);
  134. deviceList.removeWhere((element) => element.deviceMac == deviceInfo.deviceMac);
  135. });
  136. }
  137. setState(() {
  138. PrintService.connectedDeviceMacList.add(deviceInfo.deviceMac);
  139. PrintService.connectedDeviceList.add(deviceInfo);
  140. });
  141. await savaToSqlite(deviceInfo); // 保存记录到数据库
  142. database.savaBleDataToServer(); // 同步记录到服务器
  143. } else {
  144. MyNavigator.dismiss();
  145. MyNavigator.showToast('连接失败');
  146. }
  147. } else if(deviceInfo.connectStateStr.contains('断开')) {
  148. int connectResult = await PrintService.endBluetoothConnect(deviceInfo);
  149. if(connectResult == 0) { // 断开成功
  150. deviceInfo.disConnectSuccess();
  151. if(PrintService.connectedDeviceMacList.contains(deviceInfo.deviceMac)) {
  152. setState(() {
  153. PrintService.connectedDeviceMacList.removeWhere((element) => element == deviceInfo.deviceMac);
  154. PrintService.connectedDeviceList.removeWhere((element) => element.deviceMac == deviceInfo.deviceMac);
  155. });
  156. }
  157. setState(() {
  158. deviceMacList.add(deviceInfo.deviceMac);
  159. deviceList.add(deviceInfo);
  160. });
  161. }
  162. }
  163. }
  164. void getLocation() async {
  165. bool granted = await LocationUtils.checkLocationAvailable();
  166. if (!granted) {
  167. return;
  168. }
  169. LocationUtils.setLocationOption(AMapLocationOption(onceLocation: true));
  170. LocationUtils.startLocation();
  171. }
  172. void initLocation() {
  173. locationListener = LocationUtils.onLocationChanged().listen((value) async {
  174. phoneAddress = value['address'] as String;
  175. });
  176. }
  177. @override
  178. void onInit() {
  179. onReceiveDataStreamListener = BluetoothPlugin.instance.onReceiveDataStream.listen((deviceInfo) {
  180. if(deviceInfo != null) {
  181. if(deviceMacList.contains(deviceInfo.deviceMac)) {
  182. setState(() {
  183. deviceMacList.removeWhere((element) => element == deviceInfo.deviceMac);
  184. deviceList.removeWhere((element) => element.deviceMac == deviceInfo.deviceMac);
  185. });
  186. }
  187. setState(() {
  188. // 只显示支持的打印机
  189. if(deviceInfo.deviceName.contains('BTP') || deviceInfo.deviceName.contains('B3S') || deviceInfo.deviceName.contains('A8')) {
  190. deviceMacList.add(deviceInfo.deviceMac);
  191. deviceList.add(deviceInfo);
  192. }
  193. });
  194. }
  195. });
  196. onDeviceStateStreamListener = BluetoothPlugin.instance.onDeviceStateStream.listen((deviceState) {
  197. if(deviceState == DeviceState.pairEnd) {
  198. MyNavigator.dismiss();
  199. }
  200. setState(() {
  201. scanDeviceState = deviceState ?? "";
  202. });
  203. });
  204. initLocation();
  205. }
  206. @override
  207. void onDestroy() {
  208. LocationUtils.stopLocation();
  209. LocationUtils.destroy();
  210. locationListener?.cancel();
  211. onDeviceStateStreamListener?.cancel();
  212. onReceiveDataStreamListener?.cancel();
  213. }
  214. @override
  215. Widget build(BuildContext context) {
  216. return myScaffold(
  217. child: Column(
  218. children: [
  219. myAppBar(title: '打印二维码'),
  220. const SizedBox(height: 18),
  221. buildServiceItem(serviceList[0]),
  222. Offstage(
  223. offstage: PrintService.connectedDeviceList.isEmpty,
  224. child: const Text('已连接打印机'),
  225. ),
  226. ...List.generate(
  227. PrintService.connectedDeviceList.length,
  228. (index) => buildDeviceItem(PrintService.connectedDeviceList[index]),
  229. ).toList(),
  230. Offstage(
  231. offstage: deviceList.isEmpty,
  232. child: const Text('可用打印机'),
  233. ),
  234. ...List.generate(
  235. deviceList.length,
  236. (index) => buildDeviceItem(deviceList[index]),
  237. ).toList(),
  238. Offstage(
  239. offstage: PrintService.connectedDeviceList.isEmpty,
  240. child: buildServiceItem(serviceList[1]),
  241. )
  242. ],
  243. ),
  244. );
  245. }
  246. Widget buildServiceItem(ServiceModel service) {
  247. return GestureDetector(
  248. onTap: service.onTap,
  249. child: Container(
  250. margin: const EdgeInsets.only(left: 12, right: 12, bottom: 22),
  251. padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 40),
  252. clipBehavior: Clip.hardEdge,
  253. decoration: BoxDecoration(
  254. borderRadius: const BorderRadius.all(Radius.circular(12)),
  255. boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), offset: const Offset(0, 5), blurRadius: 4)],
  256. image: const DecorationImage(image: AssetImage(imgHomeListBg), fit: BoxFit.fill),
  257. ),
  258. child: Row(
  259. children: [
  260. Image.asset(service.icon, height: 64),
  261. const SizedBox(width: 12),
  262. Expanded(
  263. child: Column(
  264. mainAxisSize: MainAxisSize.min,
  265. children: [
  266. Text(
  267. "${service.name}${(service.name.contains('搜索')&&scanDeviceState == DeviceState.scanStart) ? "中..." : ""}",
  268. textAlign: TextAlign.center,
  269. style: const TextStyle(color: Color(0xFF333333), fontSize: 20, fontWeight: FontWeight.w500),
  270. ),
  271. ],
  272. ),
  273. ),
  274. ],
  275. ),
  276. ),
  277. );
  278. }
  279. Widget buildDeviceItem(BlueDeviceInfo deviceInfo) {
  280. return GestureDetector(
  281. onTap: () {
  282. // 连接
  283. startConnect(deviceInfo);
  284. },
  285. child: Container(
  286. margin: const EdgeInsets.only(left: 12, right: 12, bottom: 22),
  287. padding: const EdgeInsets.symmetric(vertical: 10),
  288. clipBehavior: Clip.hardEdge,
  289. decoration: BoxDecoration(
  290. borderRadius: const BorderRadius.all(Radius.circular(12)),
  291. boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), offset: const Offset(0, 5), blurRadius: 4)],
  292. image: const DecorationImage(image: AssetImage(imgHomeListBg), fit: BoxFit.fill),
  293. ),
  294. child: Row(
  295. mainAxisAlignment: MainAxisAlignment.spaceAround,
  296. children: [
  297. Text(
  298. deviceInfo.deviceName,
  299. textAlign: TextAlign.center,
  300. style: const TextStyle(color: Color(0xFF333333), fontSize: 15, fontWeight: FontWeight.w500),
  301. ),
  302. Text(
  303. deviceInfo.connectStateStr,
  304. textAlign: TextAlign.center,
  305. style: const TextStyle(color: Color(0xFF333333), fontSize: 15, fontWeight: FontWeight.w500),
  306. ),
  307. ],
  308. ),
  309. ),
  310. );
  311. }
  312. }