forked from SnaiNeR/react-native-bluetooth-status
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
111 lines (96 loc) · 2.59 KB
/
index.js
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
// @flow
import { useState, useEffect } from "react";
import { Platform } from "react-native";
import {
NativeModules,
DeviceEventEmitter,
NativeEventEmitter
} from "react-native";
import waitUntil from "@cs125/wait-until";
const { RNBluetoothManager } = NativeModules;
const BT_STATUS_EVENT = "bluetoothStatus";
class BluetoothManager {
subscription: mixed;
inited: boolean;
bluetoothState:
| "unknown"
| "resetting"
| "unsupported"
| "unauthorized"
| "off"
| "on"
| "unknown";
listener: function;
constructor() {
const bluetoothEvent = new NativeEventEmitter(RNBluetoothManager);
this.subscription = bluetoothEvent.addListener(BT_STATUS_EVENT, state => {
const nativeState = Platform.OS === "ios" ? state : state.status;
this.bluetoothState = nativeState;
if (this.listener) {
this.listener(this.bluetoothState === "on");
}
});
}
addListener(listener: function) {
this.listener = listener;
}
removeListener() {
this.listener = undefined;
}
async state() {
this.manualInit()
return new Promise((resolve, reject) => {
waitUntil()
.interval(100)
.times(10)
.condition(() => {
return this.bluetoothState !== undefined;
})
.done(() => {
resolve(this.bluetoothState === "on");
});
});
}
manualInit() {
if (Platform.OS === "ios") {
if(!this.inited) {
RNBluetoothManager.manualInitialization()
}
this.inited = true
}
}
enable(enabled: boolean = true) {
if (Platform.OS === "android") {
RNBluetoothManager.setBluetoothState(enabled);
}
}
async disable() {
return this.enable(false);
}
}
export const BluetoothStatus = new BluetoothManager();
const setBluetoothState = (enable: boolean = true) => {
if (Platform.OS === "android") {
RNBluetoothManager.setBluetoothState(enable);
}
};
export const useBluetoothStatus = () => {
const [status, setStatus] = useState(undefined);
const [isPending, setPending] = useState(true);
useEffect(() => {
const bluetoothEvent = new NativeEventEmitter(RNBluetoothManager);
const subscription = bluetoothEvent.addListener(BT_STATUS_EVENT, state => {
const nativeState = Platform.OS === "ios" ? state : state.status;
setStatus(nativeState === "on");
});
return () => {
bluetoothEvent.removeSubscription(subscription);
};
}, []);
useEffect(() => {
if (status !== undefined && isPending) {
setPending(false);
}
}, [status]);
return [status, isPending, setBluetoothState];
};