event_entrepot.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. typedef EventListenUnitCallback = void Function(
  2. int status,
  3. Map<String, dynamic> e,
  4. );
  5. class EventListenUnit {
  6. final String type;
  7. final String? model;
  8. final List<int>? acceptStatus;
  9. final int? maxStatus;
  10. final int? minStatus;
  11. final EventListenUnitCallback callback;
  12. EventListenUnit(
  13. this.type, {
  14. required this.callback,
  15. this.model,
  16. this.acceptStatus,
  17. this.minStatus,
  18. this.maxStatus,
  19. });
  20. @override
  21. String toString() {
  22. if (model == null || model?.isEmpty == true) {
  23. return type;
  24. }
  25. return "$type|$model";
  26. }
  27. }
  28. class EventEntrepot {
  29. static EventEntrepot? _instance;
  30. final _listenMap = <String, EventListenUnit>{};
  31. EventEntrepot._();
  32. static EventEntrepot get instance {
  33. _instance ??= EventEntrepot._();
  34. return _instance!;
  35. }
  36. void register(EventListenUnit unit) {
  37. final key = unit.toString();
  38. _listenMap[key] = unit;
  39. }
  40. void unregister(EventListenUnit unit) {
  41. final key = unit.toString();
  42. _listenMap.remove(key);
  43. }
  44. void receiveEvent(Map<String, dynamic> event) {
  45. final int status = event["STATUS"];
  46. for (final unit in _listenMap.values) {
  47. unit.callback.call(status, event);
  48. }
  49. return;
  50. // TODO:
  51. EventListenUnit? unit;
  52. Map<String, dynamic>? data;
  53. if (event.containsKey("DATAS")) {
  54. data = event["DATAS"];
  55. unit = _findUnit(event);
  56. } else {
  57. data = event["DATA"];
  58. unit = _findUnit(data);
  59. }
  60. if (data == null) {
  61. unit = _listenMap['temp'];
  62. unit?.callback.call(status, event);
  63. return; // TODO:
  64. }
  65. if (unit != null) {
  66. bool isAccept = true;
  67. if (unit.acceptStatus != null) {
  68. isAccept = unit.acceptStatus!.contains(status);
  69. } else {
  70. if (unit.minStatus != null && unit.minStatus! > status) {
  71. isAccept = false;
  72. }
  73. if (unit.maxStatus != null && unit.maxStatus! < status) {
  74. isAccept = false;
  75. }
  76. }
  77. if (isAccept) {
  78. unit.callback.call(status, data);
  79. }
  80. }
  81. }
  82. EventListenUnit? _findUnit(Map<String, dynamic>? data) {
  83. if (data == null) return null;
  84. if (data.containsKey("TYPE")) {
  85. final type = data["TYPE"];
  86. if (data.containsKey("MODEL")) {
  87. final model = data["MODEL"];
  88. try {
  89. final unit = _listenMap["$type|$model"];
  90. return unit ?? _listenMap[type];
  91. } catch (e) {
  92. print(e);
  93. }
  94. } else {
  95. return _listenMap[type];
  96. }
  97. }
  98. return null;
  99. }
  100. }