searcher.dart 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import 'dart:async';
  2. import 'package:vnote_device_plugin/event_type.dart';
  3. import 'consts/status.dart';
  4. import 'event_entrepot.dart';
  5. import 'models/device.dart';
  6. import 'vnote_device_plugin_platform_interface.dart';
  7. class DeviceSearcher {
  8. final String type;
  9. final failEvent = FEventHandler<String?>();
  10. final successEvent = FEventHandler<DeviceInfo>();
  11. final cancelEvent = FEventHandler<void>();
  12. late final EventListenUnit _eventUnit;
  13. final _statusHandlers = <int, void Function(Map<String, dynamic>? data)>{};
  14. Completer<void>? _startCompleter;
  15. Completer<void>? _stopCompleter;
  16. DeviceSearcher(this.type) {
  17. _initCallbackMap();
  18. _eventUnit = EventListenUnit(type, callback: _onEventCallback);
  19. }
  20. Future<void> start() async {
  21. EventEntrepot.instance.register(_eventUnit);
  22. _startCompleter = Completer<void>();
  23. await VnoteDevicePluginPlatform.instance.callAction(
  24. "SEARCH_START",
  25. {"TYPE": type},
  26. );
  27. await _startCompleter!.future;
  28. _startCompleter = null;
  29. }
  30. Future<void> stop() async {
  31. _stopCompleter = Completer<void>();
  32. await VnoteDevicePluginPlatform.instance.callAction(
  33. "SEARCH_STOP",
  34. {"TYPE": type},
  35. );
  36. await _stopCompleter!.future;
  37. _stopCompleter = null;
  38. EventEntrepot.instance.unregister(_eventUnit);
  39. }
  40. void _onEventCallback(int status, Map<String, dynamic> e) {
  41. final callback = _statusHandlers[status];
  42. callback?.call(e["DATA"]);
  43. }
  44. void _onStartCallback(Map<String, dynamic>? data) {
  45. _startCompleter?.complete();
  46. }
  47. void _onStopCallback(Map<String, dynamic>? data) {
  48. _stopCompleter?.complete();
  49. cancelEvent.emit(this, null);
  50. }
  51. void _onFoundCallback(Map<String, dynamic>? data) {
  52. // {"STATUS":104,"DATA":{"BLE_NAME":"IR Thermo","BLE_PRODUCT_NAME":"体温计(家测宝)","MAC":"44:A6:E5:16:62:33","MODEL":"DT-8836","TYPE":"temp"}}
  53. final device = DeviceInfo(
  54. mac: data!["MAC"],
  55. model: data["MODEL"],
  56. bleName: data["BLE_NAME"],
  57. productName: data["BLE_PRODUCT_NAME"],
  58. type: data["TYPE"],
  59. );
  60. successEvent.emit(this, device);
  61. }
  62. void _onNotFoundCallback(Map<String, dynamic>? data) {
  63. final message = data?["MESSAGE"] ?? "ERROR";
  64. failEvent.emit(this, message); // TODO:
  65. }
  66. void _initCallbackMap() {
  67. _statusHandlers[VDeviceSdkStatus.DEVICE_SEARCH_START] = _onStartCallback;
  68. _statusHandlers[VDeviceSdkStatus.DEVICE_SEARCH_STOP] = _onStopCallback;
  69. _statusHandlers[VDeviceSdkStatus.BLE_DEVICE_FOUND] = _onFoundCallback;
  70. _statusHandlers[VDeviceSdkStatus.BLE_DEVICE_NOT_FOUND] =
  71. _onNotFoundCallback;
  72. }
  73. }