print_page.dart 11 KB

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