Преглед на файлове

配对、连接、以及对应loading添加完成

周素华 преди 1 година
родител
ревизия
d4a134153d

+ 54 - 30
android/app/src/main/java/io/flutter/plugins/BluetoothPlugin.java

@@ -62,12 +62,11 @@ public class BluetoothPlugin implements FlutterPlugin, MethodChannel.MethodCallH
62 62
 
63 63
     OnDiscoveryDeviceStreamHandler onDiscoveryDeviceStreamHandler;
64 64
     private EventChannel onReceiveDeviceChannel;
65
-    public EventChannel.EventSink onReceiveSink;
66 65
 
67
-    private BlueDeviceInfo itemPosition;
68
-
69
-//    private MainActivity _mainActivity;
66
+    OnDeviceStateStreamHandler onDeviceStateStreamHandler;
67
+    private EventChannel onDeviceStateChannel;
70 68
 
69
+    private BlueDeviceInfo itemPosition;
71 70
 
72 71
     Context _applicationContext;
73 72
     private BluetoothAdapter mBluetoothAdapter;
@@ -104,8 +103,6 @@ public class BluetoothPlugin implements FlutterPlugin, MethodChannel.MethodCallH
104 103
     @Override
105 104
     public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
106 105
         setupChannels(flutterPluginBinding.getBinaryMessenger(), flutterPluginBinding.getApplicationContext());
107
-
108
-
109 106
     }
110 107
 
111 108
     private void setupChannels(BinaryMessenger binaryMessenger, Context applicationContext) {
@@ -118,6 +115,10 @@ public class BluetoothPlugin implements FlutterPlugin, MethodChannel.MethodCallH
118 115
         onReceiveDeviceChannel = new EventChannel(binaryMessenger, methodChannelName + "/onDiscoveryDevice");
119 116
         onDiscoveryDeviceStreamHandler = new OnDiscoveryDeviceStreamHandler();
120 117
         onReceiveDeviceChannel.setStreamHandler(onDiscoveryDeviceStreamHandler);
118
+
119
+        onDeviceStateChannel = new EventChannel(binaryMessenger, methodChannelName + "/onDeviceState");
120
+        onDeviceStateStreamHandler = new OnDeviceStateStreamHandler();
121
+        onDeviceStateChannel.setStreamHandler(onDeviceStateStreamHandler);
121 122
     }
122 123
 
123 124
     @Override
@@ -149,6 +150,11 @@ public class BluetoothPlugin implements FlutterPlugin, MethodChannel.MethodCallH
149 150
                 Log.d("ble", "startBluetoothConnect :"+methodCall.arguments);
150 151
                 startBluetoothConnect(methodCall, result);
151 152
                 break;
153
+            case "endBluetoothConnect":
154
+                Log.d("ble", "endBluetoothConnect :"+methodCall.arguments);
155
+                endBluetoothConnect(methodCall, result);
156
+                break;
157
+
152 158
 
153 159
 
154 160
             case "autoLogin":
@@ -220,18 +226,17 @@ public class BluetoothPlugin implements FlutterPlugin, MethodChannel.MethodCallH
220 226
         if (mBluetoothAdapter.isDiscovering()) {
221 227
             mBluetoothAdapter.cancelDiscovery();
222 228
         }
223
-        Log.d("ble", "startBluetoothPair");
224
-        String deviceMac = methodCall.arguments.toString();
225
-        String[] deviceInfoList = deviceMac.split(delimiterStr);
229
+
230
+        String deviceInfo = methodCall.arguments.toString();
231
+        String[] deviceInfoList = deviceInfo.split(delimiterStr);
232
+        for(int i =0; i < deviceInfoList.length ; i++) {
233
+            Log.d("ble", i+":"+deviceInfoList[i]);
234
+        }
235
+        Log.d("ble", "startBluetoothPair : ---"+deviceInfo + "----0:"+deviceInfoList[0]);
226 236
         itemPosition = new BlueDeviceInfo(deviceInfoList[0], deviceInfoList[1], Integer.parseInt(deviceInfoList[2]));
227 237
         BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(itemPosition.getDeviceHardwareAddress());
228 238
 
229 239
         executorService.submit(() -> {
230
-//            requireActivity().runOnUiThread(() -> {
231
-//                bind.spinKit.setVisibility(View.GONE);
232
-//                fragment = new MyDialogLoadingFragment("配对中");
233
-//                fragment.show(requireActivity().getSupportFragmentManager(), "pairing");
234
-//            });
235 240
             Log.d("ble", "配对: 开始");
236 241
             boolean returnValue = false;
237 242
             try {
@@ -262,26 +267,21 @@ public class BluetoothPlugin implements FlutterPlugin, MethodChannel.MethodCallH
262 267
         BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(itemPosition.getDeviceHardwareAddress());
263 268
 
264 269
         executorService.submit(() -> {
265
-//            requireActivity().runOnUiThread(() -> {
266
-//                bind.spinKit.setVisibility(View.GONE);
267
-//                fragment = new MyDialogLoadingFragment("连接中");
268
-//                fragment.show(requireActivity().getSupportFragmentManager(), "CONNECT");
269
-//            });
270
-
271 270
             BlueDeviceInfo blueDeviceInfo = new BlueDeviceInfo(bluetoothDevice.getName(), bluetoothDevice.getAddress(), itemPosition.getConnectState());
272 271
             PrintUtil.setConnectedType(-1);
273 272
             int connectResult = PrintUtil.connectBluetoothPrinter(blueDeviceInfo.getDeviceHardwareAddress());
274 273
             Log.d("ble", "测试:连接结果 " + connectResult);
275 274
             result.success(connectResult);
276
-
277 275
         });
278 276
     }
279 277
 
280
-
278
+    void endBluetoothConnect(@NonNull MethodCall methodCall, @NonNull MethodChannel.Result result) {
279
+        PrintUtil.close();
280
+        result.success(0);
281
+    }
281 282
 
282 283
     private final BroadcastReceiver receiver = new BroadcastReceiver() {
283 284
 
284
-
285 285
         @SuppressLint("MissingPermission")
286 286
         @Override
287 287
         public void onReceive(Context context, Intent intent) {
@@ -314,20 +314,25 @@ public class BluetoothPlugin implements FlutterPlugin, MethodChannel.MethodCallH
314 314
                     if (supportBluetoothType && supportPrintName) {
315 315
 
316 316
                         Log.d("ble", "测试:打印机名称- " + deviceName + ",设备地址:" + deviceHardwareAddress + ",设备类型:" + device.getType() + ", 设备状态:"+deviceStatus);
317
-                        Log.d("ble", "sink:" + onReceiveSink + ":" + "onDiscoveryDeviceStreamHandler" +  (onDiscoveryDeviceStreamHandler != null) + "onDiscoveryDeviceStreamHandler.sink != null:" + (onDiscoveryDeviceStreamHandler.sink));
317
+                        Log.d("ble",  ":" + "onDiscoveryDeviceStreamHandler" +  (onDiscoveryDeviceStreamHandler != null) + "onDiscoveryDeviceStreamHandler.sink != null:" + (onDiscoveryDeviceStreamHandler.sink));
318 318
                         if (onDiscoveryDeviceStreamHandler != null && onDiscoveryDeviceStreamHandler.sink != null) {
319 319
                             onDiscoveryDeviceStreamHandler.sink.success(deviceName+delimiterStr+deviceHardwareAddress+delimiterStr+deviceStatus);
320 320
                         }
321 321
                     }
322
-
323 322
                 }
324
-
325 323
             } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
326 324
                 Log.v("ble", "测试:开始搜索");
327
-//                bind.spinKit.setVisibility(View.VISIBLE);
325
+                Log.d("ble",  ":" + "onDeviceStateStreamHandler" +  (onDeviceStateStreamHandler != null) + "onDeviceStateStreamHandler.sink != null:" + (onDeviceStateStreamHandler.sink));
326
+                if (onDeviceStateStreamHandler != null && onDeviceStateStreamHandler.sink != null) {
327
+                    onDeviceStateStreamHandler.sink.success("scanStart");
328
+                }
328 329
             } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
329 330
                 Log.v("ble", "测试:搜索结束");
330 331
 //                bind.spinKit.setVisibility(View.GONE);
332
+                Log.d("ble",  ":" + "onDeviceStateStreamHandler" +  (onDeviceStateStreamHandler != null) + "onDeviceStateStreamHandler.sink != null:" + (onDeviceStateStreamHandler.sink));
333
+                if (onDeviceStateStreamHandler != null && onDeviceStateStreamHandler.sink != null) {
334
+                    onDeviceStateStreamHandler.sink.success("scanEnd");
335
+                }
331 336
             } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
332 337
                 int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
333 338
                 Log.d("ble", "测试:配对状态改变:0 " + state);
@@ -338,9 +343,10 @@ public class BluetoothPlugin implements FlutterPlugin, MethodChannel.MethodCallH
338 343
                     }
339 344
                 }
340 345
             } else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
341
-//                if (fragment != null) {
342
-//                    fragment.dismiss();
343
-//                }
346
+
347
+                if (onDeviceStateStreamHandler != null && onDeviceStateStreamHandler.sink != null) {
348
+                    onDeviceStateStreamHandler.sink.success("pairEnd");
349
+                }
344 350
             }
345 351
         }
346 352
     };
@@ -365,4 +371,22 @@ class OnDiscoveryDeviceStreamHandler implements EventChannel.StreamHandler {
365 371
         Log.e("zhousuhua","OnReceiveDataStreamHandler=== onCancel");
366 372
         sink = null;
367 373
     }
374
+}
375
+
376
+class OnDeviceStateStreamHandler implements EventChannel.StreamHandler {
377
+
378
+    public EventChannel.EventSink sink;
379
+
380
+    @Override
381
+    public void onListen(Object o, EventChannel.EventSink eventSink) {
382
+
383
+        Log.d("ble", "OnDeviceStateStreamHandler: onListen");
384
+        sink = eventSink;
385
+    }
386
+    @Override
387
+    public void onCancel(Object o) {
388
+
389
+        Log.e("zhousuhua","OnReceiveDataStreamHandler=== onCancel");
390
+        sink = null;
391
+    }
368 392
 }

+ 5 - 1
lib/page/home/home_page.dart

@@ -4,6 +4,8 @@ import 'package:flutter/material.dart';
4 4
 import 'package:lszlgl/base/base_state.dart';
5 5
 import 'package:lszlgl/page/sample_task/sample_task_list_tab_page.dart';
6 6
 
7
+import '../print/print_page.dart';
8
+
7 9
 /// 首页
8 10
 class HomePage extends StatefulWidget {
9 11
   const HomePage({Key? key}) : super(key: key);
@@ -21,7 +23,9 @@ class _HomePageState extends BaseState<HomePage> with AutomaticKeepAliveClientMi
21 23
   late List<ServiceModel> serviceList;
22 24
 
23 25
   void startSampleList(StepType type) async {
24
-    MyRouter.startSampleTaskList(SampleTaskListTabPageArgs(type: type));
26
+    var args = PrintPageArgs(count: 0);
27
+    await MyRouter.startPrint(args: args);
28
+    // MyRouter.startSampleTaskList(SampleTaskListTabPageArgs(type: type));
25 29
   }
26 30
 
27 31
   @override

+ 64 - 47
lib/page/print/connect_print_page.dart

@@ -1,7 +1,10 @@
1 1
 import 'package:flutter/material.dart';
2 2
 import 'package:flutter/services.dart';
3 3
 import 'package:lszlgl/base/base_lifecycle_state.dart';
4
+import 'package:lszlgl/main.dart';
4 5
 import 'package:lszlgl/service/print_service.dart';
6
+import 'package:lszlgl/widget/loading_widget.dart';
7
+import 'package:lszlgl/widget/page_widget.dart';
5 8
 import 'package:signature/signature.dart';
6 9
 import 'package:lszlgl/widget/button.dart';
7 10
 
@@ -33,18 +36,16 @@ class ConnectPrintPage extends StatefulWidget {
33 36
 }
34 37
 
35 38
 class _ConnectPrintPageState extends BaseLifecycleState<ConnectPrintPage> {
36
-  late int count;
37
-  late List<SignatureController> ctrlList;
38
-  late PageController pageCtrl;
39
-
40
-  final previousEnable = false.notifier<bool>();
41
-  final nextEnable = false.notifier<bool>();
42
-  final submitEnable = false.notifier<bool>();
43 39
 
44 40
   late List<ServiceModel> serviceList;
45 41
   late List<BlueDeviceInfo> deviceList;
46 42
   late List<String> deviceMacList;
47 43
 
44
+  late List<BlueDeviceInfo> connectedDeviceList;
45
+  late List<String> connectedDeviceMacList;
46
+
47
+  String scanDeviceState = '';
48
+
48 49
   @override
49 50
   void initState() {
50 51
     super.initState();
@@ -53,9 +54,11 @@ class _ConnectPrintPageState extends BaseLifecycleState<ConnectPrintPage> {
53 54
     ];
54 55
     deviceList = [];
55 56
     deviceMacList = [];
57
+    connectedDeviceList = [];
58
+    connectedDeviceMacList = [];
56 59
   }
57 60
 
58
-  /// 去连接
61
+  /// 去搜索
59 62
   Future<void> startScan() async {
60 63
 
61 64
     setState(() {
@@ -65,36 +68,53 @@ class _ConnectPrintPageState extends BaseLifecycleState<ConnectPrintPage> {
65 68
     await PrintService.startBluetoothDiscovery();
66 69
   }
67 70
 
68
-  /// 去打印
71
+  /// 去连接
69 72
   Future<void> startConnect(BlueDeviceInfo deviceInfo) async {
70 73
     if(deviceInfo.connectStateStr == '未配对') {
74
+      MyNavigator.showLoading(msg: '配对中...');
71 75
       await PrintService.startBluetoothPair(deviceInfo);
72 76
     } else if(deviceInfo.connectStateStr == '已配对') {
73
-      await PrintService.startBluetoothConnect(deviceInfo);
77
+      MyNavigator.showLoading(msg: '连接中...');
78
+      int connectResult =  await PrintService.startBluetoothConnect(deviceInfo);
79
+      if(connectResult == 0) { // 连接成功
80
+        MyNavigator.dismiss();
81
+        MyNavigator.showToast('连接成功');
82
+        deviceInfo.connectSuccess();
83
+        if(deviceMacList.contains(deviceInfo.deviceMac)) {
84
+          setState(() {
85
+            deviceMacList.removeWhere((element) => element == deviceInfo.deviceMac);
86
+            deviceList.removeWhere((element) => element.deviceMac == deviceInfo.deviceMac);
87
+          });
88
+        }
89
+        setState(() {
90
+          connectedDeviceMacList.add(deviceInfo.deviceMac);
91
+          connectedDeviceList.add(deviceInfo);
92
+        });
93
+      } else {
94
+        MyNavigator.dismiss();
95
+        MyNavigator.showToast('连接失败');
96
+      }
97
+    } else if(deviceInfo.connectStateStr == '断开') {
98
+      int connectResult =  await PrintService.endBluetoothConnect(deviceInfo);
99
+      if(connectResult == 0) {  // 断开成功
100
+        deviceInfo.disConnectSuccess();
101
+        if(connectedDeviceMacList.contains(deviceInfo.deviceMac)) {
102
+          setState(() {
103
+            connectedDeviceMacList.removeWhere((element) => element == deviceInfo.deviceMac);
104
+            connectedDeviceList.removeWhere((element) => element.deviceMac == deviceInfo.deviceMac);
105
+          });
106
+        }
107
+        setState(() {
108
+          deviceMacList.add(deviceInfo.deviceMac);
109
+          deviceList.add(deviceInfo);
110
+        });
111
+      }
74 112
     }
75 113
   }
76 114
 
77 115
   @override
78 116
   void onInit() {
79 117
 
80
-    // 创建签名列表
81
-    count = widget.args.count;
82
-    ctrlList = List.generate(
83
-      count,
84
-          (index) => SignatureController(
85
-        penStrokeWidth: 6,
86
-        penColor: Colors.black,
87
-        strokeJoin: StrokeJoin.round,
88
-        strokeCap: StrokeCap.round,
89
-      ),
90
-    ).toList();
91
-    pageCtrl = PageController();
92
-    if (count == 1) {
93
-      submitEnable.value = true;
94
-    } else {
95
-      nextEnable.value = true;
96
-    }
97
-
98 118
     BluetoothPlugin.instance.onReceiveDataStream.listen((deviceInfo) {
99 119
       if(deviceInfo != null) {
100 120
         if(deviceMacList.contains(deviceInfo.deviceMac)) {
@@ -110,17 +130,19 @@ class _ConnectPrintPageState extends BaseLifecycleState<ConnectPrintPage> {
110 130
       }
111 131
     });
112 132
 
133
+    BluetoothPlugin.instance.onDeviceStateStream.listen((deviceState) {
134
+      if(deviceState == DeviceState.pairEnd) {
135
+        MyNavigator.dismiss();
136
+      }
137
+      setState(() {
138
+        scanDeviceState = deviceState ?? "";
139
+      });
140
+    });
113 141
   }
114 142
 
115 143
   @override
116 144
   void onDestroy() {
117
-    SystemChrome.setPreferredOrientations([
118
-      DeviceOrientation.portraitUp,
119
-      DeviceOrientation.portraitDown,
120
-    ]);
121
-    for (var ctrl in ctrlList) {
122
-      ctrl.dispose();
123
-    }
145
+
124 146
   }
125 147
 
126 148
   @override
@@ -134,7 +156,12 @@ class _ConnectPrintPageState extends BaseLifecycleState<ConnectPrintPage> {
134 156
             serviceList.length,
135 157
                 (index) => buildServiceItem(serviceList[index]),
136 158
           ).toList(),
137
-
159
+          const Text('已连接打印机'),
160
+          ...List.generate(
161
+            connectedDeviceList.length,
162
+                (index) => buildDeviceItem(connectedDeviceList[index]),
163
+          ).toList(),
164
+          const Text('可用打印机'),
138 165
           ...List.generate(
139 166
             deviceList.length,
140 167
                 (index) => buildDeviceItem(deviceList[index]),
@@ -165,20 +192,10 @@ class _ConnectPrintPageState extends BaseLifecycleState<ConnectPrintPage> {
165 192
                 mainAxisSize: MainAxisSize.min,
166 193
                 children: [
167 194
                   Text(
168
-                    service.name,
195
+                    "${service.name}${scanDeviceState == DeviceState.scanStart ? "中..." : ""}",
169 196
                     textAlign: TextAlign.center,
170 197
                     style: const TextStyle(color: Color(0xFF333333), fontSize: 20, fontWeight: FontWeight.w500),
171 198
                   ),
172
-                  service.nameEn != null
173
-                      ? Padding(
174
-                    padding: const EdgeInsets.only(top: 4),
175
-                    child: Text(
176
-                      service.nameEn!,
177
-                      textAlign: TextAlign.center,
178
-                      style: const TextStyle(color: Color(0xFF333333), fontSize: 12, fontWeight: FontWeight.w500),
179
-                    ),
180
-                  )
181
-                      : const SizedBox.shrink(),
182 199
                 ],
183 200
               ),
184 201
             ),

+ 46 - 7
lib/plugin/bluetooth_plugin.dart

@@ -15,6 +15,7 @@ class BluetoothPlugin {
15 15
    final String delimiterStr = "_NIMBOT_";
16 16
   final MethodChannel _channel = const MethodChannel("io.flutter.plugins/bluetooth/methods");
17 17
   final EventChannel _onReceiveDataStream = const EventChannel('io.flutter.plugins/bluetooth/onDiscoveryDevice');
18
+  final EventChannel _onDeviceStateStream = const EventChannel('io.flutter.plugins/bluetooth/onDeviceState');
18 19
 
19 20
 
20 21
   //是否打开蓝牙
@@ -46,7 +47,8 @@ class BluetoothPlugin {
46 47
     if (Platform.isIOS) {
47 48
       return 0;
48 49
     }
49
-    return _channel.invokeMethod('startBluetoothPair').then<int>((d) => d);
50
+    String deviceInfoStr = deviceInfo.deviceName+delimiterStr+deviceInfo.deviceMac+delimiterStr+deviceInfo.connectState;
51
+    return _channel.invokeMethod('startBluetoothPair', deviceInfoStr).then<int>((d) => d);
50 52
   }
51 53
 
52 54
   //开始连接
@@ -59,7 +61,18 @@ class BluetoothPlugin {
59 61
     return _channel.invokeMethod('startBluetoothConnect', deviceInfoStr).then<int>((d) => d);
60 62
   }
61 63
 
62
-  //开始连接
64
+  //断开连接
65
+  Future<int> endBluetoothConnect(BlueDeviceInfo deviceInfo) async {
66
+
67
+    if (Platform.isIOS) {
68
+      return 0;
69
+    }
70
+    String deviceInfoStr = deviceInfo.deviceName+delimiterStr+deviceInfo.deviceMac+delimiterStr+deviceInfo.connectState;
71
+    return _channel.invokeMethod('endBluetoothConnect', deviceInfoStr).then<int>((d) => d);
72
+  }
73
+
74
+
75
+  //开始打印
63 76
   Future<int> startBluetoothPrint(BlueDeviceInfo deviceInfo) async {
64 77
 
65 78
     if (Platform.isIOS) {
@@ -72,6 +85,8 @@ class BluetoothPlugin {
72 85
 
73 86
 
74 87
 
88
+
89
+
75 90
   /// 接收数据监听
76 91
   Stream<BlueDeviceInfo?> get onReceiveDataStream async* {
77 92
 
@@ -90,10 +105,28 @@ class BluetoothPlugin {
90 105
     });
91 106
   }
92 107
 
108
+  /// 接收数据监听
109
+  Stream<String?> get onDeviceStateStream async* {
110
+
111
+    yield* _onDeviceStateStream
112
+        .receiveBroadcastStream()
113
+        .map((buffer) {
93 114
 
115
+      return buffer.toString();
116
+    });
117
+  }
94 118
 }
95 119
 
96 120
 
121
+class DeviceState {
122
+
123
+  static String scanStart = "scanStart";
124
+
125
+  static String scanEnd = "scanEnd";
126
+
127
+  static String pairEnd = "pairEnd";
128
+}
129
+
97 130
 class BlueDeviceInfo {
98 131
 
99 132
   String deviceName;
@@ -104,13 +137,8 @@ class BlueDeviceInfo {
104 137
 
105 138
   BlueDeviceInfo({required this.deviceName, required this.deviceMac, required this.connectState});
106 139
 
107
-
108 140
   String get connectStateStr {
109 141
 
110
-    if(_connectStateStr != null) {
111
-     return _connectStateStr!;
112
-    }
113
-
114 142
     if(connectState == '10') {
115 143
       _connectStateStr = "未配对";
116 144
     }
@@ -120,9 +148,20 @@ class BlueDeviceInfo {
120 148
     if(connectState == '12') {
121 149
       _connectStateStr = "已配对";
122 150
     }
151
+    if(connectState == '13') {
152
+      _connectStateStr = "断开";
153
+    }
123 154
     return _connectStateStr ?? "未知";
124 155
   }
125 156
 
157
+  void connectSuccess() {
158
+    connectState = '13';
159
+  }
160
+
161
+  void disConnectSuccess() {
162
+    connectState = '12';
163
+  }
164
+
126 165
   @override
127 166
   String toString() {
128 167
     return {'deviceName:': deviceName, "mac:": deviceMac, "state:": connectState}.toString();

+ 10 - 0
lib/service/print_service.dart

@@ -91,6 +91,16 @@ class PrintService {
91 91
     }
92 92
   }
93 93
 
94
+  //断开连接
95
+  static Future<int> endBluetoothConnect(BlueDeviceInfo deviceInfo) async {
96
+
97
+    if(await canExecAction()) {
98
+      return await BluetoothPlugin.instance.endBluetoothConnect(deviceInfo);
99
+    } else {
100
+      return 0;
101
+    }
102
+  }
103
+
94 104
   //开始打印
95 105
   static Future<int> startBluetoothPrint(BlueDeviceInfo deviceInfo) async {
96 106