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/ecg_ble.dart

233 lines
10 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 ECG_BLE extends StatefulWidget {
@override
State<ECG_BLE> createState() => _ECG_BLEState();
}
class _ECG_BLEState extends State<ECG_BLE> {
String connectionStatus = "disconnected";
BluetoothDevice currentConnectedDevice;
BluetoothCharacteristic ecgWriteCharacteristic;
StreamSubscription bleDevicesStream;
StreamSubscription bleDeviceConnectionStream;
final bleConnectionStatus = ValueNotifier<String>("Disconnected");
@override
void dispose() {
super.dispose();
if (bleDevicesStream != null) bleDevicesStream.cancel();
if (currentConnectedDevice != null) currentConnectedDevice.disconnect();
bleConnectionStatus.dispose();
if (bleDeviceConnectionStream != null) bleDeviceConnectionStream.cancel();
}
@override
void initState() {
super.initState();
// FlutterBluePlus.setLogLevel(LogLevel.verbose, color: false);
}
@override
Widget build(BuildContext context) {
return AppScaffold(
appBarTitle: "ECG",
showNewAppBar: true,
isShowDecPage: false,
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,
),
ValueListenableBuilder(
valueListenable: bleConnectionStatus,
builder: (context, value, _) {
return Text("Connection state: $value");
},
),
SizedBox(
height: 50.0,
),
// Text("Current Temp: $currentTempInCelsius"),
],
),
);
} 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) {
bleConnectionStatus.value = "Connecting...";
bleDevicesStream = FlutterBluePlus.scanResults.listen((results) {
List<ScanResult> blueToothDevices = results;
blueToothDevices.forEach((element) async {
if (element.device.localName.isNotEmpty) {
if (element.device.localName.toLowerCase() == "pm101897") {
bleDevicesStream.cancel();
element.device.connect(timeout: Duration(seconds: 30), autoConnect: false).then((value) async {
bleConnectionStatus.value = "Connected...";
print("Device Connected-------");
currentConnectedDevice = element.device;
bleDeviceConnectionStream = currentConnectedDevice.connectionState.listen((event) {
if (event == BluetoothConnectionState.disconnected) {
bleConnectionStatus.value = "Disconnected...";
print("Device Disconnected-------");
// if (_timer.isActive) _timer.cancel();
}
});
FlutterBluePlus.stopScan();
List<BluetoothService> services = await element.device.discoverServices(timeout: 30).catchError((err) {
print(err.toString());
element.device.disconnect(timeout: 15);
});
if (services != null && services.isNotEmpty) {
services.forEach((service) {
if (service.serviceUuid.toString().toLowerCase() == BLEUtils.ECG_SERVICE) {
print(service.serviceUuid);
service.characteristics.forEach((characteristic) async {
if (characteristic.characteristicUuid.toString().toLowerCase() == BLEUtils.ECG_READ_CHARACTERISTIC) {
print(characteristic.characteristicUuid);
print(characteristic.properties.toString());
characteristic.onValueReceived.listen((event) {
print("onValueReceived 1e4d Stream");
print(event);
});
await Future.delayed(Duration(milliseconds: 1000)).then((value) async {
print("-----Delayed 1e4d notify true done-----");
if (!characteristic.isNotifying) await characteristic.setNotifyValue(true).catchError((err) {});
});
}
if (characteristic.characteristicUuid.toString().toLowerCase() == BLEUtils.ECG_WRITE_CHARACTERISTIC) {
print(characteristic.characteristicUuid);
print(characteristic.properties.toString());
// Write get cases command to 8841
await Future.delayed(Duration(milliseconds: 1000)).then((value) async {
// 0x90 00 00 00 1
characteristic.write([0x90, 0x00, 0x00, 0x00, 0x01], withoutResponse: false).then((value) {
print("----8841 get device info command data written----");
});
});
}
});
}
});
}
}).catchError((onError) {
print("----- ERRORRRR!!!!!! -------");
print(onError.toString());
});
}
}
// if (element.device.localName.isNotEmpty) {
// if (element.device.localName.toLowerCase() == "pm101897") {
// bleDevicesStream.cancel();
// element.device.connectionState.listen((BluetoothConnectionState state) async {
// if (mounted) {
// 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) {
// if (FlutterBluePlus.isScanningNow) {
// FlutterBluePlus.stopScan();
// }
// currentConnectedDevice = element.device;
// // currentConnectedDevice.clearGattCache();
// // currentConnectedDevice.requestConnectionPriority(connectionPriorityRequest: ConnectionPriority.high);
// // currentConnectedDevice.requestMtu(512);
// // currentConnectedDevice.mtu.first.then((value) {
// // print("MTU Size: $value");
// // });
// List<BluetoothService> services = await element.device.discoverServices();
// services.forEach((service) {
// if (service.serviceUuid.toString().toLowerCase() == BLEUtils.ECG_SERVICE) {
// print(service.serviceUuid);
// service.characteristics.forEach((characteristic) async {
// if (characteristic.characteristicUuid.toString().toLowerCase() == BLEUtils.ECG_READ_CHARACTERISTIC) {
// print(characteristic.characteristicUuid);
// characteristic.onValueReceived.listen((event) {
// print("onValueReceived Stream");
// print(event);
// });
// if (!characteristic.isNotifying) await characteristic.setNotifyValue(true);
// }
//
// if (characteristic.characteristicUuid.toString().toLowerCase() == BLEUtils.ECG_WRITE_CHARACTERISTIC) {
// print("Write Characteristic: ${characteristic.characteristicUuid}");
// ecgWriteCharacteristic = characteristic;
// await ecgWriteCharacteristic.write([0x83]);
// }
// });
// return true;
// }
// });
// }
// });
// await element.device.connect(timeout: Duration(seconds: 35));
// return true;
// }
// }
});
});
FlutterBluePlus.startScan(timeout: const Duration(seconds: 15), androidUsesFineLocation: false);
}
}
}