mobile_scanner_controller.dart
6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'objects/barcode_utility.dart';
/// The facing of a camera.
enum CameraFacing {
/// Front facing camera.
front,
/// Back facing camera.
back,
}
enum MobileScannerState { undetermined, authorized, denied }
/// The state of torch.
enum TorchState {
/// Torch is off.
off,
/// Torch is on.
on,
}
// enum AnalyzeMode { none, barcode }
class MobileScannerController {
MethodChannel methodChannel =
const MethodChannel('dev.steenbakker.mobile_scanner/scanner/method');
EventChannel eventChannel =
const EventChannel('dev.steenbakker.mobile_scanner/scanner/event');
int? _controllerHashcode;
StreamSubscription? events;
final ValueNotifier<MobileScannerArguments?> args = ValueNotifier(null);
final ValueNotifier<TorchState> torchState = ValueNotifier(TorchState.off);
late final ValueNotifier<CameraFacing> cameraFacingState;
final Ratio? ratio;
final bool? torchEnabled;
CameraFacing facing;
bool hasTorch = false;
late StreamController<Barcode> barcodesController;
Stream<Barcode> get barcodes => barcodesController.stream;
MobileScannerController(
{this.facing = CameraFacing.back, this.ratio, this.torchEnabled}) {
// In case a new instance is created before calling dispose()
if (_controllerHashcode != null) {
stop();
}
_controllerHashcode = hashCode;
cameraFacingState = ValueNotifier(facing);
// Sets analyze mode and barcode stream
barcodesController = StreamController.broadcast(
// onListen: () => setAnalyzeMode(AnalyzeMode.barcode.index),
// onCancel: () => setAnalyzeMode(AnalyzeMode.none.index),
);
start();
// Listen to events from the platform specific code
events = eventChannel
.receiveBroadcastStream()
.listen((data) => handleEvent(data));
}
void handleEvent(Map<dynamic, dynamic> event) {
final name = event['name'];
final data = event['data'];
switch (name) {
case 'torchState':
final state = TorchState.values[data];
torchState.value = state;
break;
case 'barcode':
final barcode = Barcode.fromNative(data);
barcodesController.add(barcode);
break;
case 'barcodeMac':
barcodesController.add(Barcode(rawValue: data['payload']));
break;
default:
throw UnimplementedError();
}
}
// TODO: Add more analyzers like text analyzer
// void setAnalyzeMode(int mode) {
// if (hashCode != _controllerHashcode) {
// return;
// }
// methodChannel.invokeMethod('analyze', mode);
// }
// List<BarcodeFormats>? formats = _defaultBarcodeFormats,
bool isStarting = false;
/// Start barcode scanning. This will first check if the required permissions
/// are set.
Future<void> start() async {
ensure('startAsync');
if (isStarting) {
throw Exception('mobile_scanner: Called start() while already starting.');
}
isStarting = true;
// setAnalyzeMode(AnalyzeMode.barcode.index);
// Check authorization status
MobileScannerState state =
MobileScannerState.values[await methodChannel.invokeMethod('state')];
switch (state) {
case MobileScannerState.undetermined:
final bool result = await methodChannel.invokeMethod('request');
state =
result ? MobileScannerState.authorized : MobileScannerState.denied;
break;
case MobileScannerState.denied:
isStarting = false;
throw PlatformException(code: 'NO ACCESS');
case MobileScannerState.authorized:
break;
}
cameraFacingState.value = facing;
// Set the starting arguments for the camera
Map arguments = {};
arguments['facing'] = facing.index;
if (ratio != null) arguments['ratio'] = ratio;
if (torchEnabled != null) arguments['torch'] = torchEnabled;
// Start the camera with arguments
Map<String, dynamic>? startResult = {};
try {
startResult = await methodChannel.invokeMapMethod<String, dynamic>(
'start', arguments);
} on PlatformException catch (error) {
debugPrint('${error.code}: ${error.message}');
isStarting = false;
// setAnalyzeMode(AnalyzeMode.none.index);
return;
}
if (startResult == null) {
isStarting = false;
throw PlatformException(code: 'INITIALIZATION ERROR');
}
hasTorch = startResult['torchable'];
args.value = MobileScannerArguments(
textureId: startResult['textureId'],
size: toSize(startResult['size']),
hasTorch: hasTorch);
isStarting = false;
}
Future<void> stop() async {
try {
await methodChannel.invokeMethod('stop');
} on PlatformException catch (error) {
debugPrint('${error.code}: ${error.message}');
}
}
/// Switches the torch on or off.
///
/// Only works if torch is available.
Future<void> toggleTorch() async {
ensure('toggleTorch');
if (!hasTorch) {
debugPrint('Device has no torch/flash.');
return;
}
TorchState state =
torchState.value == TorchState.off ? TorchState.on : TorchState.off;
try {
await methodChannel.invokeMethod('torch', state.index);
} on PlatformException catch (error) {
debugPrint('${error.code}: ${error.message}');
}
}
/// Switches the torch on or off.
///
/// Only works if torch is available.
Future<void> switchCamera() async {
ensure('switchCamera');
try {
await methodChannel.invokeMethod('stop');
} on PlatformException catch (error) {
debugPrint(
'${error.code}: camera is stopped! Please start before switching camera.');
return;
}
facing =
facing == CameraFacing.back ? CameraFacing.front : CameraFacing.back;
await start();
}
/// Handles a local image file.
/// Returns true if a barcode or QR code is found.
/// Returns false if nothing is found.
///
/// [path] The path of the image on the devices
Future<bool> analyzeImage(String path) async {
return await methodChannel.invokeMethod('analyzeImage', path);
}
/// Disposes the MobileScannerController and closes all listeners.
void dispose() {
if (hashCode == _controllerHashcode) {
stop();
events?.cancel();
events = null;
_controllerHashcode = null;
}
barcodesController.close();
}
/// Checks if the MobileScannerController is bound to the correct MobileScanner object.
void ensure(String name) {
final message =
'MobileScannerController.$name called after MobileScannerController.dispose\n'
'MobileScannerController methods should not be used after calling dispose.';
assert(hashCode == _controllerHashcode, message);
}
}