fake_bluetooth_platform.dart 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import 'dart:async';
  2. import 'package:flutter_blue_plus/flutter_blue_plus.dart';
  3. import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart';
  4. final class FakeBluetoothPlatform extends FlutterBluePlusPlatform {
  5. final _connections = StreamController<BmConnectionStateResponse>.broadcast();
  6. final _services = StreamController<BmDiscoverServicesResult>.broadcast();
  7. final _received = StreamController<BmCharacteristicData>.broadcast();
  8. final _written = StreamController<BmCharacteristicData>.broadcast();
  9. final _mtus = StreamController<BmMtuChangedResponse>.broadcast();
  10. final _descriptors = StreamController<BmDescriptorData>.broadcast();
  11. final _scans = StreamController<BmScanResponse>.broadcast();
  12. final writes = <List<int>>[];
  13. final connected = <DeviceIdentifier>{};
  14. final serviceUuid = Guid('0000ffe0-0000-1000-8000-00805f9b34fb');
  15. final characteristicUuid = Guid('0000ffe1-0000-1000-8000-00805f9b34fb');
  16. bool failDiscovery = false;
  17. bool failNotifications = false;
  18. bool failWrites = false;
  19. int? failWriteAt;
  20. bool hasCharacteristic = true;
  21. bool writable = true;
  22. bool writableWithoutResponse = false;
  23. bool notifiable = true;
  24. bool respondToIdentity = true;
  25. Completer<void>? discoveryGate;
  26. Completer<void>? writeGate;
  27. int mtu = 23;
  28. int _nextId = 0;
  29. int scanStarts = 0;
  30. int scanStops = 0;
  31. int connectionAttempts = 0;
  32. BluetoothDevice newDevice() => BluetoothDevice.fromId('review-${_nextId++}');
  33. void reset() {
  34. writes.clear();
  35. failDiscovery = false;
  36. failNotifications = false;
  37. failWrites = false;
  38. failWriteAt = null;
  39. hasCharacteristic = true;
  40. writable = true;
  41. writableWithoutResponse = false;
  42. notifiable = true;
  43. respondToIdentity = true;
  44. discoveryGate = null;
  45. writeGate = null;
  46. mtu = 23;
  47. scanStarts = 0;
  48. scanStops = 0;
  49. connectionAttempts = 0;
  50. }
  51. @override
  52. Stream<BmConnectionStateResponse> get onConnectionStateChanged =>
  53. _connections.stream;
  54. @override
  55. Stream<BmDiscoverServicesResult> get onDiscoveredServices => _services.stream;
  56. @override
  57. Stream<BmCharacteristicData> get onCharacteristicReceived => _received.stream;
  58. @override
  59. Stream<BmCharacteristicData> get onCharacteristicWritten => _written.stream;
  60. @override
  61. Stream<BmMtuChangedResponse> get onMtuChanged => _mtus.stream;
  62. @override
  63. Stream<BmDescriptorData> get onDescriptorWritten => _descriptors.stream;
  64. @override
  65. Stream<BmScanResponse> get onScanResponse => _scans.stream;
  66. @override
  67. Future<bool> startScan(BmScanSettings request) async {
  68. scanStarts++;
  69. return true;
  70. }
  71. @override
  72. Future<bool> stopScan(BmStopScanRequest request) async {
  73. scanStops++;
  74. return true;
  75. }
  76. @override
  77. Future<BmBluetoothAdapterState> getAdapterState(
  78. BmBluetoothAdapterStateRequest request,
  79. ) async => BmBluetoothAdapterState(adapterState: BmAdapterStateEnum.on);
  80. void _connection(DeviceIdentifier id, BmConnectionStateEnum state) {
  81. _connections.add(
  82. BmConnectionStateResponse(
  83. remoteId: id,
  84. connectionState: state,
  85. disconnectReasonCode: null,
  86. disconnectReasonString: null,
  87. ),
  88. );
  89. }
  90. @override
  91. Future<bool> connect(BmConnectRequest request) async {
  92. connectionAttempts++;
  93. connected.add(request.remoteId);
  94. _connection(request.remoteId, BmConnectionStateEnum.connected);
  95. return true;
  96. }
  97. @override
  98. Future<bool> disconnect(BmDisconnectRequest request) async {
  99. final changed = connected.remove(request.remoteId);
  100. if (changed) {
  101. _connection(request.remoteId, BmConnectionStateEnum.disconnected);
  102. }
  103. return changed;
  104. }
  105. @override
  106. Future<bool> requestMtu(BmMtuChangeRequest request) async {
  107. _mtus.add(
  108. BmMtuChangedResponse(
  109. remoteId: request.remoteId,
  110. mtu: mtu,
  111. success: true,
  112. errorCode: 0,
  113. errorString: '',
  114. ),
  115. );
  116. return true;
  117. }
  118. @override
  119. Future<bool> discoverServices(BmDiscoverServicesRequest request) async {
  120. if (failDiscovery) throw StateError('Discovery failed');
  121. final result = BmDiscoverServicesResult(
  122. remoteId: request.remoteId,
  123. services: [
  124. BmBluetoothService(
  125. remoteId: request.remoteId,
  126. primaryServiceUuid: null,
  127. serviceUuid: serviceUuid,
  128. characteristics: [
  129. if (hasCharacteristic)
  130. BmBluetoothCharacteristic(
  131. remoteId: request.remoteId,
  132. primaryServiceUuid: null,
  133. serviceUuid: serviceUuid,
  134. characteristicUuid: characteristicUuid,
  135. instanceId: 0,
  136. descriptors: [],
  137. properties: BmCharacteristicProperties(
  138. broadcast: false,
  139. read: false,
  140. writeWithoutResponse: writableWithoutResponse,
  141. write: writable,
  142. notify: notifiable,
  143. indicate: false,
  144. authenticatedSignedWrites: false,
  145. extendedProperties: false,
  146. notifyEncryptionRequired: false,
  147. indicateEncryptionRequired: false,
  148. ),
  149. ),
  150. ],
  151. ),
  152. ],
  153. success: true,
  154. errorCode: 0,
  155. errorString: '',
  156. );
  157. final gate = discoveryGate;
  158. if (gate == null) {
  159. _services.add(result);
  160. } else {
  161. unawaited(gate.future.then((_) => _services.add(result)));
  162. }
  163. return true;
  164. }
  165. @override
  166. Future<bool> setNotifyValue(BmSetNotifyValueRequest request) async {
  167. if (failNotifications) throw StateError('Notification setup failed');
  168. return false;
  169. }
  170. @override
  171. Future<bool> writeCharacteristic(BmWriteCharacteristicRequest request) async {
  172. await writeGate?.future;
  173. if (failWrites || writes.length == failWriteAt) {
  174. throw StateError('Write failed');
  175. }
  176. if (request.value.length > mtu - 3) {
  177. throw StateError('Write exceeds MTU payload');
  178. }
  179. writes.add(List<int>.from(request.value));
  180. if (respondToIdentity &&
  181. String.fromCharCodes(request.value).contains('cmd uname')) {
  182. notify(
  183. BluetoothDevice.fromId(request.remoteId.str),
  184. 'cmd uname meCoffee V10 OK\n',
  185. );
  186. }
  187. _written.add(
  188. BmCharacteristicData(
  189. remoteId: request.remoteId,
  190. primaryServiceUuid: request.primaryServiceUuid,
  191. serviceUuid: request.serviceUuid,
  192. characteristicUuid: request.characteristicUuid,
  193. instanceId: request.instanceId,
  194. value: request.value,
  195. success: true,
  196. errorCode: 0,
  197. errorString: '',
  198. ),
  199. );
  200. return true;
  201. }
  202. void notify(BluetoothDevice device, String message) {
  203. _received.add(
  204. BmCharacteristicData(
  205. remoteId: device.remoteId,
  206. primaryServiceUuid: null,
  207. serviceUuid: serviceUuid,
  208. characteristicUuid: characteristicUuid,
  209. instanceId: 0,
  210. value: message.codeUnits,
  211. success: true,
  212. errorCode: 0,
  213. errorString: '',
  214. ),
  215. );
  216. }
  217. }