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(); final successEvent = FEventHandler(); final cancelEvent = FEventHandler(); late final EventListenUnit _eventUnit; final _statusHandlers = ? data)>{}; Completer? _startCompleter; Completer? _stopCompleter; DeviceSearcher(this.type) { _initCallbackMap(); _eventUnit = EventListenUnit(type, callback: _onEventCallback); } Future start() async { EventEntrepot.instance.register(_eventUnit); _startCompleter = Completer(); await VnoteDevicePluginPlatform.instance.callAction( "SEARCH_START", {"TYPE": type}, ); await _startCompleter!.future; _startCompleter = null; } Future stop() async { _stopCompleter = Completer(); await VnoteDevicePluginPlatform.instance.callAction( "SEARCH_STOP", {"TYPE": type}, ); await _stopCompleter!.future; _stopCompleter = null; EventEntrepot.instance.unregister(_eventUnit); } void _onEventCallback(int status, Map e) { final callback = _statusHandlers[status]; callback?.call(e["DATA"]); } void _onStartCallback(Map? data) { _startCompleter?.complete(); } void _onStopCallback(Map? data) { _stopCompleter?.complete(); cancelEvent.emit(this, null); } void _onFoundCallback(Map? 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? 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; } }