Browse Source

fix: error handler, connection logic

Raihan Rizal 5 months ago
parent
commit
39a97e8bdb

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

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

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

13
 import io.flutter.plugin.common.MethodChannel;
13
 import io.flutter.plugin.common.MethodChannel;
14
 
14
 
15
 public class BluetoothConnectionHandler {
15
 public class BluetoothConnectionHandler {
16
-    String macAddress;
17
 
16
 
18
     public void handle(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
17
     public void handle(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
19
 
18
 
25
                     String connectionInfo = BluetoothConnectionHolder.connection.getSimpleConnectionName();
24
                     String connectionInfo = BluetoothConnectionHolder.connection.getSimpleConnectionName();
26
                     String currentConnectionMacAddress = connectionInfo.substring(0, 17);
25
                     String currentConnectionMacAddress = connectionInfo.substring(0, 17);
27
 
26
 
28
-                    if (currentConnectionMacAddress != macAddressArgument) {
27
+                    if (!currentConnectionMacAddress.equals(macAddressArgument)) {
29
                         closeAndReopenConnection(result, macAddressArgument);
28
                         closeAndReopenConnection(result, macAddressArgument);
30
 
29
 
30
+                    } else {
31
+                        openConnection(result);
32
+
31
                     }
33
                     }
34
+
32
                     break;
35
                     break;
33
                 }
36
                 }
34
 
37
 
92
         new Thread(new Runnable() {
95
         new Thread(new Runnable() {
93
             @Override
96
             @Override
94
             public void run() {
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
         }).start();
117
         }).start();
103
     }
118
     }
108
             public void run() {
123
             public void run() {
109
                 try {
124
                 try {
110
                     BluetoothConnectionHolder.connection.close();
125
                     BluetoothConnectionHolder.connection.close();
126
+                    BluetoothConnectionHolder.connection = null;
111
                     result.success(null);
127
                     result.success(null);
112
                 } catch (ConnectionException e) {
128
                 } catch (ConnectionException e) {
113
                     Log.w("From Native (Android)", "something went wrong when closing connection");
129
                     Log.w("From Native (Android)", "something went wrong when closing connection");

+ 16 - 5
example/lib/main.dart

169
     setState(() {});
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
   @override
187
   @override
173
   Widget build(BuildContext context) {
188
   Widget build(BuildContext context) {
174
     return Scaffold(
189
     return Scaffold(
204
 
219
 
205
             ElevatedButton(
220
             ElevatedButton(
206
               child: Text('Check connection status'),
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
             SizedBox(height: 20),
224
             SizedBox(height: 20),
214
             
225
             

+ 23 - 10
lib/src/flutter_zsdk_method_channel.dart

7
 import 'package:flutter/services.dart';
7
 import 'package:flutter/services.dart';
8
 import 'package:flutter_blue_plus/flutter_blue_plus.dart';
8
 import 'package:flutter_blue_plus/flutter_blue_plus.dart';
9
 import 'package:flutter_zsdk/src/models/bluetooth_printer.dart';
9
 import 'package:flutter_zsdk/src/models/bluetooth_printer.dart';
10
+import 'package:flutter_zsdk/src/models/error_code.dart';
10
 import 'package:flutter_zsdk/src/models/flutter_zsdk_exception.dart';
11
 import 'package:flutter_zsdk/src/models/flutter_zsdk_exception.dart';
11
 import 'package:permission_handler/permission_handler.dart';
12
 import 'package:permission_handler/permission_handler.dart';
12
 
13
 
37
     //   print(event);
38
     //   print(event);
38
     // });
39
     // });
39
     if (!await FlutterBluePlus.isSupported) {
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
         try {
47
         try {
47
           await FlutterBluePlus.turnOn();
48
           await FlutterBluePlus.turnOn();
48
         } on FlutterBluePlusException catch (e) {
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
       } else {
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
         return bluetoothDiscoveryEventChannel.receiveBroadcastStream();
76
         return bluetoothDiscoveryEventChannel.receiveBroadcastStream();
76
       } else {
77
       } else {
77
         // throw Exception("Permissions not granted, please allow permission to discover bluetooth printers.");
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
     } else {
82
     } else {
91
 
92
 
92
     } on PlatformException catch (e) {
93
     } on PlatformException catch (e) {
93
       inspect(e);
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
     } catch (e) {
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
   @override
102
   @override
102
   Future<bool> isConnected() async {
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
   @override
115
   @override
109
   Future<void> closeConnection() async {
116
   Future<void> closeConnection() async {
110
     try {
117
     try {
111
       await methodChannel.invokeMethod('bluetoothCloseConnection');
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
     } catch (e) {
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
   Future<void> printZplOverBluetooth(String zplData) async {
128
   Future<void> printZplOverBluetooth(String zplData) async {
119
     try {
129
     try {
120
       await methodChannel.invokeMethod('printZplOverBluetooth', {'zplData': zplData});
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
     } catch (e) {
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

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