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 deviceStatus = ValueNotifier(''); String eSenseDeviceName = ''; bool connected = false; bool sampling = false; ESenseInput._() { _listenToESense(); } Future _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 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); } } }