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.

main.dart 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // Copyright 2017, Paul DeMarco.
  2. // All rights reserved. Use of this source code is governed by a
  3. // BSD-style license that can be found in the LICENSE file.
  4. import 'dart:async';
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter_blue/flutter_blue.dart';
  7. import 'package:flutter_blue_example/widgets.dart';
  8. void main() {
  9. runApp(new FlutterBlueApp());
  10. }
  11. class FlutterBlueApp extends StatefulWidget {
  12. FlutterBlueApp({Key key, this.title}) : super(key: key);
  13. final String title;
  14. @override
  15. _FlutterBlueAppState createState() => new _FlutterBlueAppState();
  16. }
  17. class _FlutterBlueAppState extends State<FlutterBlueApp> {
  18. FlutterBlue _flutterBlue = FlutterBlue.instance;
  19. /// Scanning
  20. StreamSubscription _scanSubscription;
  21. Map<DeviceIdentifier, ScanResult> scanResults = new Map();
  22. bool isScanning = false;
  23. /// State
  24. StreamSubscription _stateSubscription;
  25. BluetoothState state = BluetoothState.unknown;
  26. /// Device
  27. BluetoothDevice device;
  28. bool get isConnected => (device != null);
  29. StreamSubscription deviceConnection;
  30. StreamSubscription deviceStateSubscription;
  31. List<BluetoothService> services = new List();
  32. Map<Guid, StreamSubscription> valueChangedSubscriptions = {};
  33. BluetoothDeviceState deviceState = BluetoothDeviceState.disconnected;
  34. @override
  35. void initState() {
  36. super.initState();
  37. // Immediately get the state of FlutterBlue
  38. _flutterBlue.state.then((s) {
  39. setState(() {
  40. state = s;
  41. });
  42. });
  43. // Subscribe to state changes
  44. _stateSubscription = _flutterBlue.onStateChanged().listen((s) {
  45. setState(() {
  46. state = s;
  47. });
  48. });
  49. }
  50. @override
  51. void dispose() {
  52. _stateSubscription?.cancel();
  53. _stateSubscription = null;
  54. _scanSubscription?.cancel();
  55. _scanSubscription = null;
  56. deviceConnection?.cancel();
  57. deviceConnection = null;
  58. super.dispose();
  59. }
  60. _startScan() {
  61. _scanSubscription = _flutterBlue
  62. .scan(
  63. timeout: const Duration(seconds: 5),
  64. /*withServices: [
  65. new Guid('0000180F-0000-1000-8000-00805F9B34FB')
  66. ]*/
  67. )
  68. .listen((scanResult) {
  69. print('localName: ${scanResult.advertisementData.localName}');
  70. print(
  71. 'manufacturerData: ${scanResult.advertisementData.manufacturerData}');
  72. print('serviceData: ${scanResult.advertisementData.serviceData}');
  73. setState(() {
  74. scanResults[scanResult.device.id] = scanResult;
  75. });
  76. }, onDone: _stopScan);
  77. setState(() {
  78. isScanning = true;
  79. });
  80. }
  81. _stopScan() {
  82. _scanSubscription?.cancel();
  83. _scanSubscription = null;
  84. setState(() {
  85. isScanning = false;
  86. });
  87. }
  88. _connect(BluetoothDevice d) async {
  89. device = d;
  90. // Connect to device
  91. deviceConnection = _flutterBlue
  92. .connect(device, timeout: const Duration(seconds: 4))
  93. .listen(
  94. null,
  95. onDone: _disconnect,
  96. );
  97. // Update the connection state immediately
  98. device.state.then((s) {
  99. setState(() {
  100. deviceState = s;
  101. });
  102. });
  103. // Subscribe to connection changes
  104. deviceStateSubscription = device.onStateChanged().listen((s) {
  105. setState(() {
  106. deviceState = s;
  107. });
  108. if (s == BluetoothDeviceState.connected) {
  109. device.discoverServices().then((s) {
  110. setState(() {
  111. services = s;
  112. });
  113. });
  114. }
  115. });
  116. }
  117. _disconnect() {
  118. // Remove all value changed listeners
  119. valueChangedSubscriptions.forEach((uuid, sub) => sub.cancel());
  120. valueChangedSubscriptions.clear();
  121. deviceStateSubscription?.cancel();
  122. deviceStateSubscription = null;
  123. deviceConnection?.cancel();
  124. deviceConnection = null;
  125. setState(() {
  126. device = null;
  127. });
  128. }
  129. _readCharacteristic(BluetoothCharacteristic c) async {
  130. await device.readCharacteristic(c);
  131. setState(() {});
  132. }
  133. _writeCharacteristic(BluetoothCharacteristic c) async {
  134. await device.writeCharacteristic(c, [0x12, 0x34],
  135. type: CharacteristicWriteType.withResponse);
  136. setState(() {});
  137. }
  138. _readDescriptor(BluetoothDescriptor d) async {
  139. await device.readDescriptor(d);
  140. setState(() {});
  141. }
  142. _writeDescriptor(BluetoothDescriptor d) async {
  143. await device.writeDescriptor(d, [0x12, 0x34]);
  144. setState(() {});
  145. }
  146. _setNotification(BluetoothCharacteristic c) async {
  147. if (c.isNotifying) {
  148. await device.setNotifyValue(c, false);
  149. // Cancel subscription
  150. valueChangedSubscriptions[c.uuid]?.cancel();
  151. valueChangedSubscriptions.remove(c.uuid);
  152. } else {
  153. await device.setNotifyValue(c, true);
  154. // ignore: cancel_subscriptions
  155. final sub = device.onValueChanged(c).listen((d) {
  156. setState(() {
  157. print('onValueChanged $d');
  158. });
  159. });
  160. // Add to map
  161. valueChangedSubscriptions[c.uuid] = sub;
  162. }
  163. setState(() {});
  164. }
  165. _refreshDeviceState(BluetoothDevice d) async {
  166. var state = await d.state;
  167. setState(() {
  168. deviceState = state;
  169. print('State refreshed: $deviceState');
  170. });
  171. }
  172. _buildScanningButton() {
  173. if (isConnected || state != BluetoothState.on) {
  174. return null;
  175. }
  176. if (isScanning) {
  177. return new FloatingActionButton(
  178. child: new Icon(Icons.stop),
  179. onPressed: _stopScan,
  180. backgroundColor: Colors.red,
  181. );
  182. } else {
  183. return new FloatingActionButton(
  184. child: new Icon(Icons.search), onPressed: _startScan);
  185. }
  186. }
  187. _buildScanResultTiles() {
  188. return scanResults.values
  189. .map((r) => ScanResultTile(
  190. result: r,
  191. onTap: () => _connect(r.device),
  192. ))
  193. .toList();
  194. }
  195. List<Widget> _buildServiceTiles() {
  196. return services
  197. .map(
  198. (s) => new ServiceTile(
  199. service: s,
  200. characteristicTiles: s.characteristics
  201. .map(
  202. (c) => new CharacteristicTile(
  203. characteristic: c,
  204. onReadPressed: () => _readCharacteristic(c),
  205. onWritePressed: () => _writeCharacteristic(c),
  206. onNotificationPressed: () => _setNotification(c),
  207. descriptorTiles: c.descriptors
  208. .map(
  209. (d) => new DescriptorTile(
  210. descriptor: d,
  211. onReadPressed: () => _readDescriptor(d),
  212. onWritePressed: () =>
  213. _writeDescriptor(d),
  214. ),
  215. )
  216. .toList(),
  217. ),
  218. )
  219. .toList(),
  220. ),
  221. )
  222. .toList();
  223. }
  224. _buildActionButtons() {
  225. if (isConnected) {
  226. return <Widget>[
  227. new IconButton(
  228. icon: const Icon(Icons.cancel),
  229. onPressed: () => _disconnect(),
  230. )
  231. ];
  232. }
  233. }
  234. _buildAlertTile() {
  235. return new Container(
  236. color: Colors.redAccent,
  237. child: new ListTile(
  238. title: new Text(
  239. 'Bluetooth adapter is ${state.toString().substring(15)}',
  240. style: Theme.of(context).primaryTextTheme.subhead,
  241. ),
  242. trailing: new Icon(
  243. Icons.error,
  244. color: Theme.of(context).primaryTextTheme.subhead.color,
  245. ),
  246. ),
  247. );
  248. }
  249. _buildDeviceStateTile() {
  250. return new ListTile(
  251. leading: (deviceState == BluetoothDeviceState.connected)
  252. ? const Icon(Icons.bluetooth_connected)
  253. : const Icon(Icons.bluetooth_disabled),
  254. title: new Text('Device is ${deviceState.toString().split('.')[1]}.'),
  255. subtitle: new Text('${device.id}'),
  256. trailing: new IconButton(
  257. icon: const Icon(Icons.refresh),
  258. onPressed: () => _refreshDeviceState(device),
  259. color: Theme.of(context).iconTheme.color.withOpacity(0.5),
  260. ));
  261. }
  262. _buildProgressBarTile() {
  263. return new LinearProgressIndicator();
  264. }
  265. @override
  266. Widget build(BuildContext context) {
  267. var tiles = new List<Widget>();
  268. if (state != BluetoothState.on) {
  269. tiles.add(_buildAlertTile());
  270. }
  271. if (isConnected) {
  272. tiles.add(_buildDeviceStateTile());
  273. tiles.addAll(_buildServiceTiles());
  274. } else {
  275. tiles.addAll(_buildScanResultTiles());
  276. }
  277. return new MaterialApp(
  278. home: new Scaffold(
  279. appBar: new AppBar(
  280. title: const Text('FlutterBlue'),
  281. actions: _buildActionButtons(),
  282. ),
  283. floatingActionButton: _buildScanningButton(),
  284. body: new Stack(
  285. children: <Widget>[
  286. (isScanning) ? _buildProgressBarTile() : new Container(),
  287. new ListView(
  288. children: tiles,
  289. )
  290. ],
  291. ),
  292. ),
  293. );
  294. }
  295. }