summaryrefslogtreecommitdiff
path: root/lib/esense_input.dart
diff options
context:
space:
mode:
Diffstat (limited to 'lib/esense_input.dart')
-rw-r--r--lib/esense_input.dart83
1 files changed, 83 insertions, 0 deletions
diff --git a/lib/esense_input.dart b/lib/esense_input.dart
new file mode 100644
index 0000000..705bd5f
--- /dev/null
+++ b/lib/esense_input.dart
@@ -0,0 +1,83 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:esense_flutter/esense.dart';
+import 'package:flutter/material.dart';
+import 'package:permission_handler/permission_handler.dart';
+
+class ESenseInput {
+ static final instance = ESenseInput._();
+
+ ESenseManager eSenseManager = ESenseManager('unknown');
+ ValueNotifier<String> deviceStatus = ValueNotifier('');
+
+ String eSenseDeviceName = '';
+ bool connected = false;
+ bool sampling = false;
+
+ ESenseInput._() {
+ _listenToESense();
+ }
+
+ Future<void> _askForPermissions() async {
+ if (!Platform.isAndroid && !Platform.isIOS) return;
+ if (!(await Permission.bluetoothScan.request().isGranted &&
+ await Permission.bluetoothConnect.request().isGranted)) {
+ print(
+ 'WARNING - no permission to use Bluetooth granted. Cannot access eSense device.');
+ }
+ // for some strange reason, Android requires permission to location for Bluetooth to work.....?
+ if (Platform.isAndroid) {
+ if (!(await Permission.locationWhenInUse.request().isGranted)) {
+ print(
+ 'WARNING - no permission to access location granted. Cannot access eSense device.');
+ }
+ }
+ }
+
+ StreamSubscription _listenToESense() {
+ // if you want to get the connection events when connecting,
+ // set up the listener BEFORE connecting...
+ return eSenseManager.connectionEvents.listen((event) {
+ print('CONNECTION event: $event');
+
+ // when we're connected to the eSense device, we can start listening to events from it
+ // if (event.type == ConnectionType.connected) _listenToESenseEvents();
+
+ connected = false;
+ switch (event.type) {
+ case ConnectionType.connected:
+ deviceStatus.value = 'connected';
+ connected = true;
+ break;
+ case ConnectionType.unknown:
+ deviceStatus.value = 'unknown';
+ break;
+ case ConnectionType.disconnected:
+ deviceStatus.value = 'disconnected';
+ sampling = false;
+ break;
+ case ConnectionType.device_found:
+ deviceStatus.value = 'device_found';
+ break;
+ case ConnectionType.device_not_found:
+ deviceStatus.value = 'device_not_found';
+ break;
+ }
+ });
+ }
+
+ Future<void> connectToESense(String deviceName) async {
+ if (!connected) {
+ await _askForPermissions();
+ print('Trying to connect to eSense device namend \'$deviceName\'');
+ eSenseDeviceName = deviceName;
+ eSenseManager.deviceName = deviceName;
+ connected = await eSenseManager.connect();
+ print('Trying to connect to eSense device namend \'${eSenseManager.deviceName}\'');
+
+ deviceStatus.value = connected ? 'connecting...' : 'connection failed';
+ print(deviceStatus.value);
+ }
+ }
+}