print_page.dart 10 KB

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