-
Notifications
You must be signed in to change notification settings - Fork 27
/
useBLE.tsx
164 lines (142 loc) · 4.67 KB
/
useBLE.tsx
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
/* eslint-disable no-bitwise */
import {useState} from 'react';
import {PermissionsAndroid, Platform} from 'react-native';
import {
BleError,
BleManager,
Characteristic,
Device,
} from 'react-native-ble-plx';
import {PERMISSIONS, requestMultiple} from 'react-native-permissions';
import DeviceInfo from 'react-native-device-info';
import {atob} from 'react-native-quick-base64';
const HEART_RATE_UUID = '0000180d-0000-1000-8000-00805f9b34fb';
const HEART_RATE_CHARACTERISTIC = '00002a37-0000-1000-8000-00805f9b34fb';
const bleManager = new BleManager();
type VoidCallback = (result: boolean) => void;
interface BluetoothLowEnergyApi {
requestPermissions(cb: VoidCallback): Promise<void>;
scanForPeripherals(): void;
connectToDevice: (deviceId: Device) => Promise<void>;
disconnectFromDevice: () => void;
connectedDevice: Device | null;
allDevices: Device[];
heartRate: number;
}
function useBLE(): BluetoothLowEnergyApi {
const [allDevices, setAllDevices] = useState<Device[]>([]);
const [connectedDevice, setConnectedDevice] = useState<Device | null>(null);
const [heartRate, setHeartRate] = useState<number>(0);
const requestPermissions = async (cb: VoidCallback) => {
if (Platform.OS === 'android') {
const apiLevel = await DeviceInfo.getApiLevel();
if (apiLevel < 31) {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'Bluetooth Low Energy requires Location',
buttonNeutral: 'Ask Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
cb(granted === PermissionsAndroid.RESULTS.GRANTED);
} else {
const result = await requestMultiple([
PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
]);
const isGranted =
result['android.permission.BLUETOOTH_CONNECT'] ===
PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.BLUETOOTH_SCAN'] ===
PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.ACCESS_FINE_LOCATION'] ===
PermissionsAndroid.RESULTS.GRANTED;
cb(isGranted);
}
} else {
cb(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 = atob(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,
(error, characteristic) => onHeartRateUpdate(error, characteristic),
);
} else {
console.log('No Device Connected');
}
};
return {
scanForPeripherals,
requestPermissions,
connectToDevice,
allDevices,
connectedDevice,
disconnectFromDevice,
heartRate,
};
}
export default useBLE;