mobile_scanner_controller.dart
5.34 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
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'mobile_scanner_arguments.dart';
import 'objects/barcode.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,
}
// /// A camera controller.
// abstract class CameraController {
// /// Arguments for [CameraView].
// ValueNotifier<CameraArgs?> get args;
//
// /// Torch state of the camera.
// ValueNotifier<TorchState> get torchState;
//
// /// A stream of barcodes.
// Stream<Barcode> get barcodes;
//
// /// Create a [CameraController].
// ///
// /// [facing] target facing used to select camera.
// ///
// /// [formats] the barcode formats for image analyzer.
// factory CameraController([CameraFacing facing = CameraFacing.back] ) =>
// _CameraController(facing);
//
// /// Start the camera asynchronously.
// Future<void> start();
//
// /// Switch the torch's state.
// void torch();
//
// /// Release the resources of the camera.
// void dispose();
// }
class MobileScannerController {
static const MethodChannel method =
MethodChannel('dev.steenbakker.mobile_scanner/scanner/method');
static const EventChannel event =
EventChannel('dev.steenbakker.mobile_scanner/scanner/event');
static const analyze_none = 0;
static const analyze_barcode = 1;
static int? id;
static StreamSubscription? subscription;
final CameraFacing facing;
final ValueNotifier<MobileScannerArguments?> args;
final ValueNotifier<TorchState> torchState;
bool torchable;
late StreamController<Barcode> barcodesController;
Stream<Barcode> get barcodes => barcodesController.stream;
MobileScannerController(BuildContext context, {required num width, required num height, this.facing = CameraFacing.back})
: args = ValueNotifier(null),
torchState = ValueNotifier(TorchState.off),
torchable = false {
// In case new instance before dispose.
if (id != null) {
stop();
}
id = hashCode;
// Create barcode stream controller.
barcodesController = StreamController.broadcast(
onListen: () => tryAnalyze(analyze_barcode),
onCancel: () => tryAnalyze(analyze_none),
);
final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
start(
width: (devicePixelRatio * width.toInt()).ceil(),
height: (devicePixelRatio * height.toInt()).ceil());
// Listen event handler.
subscription =
event.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;
default:
throw UnimplementedError();
}
}
void tryAnalyze(int mode) {
if (hashCode != id) {
return;
}
method.invokeMethod('analyze', mode);
}
Future<void> start({
int? width,
int? height,
// List<BarcodeFormats>? formats = _defaultBarcodeFormats,
}) async {
ensure('startAsync');
// Check authorization state.
MobileScannerState state = MobileScannerState.values[await method.invokeMethod('state')];
switch (state) {
case MobileScannerState.undetermined:
final bool result = await method.invokeMethod('request');
state = result ? MobileScannerState.authorized : MobileScannerState.denied;
break;
case MobileScannerState.authorized:
break;
case MobileScannerState.denied:
throw PlatformException(code: 'NO ACCESS');
}
debugPrint('TARGET RESOLUTION $width, $height');
// Start camera.
final answer =
await method.invokeMapMethod<String, dynamic>('start', {
'targetWidth': width,
'targetHeight': height,
'facing': facing.index
});
final textureId = answer?['textureId'];
final Size size = toSize(answer?['size']);
debugPrint('RECEIVED SIZE: ${size.width} ${size.height}');
if (width != null && height != null) {
args.value = MobileScannerArguments(textureId: textureId, size: size, wantedSize: Size(width.toDouble(), height.toDouble()));
} else {
args.value = MobileScannerArguments(textureId: textureId, size: size);
}
torchable = answer?['torchable'];
}
void torch() {
ensure('torch');
if (!torchable) return;
var state =
torchState.value == TorchState.off ? TorchState.on : TorchState.off;
method.invokeMethod('torch', state.index);
}
void dispose() {
if (hashCode == id) {
stop();
subscription?.cancel();
subscription = null;
id = null;
}
barcodesController.close();
}
void stop() => method.invokeMethod('stop');
void ensure(String name) {
final message =
'CameraController.$name called after CameraController.dispose\n'
'CameraController methods should not be used after calling dispose.';
assert(hashCode == id, message);
}
}