print_page.dart 10 KB

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