print_page.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. Offstage(
  201. offstage: PrintService.connectedDeviceList.isEmpty,
  202. child: const Text('已连接打印机'),
  203. ),
  204. ...List.generate(
  205. PrintService.connectedDeviceList.length,
  206. (index) => buildDeviceItem(PrintService.connectedDeviceList[index]),
  207. ).toList(),
  208. Offstage(
  209. offstage: deviceList.isEmpty,
  210. child: const Text('可用打印机'),
  211. ),
  212. ...List.generate(
  213. deviceList.length,
  214. (index) => buildDeviceItem(deviceList[index]),
  215. ).toList(),
  216. Offstage(
  217. offstage: PrintService.connectedDeviceList.isEmpty,
  218. child: buildServiceItem(serviceList[1]),
  219. )
  220. ],
  221. ),
  222. );
  223. }
  224. Widget buildServiceItem(ServiceModel service) {
  225. return GestureDetector(
  226. onTap: service.onTap,
  227. child: Container(
  228. margin: const EdgeInsets.only(left: 12, right: 12, bottom: 22),
  229. padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 40),
  230. clipBehavior: Clip.hardEdge,
  231. decoration: BoxDecoration(
  232. borderRadius: const BorderRadius.all(Radius.circular(12)),
  233. boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), offset: const Offset(0, 5), blurRadius: 4)],
  234. image: const DecorationImage(image: AssetImage(imgHomeListBg), fit: BoxFit.fill),
  235. ),
  236. child: Row(
  237. children: [
  238. Image.asset(service.icon, height: 64),
  239. const SizedBox(width: 12),
  240. Expanded(
  241. child: Column(
  242. mainAxisSize: MainAxisSize.min,
  243. children: [
  244. Text(
  245. "${service.name}${(service.name.contains('搜索')&&scanDeviceState == DeviceState.scanStart) ? "中..." : ""}",
  246. textAlign: TextAlign.center,
  247. style: const TextStyle(color: Color(0xFF333333), fontSize: 20, fontWeight: FontWeight.w500),
  248. ),
  249. ],
  250. ),
  251. ),
  252. ],
  253. ),
  254. ),
  255. );
  256. }
  257. Widget buildDeviceItem(BlueDeviceInfo deviceInfo) {
  258. return GestureDetector(
  259. onTap: () {
  260. // 连接
  261. startConnect(deviceInfo);
  262. },
  263. child: Container(
  264. margin: const EdgeInsets.only(left: 12, right: 12, bottom: 22),
  265. padding: const EdgeInsets.symmetric(vertical: 10),
  266. clipBehavior: Clip.hardEdge,
  267. decoration: BoxDecoration(
  268. borderRadius: const BorderRadius.all(Radius.circular(12)),
  269. boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), offset: const Offset(0, 5), blurRadius: 4)],
  270. image: const DecorationImage(image: AssetImage(imgHomeListBg), fit: BoxFit.fill),
  271. ),
  272. child: Row(
  273. mainAxisAlignment: MainAxisAlignment.spaceAround,
  274. children: [
  275. Text(
  276. deviceInfo.deviceName,
  277. textAlign: TextAlign.center,
  278. style: const TextStyle(color: Color(0xFF333333), fontSize: 15, fontWeight: FontWeight.w500),
  279. ),
  280. Text(
  281. deviceInfo.connectStateStr,
  282. textAlign: TextAlign.center,
  283. style: const TextStyle(color: Color(0xFF333333), fontSize: 15, fontWeight: FontWeight.w500),
  284. ),
  285. ],
  286. ),
  287. ),
  288. );
  289. }
  290. }