12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- import 'dart:async';
- import 'package:vnote_device_plugin/event_type.dart';
- import 'consts/status.dart';
- import 'event_entrepot.dart';
- import 'models/device.dart';
- import 'vnote_device_plugin_platform_interface.dart';
- class DeviceSearcher {
- final String type;
- final failEvent = FEventHandler<String?>();
- final successEvent = FEventHandler<DeviceInfo>();
- final cancelEvent = FEventHandler<void>();
- late final EventListenUnit _eventUnit;
- final _statusHandlers = <int, void Function(Map<String, dynamic>? data)>{};
- Completer<void>? _startCompleter;
- Completer<void>? _stopCompleter;
- DeviceSearcher(this.type) {
- _initCallbackMap();
- _eventUnit = EventListenUnit(type, callback: _onEventCallback);
- }
- Future<void> start() async {
- EventEntrepot.instance.register(_eventUnit);
- _startCompleter = Completer<void>();
- await VnoteDevicePluginPlatform.instance.callAction(
- "SEARCH_START",
- {"TYPE": type},
- );
- await _startCompleter!.future;
- _startCompleter = null;
- }
- Future<void> stop() async {
- _stopCompleter = Completer<void>();
- await VnoteDevicePluginPlatform.instance.callAction(
- "SEARCH_STOP",
- {"TYPE": type},
- );
- await _stopCompleter!.future;
- _stopCompleter = null;
- EventEntrepot.instance.unregister(_eventUnit);
- }
- void _onEventCallback(int status, Map<String, dynamic> e) {
- final callback = _statusHandlers[status];
- callback?.call(e["DATA"]);
- }
- void _onStartCallback(Map<String, dynamic>? data) {
- _startCompleter?.complete();
- }
- void _onStopCallback(Map<String, dynamic>? data) {
- _stopCompleter?.complete();
- cancelEvent.emit(this, null);
- }
- void _onFoundCallback(Map<String, dynamic>? data) {
- // {"STATUS":104,"DATA":{"BLE_NAME":"IR Thermo","BLE_PRODUCT_NAME":"体温计(家测宝)","MAC":"44:A6:E5:16:62:33","MODEL":"DT-8836","TYPE":"temp"}}
- final device = DeviceInfo(
- mac: data!["MAC"],
- model: data["MODEL"],
- bleName: data["BLE_NAME"],
- productName: data["BLE_PRODUCT_NAME"],
- type: data["TYPE"],
- );
- successEvent.emit(this, device);
- }
- void _onNotFoundCallback(Map<String, dynamic>? data) {
- final message = data?["MESSAGE"] ?? "ERROR";
- failEvent.emit(this, message); // TODO:
- }
- void _initCallbackMap() {
- _statusHandlers[VDeviceSdkStatus.DEVICE_SEARCH_START] = _onStartCallback;
- _statusHandlers[VDeviceSdkStatus.DEVICE_SEARCH_STOP] = _onStopCallback;
- _statusHandlers[VDeviceSdkStatus.BLE_DEVICE_FOUND] = _onFoundCallback;
- _statusHandlers[VDeviceSdkStatus.BLE_DEVICE_NOT_FOUND] =
- _onNotFoundCallback;
- }
- }
|