-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBleHelper.js
More file actions
79 lines (71 loc) · 2.76 KB
/
BleHelper.js
File metadata and controls
79 lines (71 loc) · 2.76 KB
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
import {
NativeModules,
NativeEventEmitter,
Platform,
PermissionsAndroid,
} from 'react-native'
import BleManager from 'react-native-ble-manager';
import {throttle} from 'lodash';
const bleManagerEmitter = new NativeEventEmitter(NativeModules.BleManager);
class BleHelper {
requestPermission() {
return new Promise(
(resolve, reject) => {
if (Platform.OS === 'android' && Platform.Version >= 23) {
PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
if (result) {
resolve();
} else {
PermissionsAndroid.requestPermission(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
if (result) {
resolve();
} else {
reject()
}
});
}
});
} else {
resolve();
}
}
)
}
registerNotification(peripheralId, serviceId, charId, callback) {
return new Promise(
(resolve, reject) => {
BleManager.startNotification(peripheralId, serviceId, charId)
.then(() => {
resolve(bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', callback));
})
.catch(err => {
console.warn('BleHelper registerNotification', err);
reject(err)
})
}
)
}
unregisterNotification(handle) {
handle.remove();
}
registerListener({onDiscovery=null, onStopScan=null}) {
if (onDiscovery) {
if (this.onDiscoveryHandler) {
throw new Error('you should only register one listener using this helper method at a time');
}
onDiscovery = throttle(onDiscovery, 250);
this.onDiscoveryHandler = bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', onDiscovery);
}
if (onStopScan) {
if (this.onStopScanHandler) {
throw new Error('you should only register one listener using this helper method at a time');
}
this.onStopScanHandler = bleManagerEmitter.addListener('BleManagerStopScan', onStopScan);
}
}
unregisterListeners() {
this.onDiscoveryHandler && this.onDiscoveryHandler.remove();
this.onStopScanHandler && this.onStopScanHandler.remove();
}
}
export default new BleHelper();