You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
PatientApp-KKUMC/lib/pages/medical/my_trackers/blood_glucose_ble.dart

172 lines
6.7 KiB
Dart

import 'dart:async';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/ble_utils.dart';
import 'package:diplomaticquarterapp/uitl/bluetooth_off.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:permission_handler/permission_handler.dart';
class BloodGlucoseBLE extends StatefulWidget {
@override
State<BloodGlucoseBLE> createState() => _BloodGlucoseBLEState();
}
class _BloodGlucoseBLEState extends State<BloodGlucoseBLE> {
String connectionStatus = "disconnected";
String currentBloodGlucose = "0.0";
BluetoothDevice currentConnectedDevice;
StreamSubscription bleDevicesStream;
StreamSubscription bloodGlucoseValuesStream;
bool isDataMeasured = false;
@override
void dispose() {
super.dispose();
if (bleDevicesStream != null) bleDevicesStream.cancel();
if (bloodGlucoseValuesStream != null) bloodGlucoseValuesStream.cancel();
if (currentConnectedDevice != null) currentConnectedDevice.disconnect();
}
@override
Widget build(BuildContext context) {
return AppScaffold(
appBarTitle: TranslationBase.of(context).bloodSugar,
showNewAppBar: true,
isShowDecPage: true,
showNewAppBarTitle: true,
backgroundColor: Color(0xffF8F8F8),
body: SingleChildScrollView(
child: StreamBuilder<BluetoothAdapterState>(
stream: FlutterBluePlus.adapterState,
initialData: BluetoothAdapterState.unknown,
builder: (c, snapshot) {
final adapterState = snapshot.data;
if (adapterState == BluetoothAdapterState.on) {
return Container(
margin: EdgeInsets.only(top: 200.0, left: 50.0, right: 50.0),
child: Column(
children: [
Center(
child: DefaultButton(
TranslationBase.of(context).start.toUpperCase(),
() {
checkBLEPermissions();
},
color: CustomColors.green,
),
),
SizedBox(
height: 50.0,
),
Text("Connection state: $connectionStatus"),
SizedBox(
height: 50.0,
),
Text("Current Temp: $currentBloodGlucose" + " mg/dL"),
],
),
);
} else {
FlutterBluePlus.stopScan();
return SizedBox(height: 300.0, child: BluetoothOffScreen(adapterState: adapterState));
}
}),
),
);
}
void checkBLEPermissions() {
[Permission.location, Permission.storage, Permission.bluetooth, Permission.bluetoothConnect, Permission.bluetoothScan].request().then((status) {
startBLEConnection();
});
}
void startBLEConnection() {
if (FlutterBluePlus.isScanningNow == false) {
setState(() {
connectionStatus = "Connecting...";
});
bleDevicesStream = FlutterBluePlus.scanResults.listen(
(results) {
List<ScanResult> blueToothDevices = results;
blueToothDevices.forEach((element) async {
if (element.device.localName.isNotEmpty) {
if (element.device.localName.toLowerCase() == "samico gl") {
element.device.connectionState.listen((BluetoothConnectionState state) async {
setState(() {
connectionStatus = state.toString();
});
if (state == BluetoothConnectionState.disconnected) {
// typically, start a periodic timer that tries to periodically reconnect.
// Note: you must always re-discover services after disconnection!
}
if (state == BluetoothConnectionState.connected) {
currentConnectedDevice = element.device;
bleDevicesStream.cancel();
List<BluetoothService> services = await element.device.discoverServices();
services.forEach((service) {
if (service.serviceUuid.toString().toLowerCase() == BLEUtils.BLOOD_GLUCOSE_SERVICE) {
print(service.serviceUuid);
service.characteristics.forEach((characteristic) async {
if (characteristic.characteristicUuid.toString().toLowerCase() == BLEUtils.BLOOD_GLUCOSE_CHARACTERISTIC) {
print(characteristic.characteristicUuid);
bloodGlucoseValuesStream = characteristic.onValueReceived.listen((event) {
print("onValueReceived Stream");
print(event);
setState(() {
if (!isDataMeasured) currentBloodGlucose = getBloodGlucoseMeasurements(event)[0];
// currentTempInCelsius = convertIntListToHex(event);
// String currentTempInFahrenheit = ((num.parse(currentTempInCelsius) * 1.8) + 32).toStringAsFixed(1);
// currentTempInCelsius = currentTempInCelsius + "\u2103" + " / " + currentTempInFahrenheit + "\u2109";
});
});
await characteristic.setNotifyValue(true);
}
});
return true;
}
});
}
});
await element.device.connect(timeout: Duration(seconds: 35));
return true;
}
}
});
},
// onError(e) => print(e);
);
FlutterBluePlus.startScan(timeout: const Duration(seconds: 5), androidUsesFineLocation: false);
}
}
List<String> getBloodGlucoseMeasurements(List<int> byteArray) {
List<String> results = [];
//[85, 6, 2, 0, 4, 99]
//[85, 12, 3, 23, 9, 12, 12, 25, 0, 75, 0, 2]
if (byteArray.length == 6) {
int secsRemaining = 0;
secsRemaining = byteArray[4];
results.add("Measuring: $secsRemaining");
} else {
num measuredValue = byteArray[9];
results.add("Measured: $measuredValue");
isDataMeasured = true;
bloodGlucoseValuesStream.cancel();
}
return results;
}
}