-
Notifications
You must be signed in to change notification settings - Fork 34
/
useBLE.ts
179 lines (158 loc) · 4.99 KB
/
useBLE.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/* eslint-disable no-bitwise */
import { useMemo, useState } from "react";
import { PermissionsAndroid, Platform } from "react-native";
import {
BleError,
BleManager,
Characteristic,
Device,
} from "react-native-ble-plx";
import * as ExpoDevice from "expo-device";
import base64 from "react-native-base64";
const HEART_RATE_UUID = "0000180d-0000-1000-8000-00805f9b34fb";
const HEART_RATE_CHARACTERISTIC = "00002a37-0000-1000-8000-00805f9b34fb";
interface BluetoothLowEnergyApi {
requestPermissions(): Promise<boolean>;
scanForPeripherals(): void;
connectToDevice: (deviceId: Device) => Promise<void>;
disconnectFromDevice: () => void;
connectedDevice: Device | null;
allDevices: Device[];
heartRate: number;
}
function useBLE(): BluetoothLowEnergyApi {
const bleManager = useMemo(() => new BleManager(), []);
const [allDevices, setAllDevices] = useState<Device[]>([]);
const [connectedDevice, setConnectedDevice] = useState<Device | null>(null);
const [heartRate, setHeartRate] = useState<number>(0);
const requestAndroid31Permissions = async () => {
const bluetoothScanPermission = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
{
title: "Location Permission",
message: "Bluetooth Low Energy requires Location",
buttonPositive: "OK",
}
);
const bluetoothConnectPermission = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
{
title: "Location Permission",
message: "Bluetooth Low Energy requires Location",
buttonPositive: "OK",
}
);
const fineLocationPermission = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Location Permission",
message: "Bluetooth Low Energy requires Location",
buttonPositive: "OK",
}
);
return (
bluetoothScanPermission === "granted" &&
bluetoothConnectPermission === "granted" &&
fineLocationPermission === "granted"
);
};
const requestPermissions = async () => {
if (Platform.OS === "android") {
if ((ExpoDevice.platformApiLevel ?? -1) < 31) {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Location Permission",
message: "Bluetooth Low Energy requires Location",
buttonPositive: "OK",
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} else {
const isAndroid31PermissionsGranted =
await requestAndroid31Permissions();
return isAndroid31PermissionsGranted;
}
} else {
return true;
}
};
const isDuplicteDevice = (devices: Device[], nextDevice: Device) =>
devices.findIndex((device) => nextDevice.id === device.id) > -1;
const scanForPeripherals = () =>
bleManager.startDeviceScan(null, null, (error, device) => {
if (error) {
console.log(error);
}
if (device && device.name?.includes("CorSense")) {
setAllDevices((prevState: Device[]) => {
if (!isDuplicteDevice(prevState, device)) {
return [...prevState, device];
}
return prevState;
});
}
});
const connectToDevice = async (device: Device) => {
try {
const deviceConnection = await bleManager.connectToDevice(device.id);
setConnectedDevice(deviceConnection);
await deviceConnection.discoverAllServicesAndCharacteristics();
bleManager.stopDeviceScan();
startStreamingData(deviceConnection);
} catch (e) {
console.log("FAILED TO CONNECT", e);
}
};
const disconnectFromDevice = () => {
if (connectedDevice) {
bleManager.cancelDeviceConnection(connectedDevice.id);
setConnectedDevice(null);
setHeartRate(0);
}
};
const onHeartRateUpdate = (
error: BleError | null,
characteristic: Characteristic | null
) => {
if (error) {
console.log(error);
return -1;
} else if (!characteristic?.value) {
console.log("No Data was recieved");
return -1;
}
const rawData = base64.decode(characteristic.value);
let innerHeartRate: number = -1;
const firstBitValue: number = Number(rawData) & 0x01;
if (firstBitValue === 0) {
innerHeartRate = rawData[1].charCodeAt(0);
} else {
innerHeartRate =
Number(rawData[1].charCodeAt(0) << 8) +
Number(rawData[2].charCodeAt(2));
}
setHeartRate(innerHeartRate);
};
const startStreamingData = async (device: Device) => {
if (device) {
device.monitorCharacteristicForService(
HEART_RATE_UUID,
HEART_RATE_CHARACTERISTIC,
onHeartRateUpdate
);
} else {
console.log("No Device Connected");
}
};
return {
scanForPeripherals,
requestPermissions,
connectToDevice,
allDevices,
connectedDevice,
disconnectFromDevice,
heartRate,
};
}
export default useBLE;