瀏覽代碼

fix: error handler, connection logic

Raihan Rizal 5 月之前
父節點
當前提交
39a97e8bdb

+ 0 - 3
android/src/main/java/id/kalanusa/flutter_zsdk/FlutterZsdkPlugin.java

@@ -45,10 +45,7 @@ public class FlutterZsdkPlugin implements FlutterPlugin, MethodCallHandler, Acti
45 45
   private MethodChannel channel;
46 46
   private Context context;
47 47
   private Activity activity;
48
-  private ArrayList<BluetoothPrinter> discoveredPrinterList = new ArrayList<BluetoothPrinter>();
49 48
   public static final String bluetoothDiscoveryEventChannel = "id.kalanusa.flutter_zsdk.channel_events/bluetooth_discovery";
50
-  private EventChannel.EventSink attachEvent;
51
-  private Handler handler;
52 49
   private DartExecutor dartExecutor;
53 50
   private BinaryMessenger binaryMessenger;
54 51
 

+ 22 - 6
android/src/main/java/id/kalanusa/flutter_zsdk/bluetoothconnectionhandler/BluetoothConnectionHandler.java

@@ -13,7 +13,6 @@ import io.flutter.plugin.common.MethodCall;
13 13
 import io.flutter.plugin.common.MethodChannel;
14 14
 
15 15
 public class BluetoothConnectionHandler {
16
-    String macAddress;
17 16
 
18 17
     public void handle(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
19 18
 
@@ -25,10 +24,14 @@ public class BluetoothConnectionHandler {
25 24
                     String connectionInfo = BluetoothConnectionHolder.connection.getSimpleConnectionName();
26 25
                     String currentConnectionMacAddress = connectionInfo.substring(0, 17);
27 26
 
28
-                    if (currentConnectionMacAddress != macAddressArgument) {
27
+                    if (!currentConnectionMacAddress.equals(macAddressArgument)) {
29 28
                         closeAndReopenConnection(result, macAddressArgument);
30 29
 
30
+                    } else {
31
+                        openConnection(result);
32
+
31 33
                     }
34
+
32 35
                     break;
33 36
                 }
34 37
 
@@ -92,12 +95,24 @@ public class BluetoothConnectionHandler {
92 95
         new Thread(new Runnable() {
93 96
             @Override
94 97
             public void run() {
95
-                BluetoothConnectionHolder.getSimpleConnectionName();
96
-                boolean isConnected = BluetoothConnectionHolder.connection.isConnected();
98
+//                BluetoothConnectionHolder.getSimpleConnectionName();
99
+                try {
100
+                    boolean isConnected = BluetoothConnectionHolder.connection.isConnected();
97 101
 
98
-                result.success(isConnected);
102
+                    result.success(isConnected);
99 103
 
100
-                Log.w("From Native (Android)", "isConnected: " + isConnected);
104
+                    Log.w("From Native (Android)", "isConnected: " + isConnected);
105
+                } catch (Exception e) {
106
+                    Log.w("From Native (Android)", "Cant get connection status");
107
+                    Log.w("From Native (Android)", e.getClass().toString());
108
+                    Log.w("From Native (Android)", "is exception nullPointerException: " + (e.getClass() == NullPointerException.class));
109
+
110
+                    if (e.getClass() == NullPointerException.class) {
111
+                        result.error("CONNECTION_HAS_NOT_BEEN_ESTABLISHED", "Cant get connection status, establish connection first", e.getCause());
112
+                    } else {
113
+                        result.error("CHECK_CONNECTION_ERROR", "Cant get connection status", e.getMessage());
114
+                    }
115
+                }
101 116
             }
102 117
         }).start();
103 118
     }
@@ -108,6 +123,7 @@ public class BluetoothConnectionHandler {
108 123
             public void run() {
109 124
                 try {
110 125
                     BluetoothConnectionHolder.connection.close();
126
+                    BluetoothConnectionHolder.connection = null;
111 127
                     result.success(null);
112 128
                 } catch (ConnectionException e) {
113 129
                     Log.w("From Native (Android)", "something went wrong when closing connection");

+ 16 - 5
example/lib/main.dart

@@ -169,6 +169,21 @@ class _MyAppState extends State<MyApp> {
169 169
     setState(() {});
170 170
   }
171 171
 
172
+  Future<void> checkConnectionStatus() async {
173
+    print('invoked checkConnectionStatus from dart');
174
+    try{
175
+      bool isConnected = await _flutterZsdkPlugin.isConnected();
176
+              
177
+      print('isConnected from dart: $isConnected');
178
+    } on FlutterZsdkException catch (e) {
179
+      inspect(e);
180
+      showSnackBar(e.message.toString());
181
+    } catch (e) {
182
+      inspect(e);
183
+      showSnackBar('Unexpected error while checking connection status');
184
+    }
185
+  }
186
+
172 187
   @override
173 188
   Widget build(BuildContext context) {
174 189
     return Scaffold(
@@ -204,11 +219,7 @@ class _MyAppState extends State<MyApp> {
204 219
 
205 220
             ElevatedButton(
206 221
               child: Text('Check connection status'),
207
-              onPressed: () async {
208
-                bool isConnected =await _flutterZsdkPlugin.isConnected();
209
-              
210
-                print('isConnected from dart: $isConnected');
211
-              },
222
+              onPressed: checkConnectionStatus,
212 223
             ),
213 224
             SizedBox(height: 20),
214 225
             

+ 23 - 10
lib/src/flutter_zsdk_method_channel.dart

@@ -7,6 +7,7 @@ import 'package:flutter/foundation.dart';
7 7
 import 'package:flutter/services.dart';
8 8
 import 'package:flutter_blue_plus/flutter_blue_plus.dart';
9 9
 import 'package:flutter_zsdk/src/models/bluetooth_printer.dart';
10
+import 'package:flutter_zsdk/src/models/error_code.dart';
10 11
 import 'package:flutter_zsdk/src/models/flutter_zsdk_exception.dart';
11 12
 import 'package:permission_handler/permission_handler.dart';
12 13
 
@@ -37,7 +38,7 @@ class MethodChannelFlutterZsdk extends FlutterZsdkPlatform {
37 38
     //   print(event);
38 39
     // });
39 40
     if (!await FlutterBluePlus.isSupported) {
40
-      throw FlutterZsdkException("Bluetooth is not supported on this device.");
41
+      throw FlutterZsdkException(ErrorCode.bluetoothIsNotSupported, "Bluetooth is not supported on this device.");
41 42
     }
42 43
 
43 44
 
@@ -46,10 +47,10 @@ class MethodChannelFlutterZsdk extends FlutterZsdkPlatform {
46 47
         try {
47 48
           await FlutterBluePlus.turnOn();
48 49
         } on FlutterBluePlusException catch (e) {
49
-          throw FlutterZsdkException("Failed to turn on bluetooth: ${e.description}");
50
+          throw FlutterZsdkException(ErrorCode.turnOnBluetoothError, "Failed to turn on bluetooth: ${e.description}");
50 51
         }
51 52
       } else {
52
-        throw FlutterZsdkException("Bluetooth is not turned on on this device.");
53
+        throw FlutterZsdkException(ErrorCode.bluetoothDisabled, "Bluetooth is not turned on on this device.");
53 54
       }
54 55
     }
55 56
 
@@ -75,7 +76,7 @@ class MethodChannelFlutterZsdk extends FlutterZsdkPlatform {
75 76
         return bluetoothDiscoveryEventChannel.receiveBroadcastStream();
76 77
       } else {
77 78
         // throw Exception("Permissions not granted, please allow permission to discover bluetooth printers.");
78
-        throw FlutterZsdkException("Permissions not granted, please allow permission to discover bluetooth printers.");
79
+        throw FlutterZsdkException(ErrorCode.permissionNotGranted, "Permissions not granted, please allow permission to discover bluetooth printers.");
79 80
       }
80 81
 
81 82
     } else {
@@ -91,26 +92,35 @@ class MethodChannelFlutterZsdk extends FlutterZsdkPlatform {
91 92
 
92 93
     } on PlatformException catch (e) {
93 94
       inspect(e);
94
-      throw FlutterZsdkException("Failed to open connection to printer: ${e.details}");
95
+      throw FlutterZsdkException(e.code, "Failed to open connection to printer: ${e.details}");
95 96
 
96 97
     } catch (e) {
97
-      throw FlutterZsdkException("Failed to open connection to printer: $e");
98
+      throw FlutterZsdkException(ErrorCode.unexpectedError, "Message: $e");
98 99
     }
99 100
   }
100 101
 
101 102
   @override
102 103
   Future<bool> isConnected() async {
103
-    bool isConnected = await methodChannel.invokeMethod('isConnected');
104
+    try {
105
+      bool isConnected = await methodChannel.invokeMethod('isConnected');
106
+      return isConnected;
107
+    } on PlatformException catch (e) {
108
+      throw FlutterZsdkException(e.code, "Failed to check connection , message: ${e.details}");
109
+    } catch (e) {
110
+      throw FlutterZsdkException(ErrorCode.unexpectedError, "Message: $e");
111
+    }
104 112
 
105
-    return isConnected;
106 113
   }
107 114
 
108 115
   @override
109 116
   Future<void> closeConnection() async {
110 117
     try {
111 118
       await methodChannel.invokeMethod('bluetoothCloseConnection');
119
+    } on PlatformException catch (e) {
120
+      inspect(e);
121
+      throw FlutterZsdkException(e.code, "Failed to close connection, message: ${e.details}");
112 122
     } catch (e) {
113
-      throw FlutterZsdkException("Failed to close connection to printer: $e");
123
+      throw FlutterZsdkException(ErrorCode.unexpectedError, "Message: $e");
114 124
     }
115 125
   }
116 126
 
@@ -118,8 +128,11 @@ class MethodChannelFlutterZsdk extends FlutterZsdkPlatform {
118 128
   Future<void> printZplOverBluetooth(String zplData) async {
119 129
     try {
120 130
       await methodChannel.invokeMethod('printZplOverBluetooth', {'zplData': zplData});
131
+    } on PlatformException catch (e) {
132
+      inspect(e);
133
+      throw FlutterZsdkException(e.code, "Failed to print ZPL over Bluetooth, message: ${e.details}");
121 134
     } catch (e) {
122
-      throw FlutterZsdkException("Failed to print ZPL over Bluetooth: $e");
135
+      throw FlutterZsdkException(ErrorCode.unexpectedError, "Message: $e");
123 136
     }
124 137
   }
125 138
 }

+ 16 - 0
lib/src/models/error_code.dart

@@ -0,0 +1,16 @@
1
+class ErrorCode {
2
+  static const String permissionNotGranted = "PERMISSION_NOT_GRANTED";
3
+  static const String turnOnBluetoothError = "TURN_ON_BLUETOOTH_ERROR";
4
+  static const String bluetoothIsNotSupported = "BLUETOOTH_IS_NOT_SUPPORTED";
5
+  static const String bluetoothDisabled = "BLUETOOTH_DISABLED";
6
+
7
+  static const String discoveryError = "DISCOVERY_ERROR";
8
+  static const String openConnectionError = "OPEN_CONNECTION_ERROR";
9
+  static const String closeAndReopenConnectionError = "CLOSE_AND_REOPEN_CONNECTION_ERROR";
10
+  static const String connectionHasNotBeenEstablished = "CONNECTION_HAS_NOT_BEEN_ESTABLISHED";
11
+  static const String checkConnectionError = "CHECK_CONNECTION_ERROR";
12
+  static const String closeConnectionError = "CLOSE_CONNECTION_ERROR";
13
+  static const String writeError = "WRITE_ERROR";
14
+
15
+  static const String unexpectedError = "UNEXPECTED_ERROR";
16
+}

+ 2 - 1
lib/src/models/flutter_zsdk_exception.dart

@@ -1,7 +1,8 @@
1 1
 class FlutterZsdkException implements Exception {
2
+  String code;
2 3
   String message;
3 4
 
4
-  FlutterZsdkException(this.message);
5
+  FlutterZsdkException(this.code, this.message);
5 6
 
6 7
   @override
7 8
   String toString() {