fake_bluetooth_platform.dart 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. /// Answer each `cmd set <key> <value>` like the V10 firmware does.
  26. bool echoSettings = true;
  27. /// Reply for a key instead of the normal echo, e.g. `cmd set NOT OK`.
  28. final settingReplies = <String, String>{};
  29. String _writtenText = '';
  30. Completer<void>? discoveryGate;
  31. Completer<void>? writeGate;
  32. int mtu = 23;
  33. int _nextId = 0;
  34. int scanStarts = 0;
  35. int scanStops = 0;
  36. int connectionAttempts = 0;
  37. BluetoothDevice newDevice() => BluetoothDevice.fromId('review-${_nextId++}');
  38. void reset() {
  39. writes.clear();
  40. failDiscovery = false;
  41. failNotifications = false;
  42. failWrites = false;
  43. failWriteAt = null;
  44. hasCharacteristic = true;
  45. writable = true;
  46. writableWithoutResponse = false;
  47. notifiable = true;
  48. respondToIdentity = true;
  49. echoSettings = true;
  50. settingReplies.clear();
  51. _writtenText = '';
  52. discoveryGate = null;
  53. writeGate = null;
  54. mtu = 23;
  55. scanStarts = 0;
  56. scanStops = 0;
  57. connectionAttempts = 0;
  58. }
  59. @override
  60. Stream<BmConnectionStateResponse> get onConnectionStateChanged =>
  61. _connections.stream;
  62. @override
  63. Stream<BmDiscoverServicesResult> get onDiscoveredServices => _services.stream;
  64. @override
  65. Stream<BmCharacteristicData> get onCharacteristicReceived => _received.stream;
  66. @override
  67. Stream<BmCharacteristicData> get onCharacteristicWritten => _written.stream;
  68. @override
  69. Stream<BmMtuChangedResponse> get onMtuChanged => _mtus.stream;
  70. @override
  71. Stream<BmDescriptorData> get onDescriptorWritten => _descriptors.stream;
  72. @override
  73. Stream<BmScanResponse> get onScanResponse => _scans.stream;
  74. @override
  75. Future<bool> startScan(BmScanSettings request) async {
  76. scanStarts++;
  77. return true;
  78. }
  79. @override
  80. Future<bool> stopScan(BmStopScanRequest request) async {
  81. scanStops++;
  82. return true;
  83. }
  84. @override
  85. Future<BmBluetoothAdapterState> getAdapterState(
  86. BmBluetoothAdapterStateRequest request,
  87. ) async => BmBluetoothAdapterState(adapterState: BmAdapterStateEnum.on);
  88. void _connection(DeviceIdentifier id, BmConnectionStateEnum state) {
  89. _connections.add(
  90. BmConnectionStateResponse(
  91. remoteId: id,
  92. connectionState: state,
  93. disconnectReasonCode: null,
  94. disconnectReasonString: null,
  95. ),
  96. );
  97. }
  98. @override
  99. Future<bool> connect(BmConnectRequest request) async {
  100. connectionAttempts++;
  101. connected.add(request.remoteId);
  102. _connection(request.remoteId, BmConnectionStateEnum.connected);
  103. return true;
  104. }
  105. @override
  106. Future<bool> disconnect(BmDisconnectRequest request) async {
  107. final changed = connected.remove(request.remoteId);
  108. if (changed) {
  109. _connection(request.remoteId, BmConnectionStateEnum.disconnected);
  110. }
  111. return changed;
  112. }
  113. @override
  114. Future<bool> requestMtu(BmMtuChangeRequest request) async {
  115. _mtus.add(
  116. BmMtuChangedResponse(
  117. remoteId: request.remoteId,
  118. mtu: mtu,
  119. success: true,
  120. errorCode: 0,
  121. errorString: '',
  122. ),
  123. );
  124. return true;
  125. }
  126. @override
  127. Future<bool> discoverServices(BmDiscoverServicesRequest request) async {
  128. if (failDiscovery) throw StateError('Discovery failed');
  129. final result = BmDiscoverServicesResult(
  130. remoteId: request.remoteId,
  131. services: [
  132. BmBluetoothService(
  133. remoteId: request.remoteId,
  134. primaryServiceUuid: null,
  135. serviceUuid: serviceUuid,
  136. characteristics: [
  137. if (hasCharacteristic)
  138. BmBluetoothCharacteristic(
  139. remoteId: request.remoteId,
  140. primaryServiceUuid: null,
  141. serviceUuid: serviceUuid,
  142. characteristicUuid: characteristicUuid,
  143. instanceId: 0,
  144. descriptors: [],
  145. properties: BmCharacteristicProperties(
  146. broadcast: false,
  147. read: false,
  148. writeWithoutResponse: writableWithoutResponse,
  149. write: writable,
  150. notify: notifiable,
  151. indicate: false,
  152. authenticatedSignedWrites: false,
  153. extendedProperties: false,
  154. notifyEncryptionRequired: false,
  155. indicateEncryptionRequired: false,
  156. ),
  157. ),
  158. ],
  159. ),
  160. ],
  161. success: true,
  162. errorCode: 0,
  163. errorString: '',
  164. );
  165. final gate = discoveryGate;
  166. if (gate == null) {
  167. _services.add(result);
  168. } else {
  169. unawaited(gate.future.then((_) => _services.add(result)));
  170. }
  171. return true;
  172. }
  173. @override
  174. Future<bool> setNotifyValue(BmSetNotifyValueRequest request) async {
  175. if (failNotifications) throw StateError('Notification setup failed');
  176. return false;
  177. }
  178. @override
  179. Future<bool> writeCharacteristic(BmWriteCharacteristicRequest request) async {
  180. await writeGate?.future;
  181. if (failWrites || writes.length == failWriteAt) {
  182. throw StateError('Write failed');
  183. }
  184. if (request.value.length > mtu - 3) {
  185. throw StateError('Write exceeds MTU payload');
  186. }
  187. writes.add(List<int>.from(request.value));
  188. if (respondToIdentity &&
  189. String.fromCharCodes(request.value).contains('cmd uname')) {
  190. notify(
  191. BluetoothDevice.fromId(request.remoteId.str),
  192. 'cmd uname meCoffee V10 OK\n',
  193. );
  194. }
  195. _writtenText += String.fromCharCodes(request.value);
  196. while (_writtenText.contains('\n')) {
  197. final index = _writtenText.indexOf('\n');
  198. final line = _writtenText.substring(0, index).trim();
  199. _writtenText = _writtenText.substring(index + 1);
  200. final match = RegExp(r'^cmd set (\S+) (\S+)$').firstMatch(line);
  201. if (echoSettings && match != null) {
  202. notify(
  203. BluetoothDevice.fromId(request.remoteId.str),
  204. '${settingReplies[match[1]] ?? 'cmd set s_${match[1]} ${match[2]} OK'}\n',
  205. );
  206. }
  207. }
  208. _written.add(
  209. BmCharacteristicData(
  210. remoteId: request.remoteId,
  211. primaryServiceUuid: request.primaryServiceUuid,
  212. serviceUuid: request.serviceUuid,
  213. characteristicUuid: request.characteristicUuid,
  214. instanceId: request.instanceId,
  215. value: request.value,
  216. success: true,
  217. errorCode: 0,
  218. errorString: '',
  219. ),
  220. );
  221. return true;
  222. }
  223. void notify(BluetoothDevice device, String message) {
  224. _received.add(
  225. BmCharacteristicData(
  226. remoteId: device.remoteId,
  227. primaryServiceUuid: null,
  228. serviceUuid: serviceUuid,
  229. characteristicUuid: characteristicUuid,
  230. instanceId: 0,
  231. value: message.codeUnits,
  232. success: true,
  233. errorCode: 0,
  234. errorString: '',
  235. ),
  236. );
  237. }
  238. }