Masterarbeit Richard Stern. Flutter App, sich mit einem Bluetooth-Gerät verbindet und Berührungen auf einem Sensor visualisiert.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bluetoothBloc.dart 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:rxdart/rxdart.dart';
  4. import 'package:rxdart/subjects.dart';
  5. import 'package:flutter_blue/flutter_blue.dart';
  6. import 'package:touch_demonstrator/model/touchData.dart';
  7. import 'package:touch_demonstrator/model/buttonData.dart';
  8. import 'package:flutter_test/flutter_test.dart';
  9. class BluetoothBloc {
  10. FlutterBlue _flutterBlue = FlutterBlue.instance;
  11. /// Scanning
  12. StreamSubscription _scanSubscription;
  13. Map<DeviceIdentifier, ScanResult> scanResults = Map();
  14. /// State
  15. StreamSubscription _stateSubscription;
  16. final _state$ = BehaviorSubject<BluetoothState>();
  17. final _isScanning$ = PublishSubject<bool>();
  18. final _isConnected$ = BehaviorSubject<bool>();
  19. final _deviceFound$ = PublishSubject<Map<DeviceIdentifier, ScanResult>>();
  20. // final _touchMessage$ = BehaviorSubject<String>(seedValue: 'init');
  21. final _singleTouchMessage$ = BehaviorSubject<TouchData>();
  22. final _touchDataHistory$ = BehaviorSubject<List<TouchData>>();
  23. final _touchVisualise$ = BehaviorSubject<List<TouchData>>();
  24. final _buttonEnabledStatus$ = BehaviorSubject<List<bool>>();
  25. final _batteryValue$ = BehaviorSubject<int>();
  26. final _buttonVibration$ = PublishSubject<buttonsState>();
  27. final _slider$ = PublishSubject<int>();
  28. String touchMessage = "";
  29. /// Device
  30. BluetoothDevice device;
  31. /// Device specifications
  32. StreamSubscription deviceConnection;
  33. StreamSubscription deviceStateSubscription;
  34. Map<Guid, StreamSubscription> valueChangedSubscriptions = {};
  35. BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;
  36. // Stream Controllers
  37. final _scanController = StreamController<void>();
  38. final _stopController = StreamController<void>();
  39. final _connectController = StreamController<ScanResult>();
  40. final _disconnectController = StreamController<void>();
  41. //SINKS (into bloc)
  42. Sink<void> get scan => _scanController.sink;
  43. Sink<void> get stop => _stopController.sink;
  44. Sink<ScanResult> get connect => _connectController.sink;
  45. Sink<void> get disconnect => _disconnectController.sink;
  46. //STREAMS (output bloc)
  47. Stream<BluetoothState> get bluetoothState$ => _state$.stream;
  48. Stream<int> get batteryValue$ => _batteryValue$.stream;
  49. Stream<TouchData> get singleTouchMessage => _singleTouchMessage$.stream;
  50. Stream<List<TouchData>> get getTouchesToVisualise$ =>
  51. _touchVisualise$.stream; //->
  52. Stream<List<bool>> get buttonsState$ => _buttonEnabledStatus$.stream;
  53. Stream<buttonsState> get vibrationButton$ => _buttonVibration$.stream;
  54. Stream<int> get slider$ => _slider$.stream;
  55. Stream<List<TouchData>> get getHistory$ =>
  56. _touchDataHistory$.stream.debounce(Duration(milliseconds: 600)); //->
  57. Stream<bool> get isScanning$ => _isScanning$.stream;
  58. Stream<bool> get isConnected$ => _isConnected$.stream;
  59. Stream<Map<DeviceIdentifier, ScanResult>> get devicesFound$ =>
  60. _deviceFound$.stream.throttle(Duration(seconds: 2));
  61. static const xMax = 1200;
  62. String inputString = "";
  63. final history = List<TouchData>();
  64. static List<TouchData> _fingerTouches =
  65. List.generate(5, (index) => TouchData(5, index, 1200, 1200));
  66. static List<buttonsState> _buttonPressed = [
  67. buttonsState.released,
  68. buttonsState.released,
  69. buttonsState.released
  70. ];
  71. static List<bool> _buttonsState = [false, false, false];
  72. // Listen to
  73. BluetoothBloc() {
  74. print('init: Bluetooth BLOC');
  75. _flutterBlue.setLogLevel(LogLevel.warning);
  76. // Listen to BLoC inputs
  77. _flutterBlue.state.then((s) {
  78. _state$.add(s);
  79. });
  80. _stateSubscription = _flutterBlue.onStateChanged().listen((s) {
  81. _state$.add(s);
  82. if (s == BluetoothState.off) {
  83. _resetSensor();
  84. }
  85. });
  86. _scanController.stream.listen((void _) {
  87. _startScan();
  88. });
  89. _stopController.stream.listen((void _) => _stopScan);
  90. _connectController.stream
  91. .listen((ScanResult result) => _connect(result.device));
  92. _disconnectController.stream.listen((void _) {
  93. _disconnect();
  94. });
  95. _isConnected$.add(false);
  96. }
  97. void _startScan() {
  98. print('Bluetooth Bloc: start Bluetooth Scan');
  99. scanResults.clear();
  100. _isScanning$.add(true);
  101. _scanSubscription = _flutterBlue
  102. .scan(
  103. timeout: const Duration(seconds: 1),
  104. )
  105. .listen((scanResult) {
  106. // print('Local Name: ${scanResult.advertisementData.localName}');
  107. scanResults[scanResult.device.id] = scanResult;
  108. // print(scanResult.device.id);
  109. }, onDone: _stopScan);
  110. }
  111. void _stopScan() {
  112. /// Stops any ongoing Bluetooth Search
  113. print('BLOC: _stopScan()');
  114. _scanSubscription?.cancel();
  115. _scanSubscription = null;
  116. _findDevice("Touchpad Demonstrator");
  117. }
  118. void _disconnect() {
  119. /// Disconnects all Bluetooth connections
  120. // Remove all value changed listeners
  121. print('Bluetooth Bloc: disconnect');
  122. valueChangedSubscriptions.forEach((uuid, sub) => sub.cancel());
  123. valueChangedSubscriptions.clear();
  124. deviceStateSubscription?.cancel();
  125. deviceStateSubscription = null;
  126. deviceConnection?.cancel();
  127. deviceConnection = null;
  128. device = null;
  129. _resetSensor();
  130. }
  131. void _resetSensor() {
  132. /// Resets all visual components of the app to initial state
  133. _buttonsState = [false, false, false];
  134. _slider$.add(101);
  135. _buttonEnabledStatus$.add(_buttonsState);
  136. _isConnected$.add(false);
  137. _fingerTouches = [
  138. TouchData(5, 0, 1200, 1200),
  139. TouchData(5, 1, 1200, 1200),
  140. TouchData(5, 2, 1200, 1200),
  141. TouchData(5, 3, 1200, 1200),
  142. TouchData(5, 4, 1200, 1200),
  143. ];
  144. _touchVisualise$.add(_fingerTouches);
  145. history.clear();
  146. _touchDataHistory$.add(history);
  147. _batteryValue$.add(null);
  148. }
  149. _findDevice(String deviceNameSearched) {
  150. /// If one device found -> connect to it. If more are found -> Stream the results
  151. var devicesFound = 0;
  152. BluetoothDevice deviceFound;
  153. // const String touchDemonstratorName = "Touchpad Demonstrator";
  154. print("_findDevices()");
  155. scanResults.forEach((k, v) {
  156. if (v.advertisementData.localName.contains(deviceNameSearched)) {
  157. devicesFound++;
  158. deviceFound = v.device;
  159. }
  160. });
  161. print('$devicesFound devices Found');
  162. if (devicesFound == 1) {
  163. // Only one device found -> connect directly.
  164. _connect(deviceFound);
  165. // _deviceFound$.add(scanResults);
  166. } else if (devicesFound > 1) {
  167. // More than one device found.
  168. _deviceFound$.add(scanResults);
  169. } else if (devicesFound == 0) {
  170. // No device found.
  171. scanResults.clear();
  172. _deviceFound$.add(scanResults);
  173. }
  174. Future.delayed(const Duration(milliseconds: 700), () {
  175. _isScanning$.add(false);
  176. });
  177. }
  178. void _connect(BluetoothDevice d) async {
  179. /// Connects device to BluetoothDevice D and subscribes to it.
  180. print('_connect');
  181. device = d;
  182. deviceConnection = _flutterBlue
  183. .connect(device, timeout: const Duration(seconds: 2))
  184. .listen(null, onDone: _disconnect);
  185. device.state.then((s) {
  186. deviceState = s;
  187. print('device state: $deviceState'); //change it immediately
  188. });
  189. // Subscribe to connection changes
  190. deviceStateSubscription = device.onStateChanged().listen((s) {
  191. print('statesubscription change: $s');
  192. deviceState = s;
  193. if (s == BluetoothDeviceState.connected) {
  194. ///discover services
  195. device.discoverServices().then((services) {
  196. // services = s;
  197. _checkServiceAndCharacteristic(services);
  198. });
  199. } else if (s == BluetoothDeviceState.disconnected) {
  200. _disconnect();
  201. }
  202. if (device != null) {
  203. _isConnected$.add(true);
  204. }
  205. });
  206. }
  207. _checkServiceAndCharacteristic(List<BluetoothService> services) {
  208. print("_lookForService()");
  209. services.forEach((s) {
  210. print(s.uuid.toString());
  211. if (s.uuid.toString().toUpperCase().substring(4, 8) == "0001") {
  212. // Bluetooth UART characteristic found!
  213. print(
  214. "Service found: ${s.uuid.toString().toUpperCase().substring(4, 8)} -> check Characteristic");
  215. s.characteristics.forEach((c) {
  216. if (c.uuid.toString().toUpperCase().substring(4, 8) == "0003") {
  217. /* print(
  218. "Characteristic found: ${f.uuid.toString().toUpperCase().substring(4, 8)}");*/
  219. _subscribeTouchDataNotification(c);
  220. }
  221. });
  222. }
  223. else if(s.uuid.toString().toUpperCase().substring(4,8) == "180F"){
  224. print('battery service found');
  225. s.characteristics.forEach((c){
  226. if(c.uuid.toString().toUpperCase().substring(4,8) == "2A19"){
  227. _subscribeBatteryNotfications(c);
  228. }
  229. });
  230. }
  231. });
  232. }
  233. _subscribeBatteryNotfications(BluetoothCharacteristic c) async {
  234. print('_subscribe battery: ${c.isNotifying}');
  235. if (c.isNotifying) {
  236. // Unsubscribe from subscription
  237. await device.setNotifyValue(c, false);
  238. valueChangedSubscriptions[c.uuid]?.cancel();
  239. valueChangedSubscriptions.remove(c.uuid);
  240. } else {
  241. print('subscribe battery');
  242. var _batteryValue = await device.readCharacteristic(c);
  243. assert(_batteryValue[0] >= 0 && _batteryValue[0] <= 100);
  244. print('battery right now: ${_batteryValue[0]} %');
  245. _batteryValue$.add(_batteryValue[0]);
  246. // ignore: cancel_subscriptions
  247. final subBattery = device.onValueChanged(c).listen((d) {
  248. print("battery: $d");
  249. });
  250. valueChangedSubscriptions[c.uuid] = subBattery;
  251. }
  252. }
  253. _subscribeTouchDataNotification(BluetoothCharacteristic c) async {
  254. if (c.isNotifying) {
  255. // Unsubscribe from subscription
  256. await device.setNotifyValue(c, false);
  257. valueChangedSubscriptions[c.uuid]?.cancel();
  258. valueChangedSubscriptions.remove(c.uuid);
  259. } else {
  260. // ignore: cancel_subscriptions
  261. final sub = device.onValueChanged(c).listen((d) {
  262. List<int> dFiltered = new List.from(d); // Copy List
  263. dFiltered.removeWhere((item) =>
  264. item < 48 && item != 40 && item != 41 && item != 24 ||
  265. item > 57 && item != 124);
  266. var dDecoded = utf8.decode(dFiltered);
  267. _combineStringToMeasurement(dDecoded);
  268. });
  269. valueChangedSubscriptions[c.uuid] = sub;
  270. }
  271. }
  272. void _combineStringToMeasurement(String dDecoded) {
  273. // Combines one data set.
  274. for (var x = 0; x < dDecoded.length; x++) {
  275. if (touchMessage.length < 15) {
  276. if (touchMessage.length == 0) {
  277. if (dDecoded[x] == '(') {
  278. touchMessage += dDecoded[x];
  279. }
  280. } else {
  281. touchMessage += dDecoded[x];
  282. }
  283. }
  284. if (touchMessage.length == 15) {
  285. _extractTouchpointsFromString(touchMessage);
  286. touchMessage = "";
  287. } else if (touchMessage.length > 15) {
  288. touchMessage = ""; // clear string
  289. }
  290. }
  291. }
  292. void _extractTouchpointsFromString(String inputString) {
  293. // Gets data from data string and saves it
  294. TouchData t = TouchData(0, 0, 0, 0);
  295. final RegExp regExp = new RegExp(
  296. r"\(\d\|\d\|\d{4}\|\d{4}\)",
  297. caseSensitive: false,
  298. multiLine: false,
  299. );
  300. var matches = regExp.allMatches(inputString);
  301. for (var m in matches) {
  302. t.event = int.tryParse(m.group(0)[1]);
  303. t.fingerNumber = int.tryParse(m.group(0)[3]);
  304. t.x = int.tryParse(m.group(0).substring(5, 9));
  305. t.y = int.tryParse(m.group(0).substring(10, 14));
  306. if (t.x < 1100 &&
  307. t.y < 1100 &&
  308. (t.fingerNumber <= 4) &&
  309. (t.event == 1 || t.event == 4 || t.event == 5)) {
  310. _checkButtons(t);
  311. if (t.x >= 950) {
  312. _checkSlider(t);
  313. }
  314. _fillSensorVisualisationStreams(t);
  315. } else {
  316. // print("Touch not Added!!!!!!!!!!!! $i ${t.e} ${t.f} ${t.x} ${t.y}");
  317. }
  318. }
  319. }
  320. void _fillSensorVisualisationStreams(TouchData t) {
  321. _singleTouchMessage$.add(t);
  322. _fingerTouches[t.fingerNumber].touchEvent(t.event, t.x, t.y);
  323. _touchVisualise$.add(_fingerTouches);
  324. //History:
  325. history.add(t);
  326. _touchDataHistory$.add(history);
  327. }
  328. static bool enableButtons = true;
  329. Future _checkButtons(TouchData t) async {
  330. // 4 == press down; 1 == move; 5 == up
  331. final int button0Upper = 130, button0Lower = 320;
  332. final int button1Upper = 320, button1Lower = 510;
  333. final int button2Upper = 510, button2Lower = 730;
  334. const Duration durationButtonDebounce = Duration(milliseconds: 50);
  335. const Duration durationButtonPressMinimum = Duration(milliseconds: 100);
  336. if (t.x < 100 &&
  337. t.y >= button0Upper &&
  338. t.y <= button2Lower &&
  339. enableButtons) {
  340. if (t.event == 5) {
  341. // a button is released!
  342. if (t.y >= button0Upper &&
  343. t.y <= button0Lower &&
  344. _buttonPressed[0] == buttonsState.pressed) {
  345. _buttonsState[0] = !_buttonsState[0];
  346. _buttonsState[1] = _buttonsState[2] = false;
  347. _buttonPressed[0] =
  348. buttonsState.released; // wait for a new button press now
  349. print('bBloc: button released -> ButtonStatus: $_buttonsState');
  350. } else if (t.y >= button1Upper &&
  351. t.y <= button1Lower &&
  352. _buttonPressed[1] == buttonsState.pressed) {
  353. _buttonsState[1] = !_buttonsState[1];
  354. _buttonsState[0] = _buttonsState[2] = false;
  355. _buttonPressed[1] =
  356. buttonsState.released; // wait for a new button press now
  357. print('bBloc: button released -> ButtonStatus: $_buttonsState');
  358. } else if (t.y >= button2Upper &&
  359. t.y <= button2Lower &&
  360. _buttonPressed[2] == buttonsState.pressed) {
  361. _buttonsState[2] = !_buttonsState[2];
  362. _buttonsState[0] = _buttonsState[1] = false;
  363. _buttonPressed[2] =
  364. buttonsState.released; // wait for a new button press now
  365. print('bBloc: button released -> ButtonStatus: $_buttonsState');
  366. }
  367. _buttonEnabledStatus$.add(_buttonsState); // update visuals
  368. _buttonVibration$.add(buttonsState.released);
  369. enableButtons = false;
  370. Future.delayed(durationButtonDebounce, () {
  371. enableButtons = true;
  372. });
  373. } else if (t.event == 4) {
  374. // finger pressed on a button -> send event out
  375. var whichButtonPressed;
  376. if (t.y >= button0Upper &&
  377. t.y <= button0Lower &&
  378. _buttonPressed[0] == buttonsState.released) {
  379. whichButtonPressed = 0;
  380. } else if (t.y >= button1Upper &&
  381. t.y <= button1Lower &&
  382. _buttonPressed[1] == buttonsState.released) {
  383. whichButtonPressed = 1;
  384. } else if (t.y >= button2Upper &&
  385. t.y <= button2Lower &&
  386. _buttonPressed[2] == buttonsState.released) {
  387. whichButtonPressed = 2;
  388. }
  389. if (whichButtonPressed != null &&
  390. whichButtonPressed >= 0 &&
  391. whichButtonPressed <= 2) {
  392. print('bBloc: Button pressed!');
  393. _buttonVibration$.add(buttonsState.pressed);
  394. Future.delayed(durationButtonPressMinimum, () {
  395. _buttonPressed[whichButtonPressed] = buttonsState.pressed;
  396. });
  397. }
  398. }
  399. }
  400. }
  401. Future _checkSlider(TouchData t) async {
  402. const double topSlider = 75.0;
  403. const double bottomSlider = 940.0;
  404. int sliderPercent;
  405. const double range = bottomSlider - topSlider;
  406. double sliderPosition;
  407. double sliderValue;
  408. if ((t.event == 4 || t.event == 1)) {
  409. if (t.y > topSlider) {
  410. sliderPosition = t.y - topSlider;
  411. } else {
  412. sliderPosition = 0;
  413. }
  414. sliderValue = sliderPosition / range; // 0...1
  415. sliderPercent = 100 - (sliderValue * 100).round(); // %
  416. if (sliderPercent > 100) sliderPercent = 100;
  417. if (sliderPercent < 0) sliderPercent = 0;
  418. _slider$.add(sliderPercent);
  419. }
  420. }
  421. void dispose() {
  422. print('cleanup');
  423. _disconnect();
  424. _scanController.close();
  425. _stopController.close();
  426. _connectController.close();
  427. _disconnectController.close();
  428. _touchDataHistory$.close();
  429. _touchVisualise$.close();
  430. _buttonEnabledStatus$.close();
  431. _buttonVibration$.close();
  432. _slider$.close();
  433. _batteryValue$.close();
  434. _isScanning$.close();
  435. _isConnected$.close();
  436. _singleTouchMessage$.close();
  437. _stateSubscription?.cancel();
  438. _stateSubscription = null;
  439. _scanSubscription?.cancel();
  440. _scanSubscription = null;
  441. deviceConnection?.cancel();
  442. deviceConnection = null;
  443. }
  444. int checkButtonPressed(TouchData t) {
  445. return 1;
  446. }
  447. int parseData(String s) {
  448. // _parseData(s);
  449. return 1;
  450. }
  451. }