Advertisement
rajath_pai

MainPage

Aug 4th, 2021
1,423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 12.38 KB | None | 0 0
  1. import 'dart:async';
  2.  
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
  5. import 'package:scoped_model/scoped_model.dart';
  6.  
  7. import './BackgroundCollectedPage.dart';
  8. import './BackgroundCollectingTask.dart';
  9. import './ChatPage.dart';
  10. import './DiscoveryPage.dart';
  11. import './SelectBondedDevicePage.dart';
  12.  
  13. // import './helpers/LineChart.dart';
  14.  
  15. class MainPage extends StatefulWidget {
  16.   @override
  17.   _MainPage createState() => new _MainPage();
  18. }
  19.  
  20. class _MainPage extends State<MainPage> {
  21.   BluetoothState _bluetoothState = BluetoothState.UNKNOWN;
  22.  
  23.   String _address = "...";
  24.   String _name = "...";
  25.  
  26.   Timer? _discoverableTimeoutTimer;
  27.   int _discoverableTimeoutSecondsLeft = 0;
  28.  
  29.   BackgroundCollectingTask? _collectingTask;
  30.  
  31.   bool _autoAcceptPairingRequests = false;
  32.  
  33.   @override
  34.   void initState() {
  35.     super.initState();
  36.  
  37.     // Get current state
  38.     FlutterBluetoothSerial.instance.state.then((state) {
  39.       setState(() {
  40.         _bluetoothState = state;
  41.       });
  42.     });
  43.  
  44.     Future.doWhile(() async {
  45.       // Wait if adapter not enabled
  46.       if ((await FlutterBluetoothSerial.instance.isEnabled) ?? false) {
  47.         return false;
  48.       }
  49.       await Future.delayed(Duration(milliseconds: 0xDD));
  50.       return true;
  51.     }).then((_) {
  52.       // Update the address field
  53.       FlutterBluetoothSerial.instance.address.then((address) {
  54.         setState(() {
  55.           _address = address!;
  56.         });
  57.       });
  58.     });
  59.  
  60.     FlutterBluetoothSerial.instance.name.then((name) {
  61.       setState(() {
  62.         _name = name!;
  63.       });
  64.     });
  65.  
  66.     // Listen for futher state changes
  67.     FlutterBluetoothSerial.instance
  68.         .onStateChanged()
  69.         .listen((BluetoothState state) {
  70.       setState(() {
  71.         _bluetoothState = state;
  72.  
  73.         // Discoverable mode is disabled when Bluetooth gets disabled
  74.         _discoverableTimeoutTimer = null;
  75.         _discoverableTimeoutSecondsLeft = 0;
  76.       });
  77.     });
  78.   }
  79.  
  80.   @override
  81.   void dispose() {
  82.     FlutterBluetoothSerial.instance.setPairingRequestHandler(null);
  83.     _collectingTask?.dispose();
  84.     _discoverableTimeoutTimer?.cancel();
  85.     super.dispose();
  86.   }
  87.  
  88.   @override
  89.   Widget build(BuildContext context) {
  90.     return Scaffold(
  91.       appBar: AppBar(
  92.         title: const Text('Flutter Bluetooth Serial'),
  93.       ),
  94.       body: Container(
  95.         child: ListView(
  96.           children: <Widget>[
  97.             Divider(),
  98.             ListTile(title: const Text('General')),
  99.             SwitchListTile(
  100.               title: const Text('Enable Bluetooth'),
  101.               value: _bluetoothState.isEnabled,
  102.               onChanged: (bool value) {
  103.                 // Do the request and update with the true value then
  104.                 future() async {
  105.                   // async lambda seems to not working
  106.                   if (value)
  107.                     await FlutterBluetoothSerial.instance.requestEnable();
  108.                   else
  109.                     await FlutterBluetoothSerial.instance.requestDisable();
  110.                 }
  111.  
  112.                 future().then((_) {
  113.                   setState(() {});
  114.                 });
  115.               },
  116.             ),
  117.             ListTile(
  118.               title: const Text('Bluetooth status'),
  119.               subtitle: Text(_bluetoothState.toString()),
  120.               trailing: ElevatedButton(
  121.                 child: const Text('Settings'),
  122.                 onPressed: () {
  123.                   FlutterBluetoothSerial.instance.openSettings();
  124.                 },
  125.               ),
  126.             ),
  127.             ListTile(
  128.               title: const Text('Local adapter address'),
  129.               subtitle: Text(_address),
  130.             ),
  131.             ListTile(
  132.               title: const Text('Local adapter name'),
  133.               subtitle: Text(_name),
  134.               onLongPress: null,
  135.             ),
  136.             ListTile(
  137.               title: _discoverableTimeoutSecondsLeft == 0
  138.                   ? const Text("Discoverable")
  139.                   : Text(
  140.                       "Discoverable for ${_discoverableTimeoutSecondsLeft}s"),
  141.               subtitle: const Text("PsychoX-Luna"),
  142.               trailing: Row(
  143.                 mainAxisSize: MainAxisSize.min,
  144.                 children: [
  145.                   Checkbox(
  146.                     value: _discoverableTimeoutSecondsLeft != 0,
  147.                     onChanged: null,
  148.                   ),
  149.                   IconButton(
  150.                     icon: const Icon(Icons.edit),
  151.                     onPressed: null,
  152.                   ),
  153.                   IconButton(
  154.                     icon: const Icon(Icons.refresh),
  155.                     onPressed: () async {
  156.                       print('Discoverable requested');
  157.                       final int timeout = (await FlutterBluetoothSerial.instance
  158.                           .requestDiscoverable(60))!;
  159.                       if (timeout < 0) {
  160.                         print('Discoverable mode denied');
  161.                       } else {
  162.                         print(
  163.                             'Discoverable mode acquired for $timeout seconds');
  164.                       }
  165.                       setState(() {
  166.                         _discoverableTimeoutTimer?.cancel();
  167.                         _discoverableTimeoutSecondsLeft = timeout;
  168.                         _discoverableTimeoutTimer =
  169.                             Timer.periodic(Duration(seconds: 1), (Timer timer) {
  170.                           setState(() {
  171.                             if (_discoverableTimeoutSecondsLeft < 0) {
  172.                               FlutterBluetoothSerial.instance.isDiscoverable
  173.                                   .then((isDiscoverable) {
  174.                                 if (isDiscoverable ?? false) {
  175.                                   print(
  176.                                       "Discoverable after timeout... might be infinity timeout :F");
  177.                                   _discoverableTimeoutSecondsLeft += 1;
  178.                                 }
  179.                               });
  180.                               timer.cancel();
  181.                               _discoverableTimeoutSecondsLeft = 0;
  182.                             } else {
  183.                               _discoverableTimeoutSecondsLeft -= 1;
  184.                             }
  185.                           });
  186.                         });
  187.                       });
  188.                     },
  189.                   )
  190.                 ],
  191.               ),
  192.             ),
  193.             Divider(),
  194.             ListTile(title: const Text('Devices discovery and connection')),
  195.             SwitchListTile(
  196.               title: const Text('Auto-try specific pin when pairing'),
  197.               subtitle: const Text('Pin 1234'),
  198.               value: _autoAcceptPairingRequests,
  199.               onChanged: (bool value) {
  200.                 setState(() {
  201.                   _autoAcceptPairingRequests = value;
  202.                 });
  203.                 if (value) {
  204.                   FlutterBluetoothSerial.instance.setPairingRequestHandler(
  205.                       (BluetoothPairingRequest request) {
  206.                     print("Trying to auto-pair with Pin 1234");
  207.                     if (request.pairingVariant == PairingVariant.Pin) {
  208.                       return Future.value("1234");
  209.                     }
  210.                     return Future.value(null);
  211.                   });
  212.                 } else {
  213.                   FlutterBluetoothSerial.instance
  214.                       .setPairingRequestHandler(null);
  215.                 }
  216.               },
  217.             ),
  218.             ListTile(
  219.               title: ElevatedButton(
  220.                   child: const Text('Explore discovered devices'),
  221.                   onPressed: () async {
  222.                     final BluetoothDevice? selectedDevice =
  223.                         await Navigator.of(context).push(
  224.                       MaterialPageRoute(
  225.                         builder: (context) {
  226.                           return DiscoveryPage();
  227.                         },
  228.                       ),
  229.                     );
  230.  
  231.                     if (selectedDevice != null) {
  232.                       print('Discovery -> selected ' + selectedDevice.address);
  233.                     } else {
  234.                       print('Discovery -> no device selected');
  235.                     }
  236.                   }),
  237.             ),
  238.             ListTile(
  239.               title: ElevatedButton(
  240.                 child: const Text('Connect to paired device to chat'),
  241.                 onPressed: () async {
  242.                   final BluetoothDevice? selectedDevice =
  243.                       await Navigator.of(context).push(
  244.                     MaterialPageRoute(
  245.                       builder: (context) {
  246.                         return SelectBondedDevicePage(checkAvailability: false);
  247.                       },
  248.                     ),
  249.                   );
  250.  
  251.                   if (selectedDevice != null) {
  252.                     print('Connect -> selected ' + selectedDevice.address);
  253.                     _startChat(context, selectedDevice);
  254.                   } else {
  255.                     print('Connect -> no device selected');
  256.                   }
  257.                 },
  258.               ),
  259.             ),
  260.             Divider(),
  261.             ListTile(title: const Text('Multiple connections example')),
  262.             ListTile(
  263.               title: ElevatedButton(
  264.                 child: ((_collectingTask?.inProgress ?? false)
  265.                     ? const Text('Disconnect and stop background collecting')
  266.                     : const Text('Connect to start background collecting')),
  267.                 onPressed: () async {
  268.                   if (_collectingTask?.inProgress ?? false) {
  269.                     await _collectingTask!.cancel();
  270.                     setState(() {
  271.                       /* Update for `_collectingTask.inProgress` */
  272.                     });
  273.                   } else {
  274.                     final BluetoothDevice? selectedDevice =
  275.                         await Navigator.of(context).push(
  276.                       MaterialPageRoute(
  277.                         builder: (context) {
  278.                           return SelectBondedDevicePage(
  279.                               checkAvailability: false);
  280.                         },
  281.                       ),
  282.                     );
  283.  
  284.                     if (selectedDevice != null) {
  285.                       await _startBackgroundTask(context, selectedDevice);
  286.                       setState(() {
  287.                         /* Update for `_collectingTask.inProgress` */
  288.                       });
  289.                     }
  290.                   }
  291.                 },
  292.               ),
  293.             ),
  294.             ListTile(
  295.               title: ElevatedButton(
  296.                 child: const Text('View background collected data'),
  297.                 onPressed: (_collectingTask != null)
  298.                     ? () {
  299.                         Navigator.of(context).push(
  300.                           MaterialPageRoute(
  301.                             builder: (context) {
  302.                               return ScopedModel<BackgroundCollectingTask>(
  303.                                 model: _collectingTask!,
  304.                                 child: BackgroundCollectedPage(),
  305.                               );
  306.                             },
  307.                           ),
  308.                         );
  309.                       }
  310.                     : null,
  311.               ),
  312.             ),
  313.           ],
  314.         ),
  315.       ),
  316.     );
  317.   }
  318.  
  319.   void _startChat(BuildContext context, BluetoothDevice server) {
  320.     Navigator.of(context).push(
  321.       MaterialPageRoute(
  322.         builder: (context) {
  323.           return ChatPage(server: server);
  324.         },
  325.       ),
  326.     );
  327.   }
  328.  
  329.   Future<void> _startBackgroundTask(
  330.     BuildContext context,
  331.     BluetoothDevice server,
  332.   ) async {
  333.     try {
  334.       _collectingTask = await BackgroundCollectingTask.connect(server);
  335.       await _collectingTask!.start();
  336.     } catch (ex) {
  337.       _collectingTask?.cancel();
  338.       showDialog(
  339.         context: context,
  340.         builder: (BuildContext context) {
  341.           return AlertDialog(
  342.             title: const Text('Error occured while connecting'),
  343.             content: Text("${ex.toString()}"),
  344.             actions: <Widget>[
  345.               new TextButton(
  346.                 child: new Text("Close"),
  347.                 onPressed: () {
  348.                   Navigator.of(context).pop();
  349.                 },
  350.               ),
  351.             ],
  352.           );
  353.         },
  354.       );
  355.     }
  356.   }
  357. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement