forked from innoveit/react-native-ble-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
487 lines (447 loc) · 13.3 KB
/
App.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/**
* Sample BLE React Native App
*/
import React, {useState, useEffect} from 'react';
import {
SafeAreaView,
StyleSheet,
View,
Text,
StatusBar,
NativeModules,
NativeEventEmitter,
Platform,
PermissionsAndroid,
FlatList,
TouchableHighlight,
Pressable,
} from 'react-native';
import {Colors} from 'react-native/Libraries/NewAppScreen';
const SECONDS_TO_SCAN_FOR = 3;
const SERVICE_UUIDS: string[] = [];
const ALLOW_DUPLICATES = true;
import BleManager, {
BleDisconnectPeripheralEvent,
BleManagerDidUpdateValueForCharacteristicEvent,
BleScanCallbackType,
BleScanMatchMode,
BleScanMode,
Peripheral,
} from 'react-native-ble-manager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
declare module 'react-native-ble-manager' {
// enrich local contract with custom state properties needed by App.tsx
interface Peripheral {
connected?: boolean;
connecting?: boolean;
}
}
const App = () => {
const [isScanning, setIsScanning] = useState(false);
const [peripherals, setPeripherals] = useState(
new Map<Peripheral['id'], Peripheral>(),
);
//console.debug('peripherals map updated', [...peripherals.entries()]);
const startScan = () => {
if (!isScanning) {
// reset found peripherals before scan
setPeripherals(new Map<Peripheral['id'], Peripheral>());
try {
console.debug('[startScan] starting scan...');
setIsScanning(true);
BleManager.scan(SERVICE_UUIDS, SECONDS_TO_SCAN_FOR, ALLOW_DUPLICATES, {
matchMode: BleScanMatchMode.Sticky,
scanMode: BleScanMode.LowLatency,
callbackType: BleScanCallbackType.AllMatches,
})
.then(() => {
console.debug('[startScan] scan promise returned successfully.');
})
.catch((err: any) => {
console.error('[startScan] ble scan returned in error', err);
});
} catch (error) {
console.error('[startScan] ble scan error thrown', error);
}
}
};
const handleStopScan = () => {
setIsScanning(false);
console.debug('[handleStopScan] scan is stopped.');
};
const handleDisconnectedPeripheral = (
event: BleDisconnectPeripheralEvent,
) => {
console.debug(
`[handleDisconnectedPeripheral][${event.peripheral}] disconnected.`,
);
setPeripherals(map => {
let p = map.get(event.peripheral);
if (p) {
p.connected = false;
return new Map(map.set(event.peripheral, p));
}
return map;
});
};
const handleConnectPeripheral = (event: any) => {
console.log(`[handleConnectPeripheral][${event.peripheral}] connected.`);
};
const handleUpdateValueForCharacteristic = (
data: BleManagerDidUpdateValueForCharacteristicEvent,
) => {
console.debug(
`[handleUpdateValueForCharacteristic] received data from '${data.peripheral}' with characteristic='${data.characteristic}' and value='${data.value}'`,
);
};
const handleDiscoverPeripheral = (peripheral: Peripheral) => {
console.debug('[handleDiscoverPeripheral] new BLE peripheral=', peripheral);
if (!peripheral.name) {
peripheral.name = 'NO NAME';
}
setPeripherals(map => {
return new Map(map.set(peripheral.id, peripheral));
});
};
const togglePeripheralConnection = async (peripheral: Peripheral) => {
if (peripheral && peripheral.connected) {
try {
await BleManager.disconnect(peripheral.id);
} catch (error) {
console.error(
`[togglePeripheralConnection][${peripheral.id}] error when trying to disconnect device.`,
error,
);
}
} else {
await connectPeripheral(peripheral);
}
};
const retrieveConnected = async () => {
try {
const connectedPeripherals = await BleManager.getConnectedPeripherals();
if (connectedPeripherals.length === 0) {
console.warn('[retrieveConnected] No connected peripherals found.');
return;
}
console.debug(
'[retrieveConnected] connectedPeripherals',
connectedPeripherals,
);
for (var i = 0; i < connectedPeripherals.length; i++) {
var peripheral = connectedPeripherals[i];
setPeripherals(map => {
let p = map.get(peripheral.id);
if (p) {
p.connected = true;
return new Map(map.set(p.id, p));
}
return map;
});
}
} catch (error) {
console.error(
'[retrieveConnected] unable to retrieve connected peripherals.',
error,
);
}
};
const connectPeripheral = async (peripheral: Peripheral) => {
try {
if (peripheral) {
setPeripherals(map => {
let p = map.get(peripheral.id);
if (p) {
p.connecting = true;
return new Map(map.set(p.id, p));
}
return map;
});
await BleManager.connect(peripheral.id);
console.debug(`[connectPeripheral][${peripheral.id}] connected.`);
setPeripherals(map => {
let p = map.get(peripheral.id);
if (p) {
p.connecting = false;
p.connected = true;
return new Map(map.set(p.id, p));
}
return map;
});
// before retrieving services, it is often a good idea to let bonding & connection finish properly
await sleep(900);
/* Test read current RSSI value, retrieve services first */
const peripheralData = await BleManager.retrieveServices(peripheral.id);
console.debug(
`[connectPeripheral][${peripheral.id}] retrieved peripheral services`,
peripheralData,
);
const rssi = await BleManager.readRSSI(peripheral.id);
console.debug(
`[connectPeripheral][${peripheral.id}] retrieved current RSSI value: ${rssi}.`,
);
if (peripheralData.characteristics) {
for (let characteristic of peripheralData.characteristics) {
if (characteristic.descriptors) {
for (let descriptor of characteristic.descriptors) {
try {
let data = await BleManager.readDescriptor(
peripheral.id,
characteristic.service,
characteristic.characteristic,
descriptor.uuid,
);
console.debug(
`[connectPeripheral][${peripheral.id}] ${characteristic.service} ${characteristic.characteristic} ${descriptor.uuid} descriptor read as:`,
data,
);
} catch (error) {
console.error(
`[connectPeripheral][${peripheral.id}] failed to retrieve descriptor ${descriptor} for characteristic ${characteristic}:`,
error,
);
}
}
}
}
}
setPeripherals(map => {
let p = map.get(peripheral.id);
if (p) {
p.rssi = rssi;
return new Map(map.set(p.id, p));
}
return map;
});
}
} catch (error) {
console.error(
`[connectPeripheral][${peripheral.id}] connectPeripheral error`,
error,
);
}
};
function sleep(ms: number) {
return new Promise<void>(resolve => setTimeout(resolve, ms));
}
useEffect(() => {
try {
BleManager.start({showAlert: false})
.then(() => console.debug('BleManager started.'))
.catch((error: any) =>
console.error('BeManager could not be started.', error),
);
} catch (error) {
console.error('unexpected error starting BleManager.', error);
return;
}
const listeners = [
bleManagerEmitter.addListener(
'BleManagerDiscoverPeripheral',
handleDiscoverPeripheral,
),
bleManagerEmitter.addListener('BleManagerStopScan', handleStopScan),
bleManagerEmitter.addListener(
'BleManagerDisconnectPeripheral',
handleDisconnectedPeripheral,
),
bleManagerEmitter.addListener(
'BleManagerDidUpdateValueForCharacteristic',
handleUpdateValueForCharacteristic,
),
bleManagerEmitter.addListener(
'BleManagerConnectPeripheral',
handleConnectPeripheral,
),
];
handleAndroidPermissions();
return () => {
console.debug('[app] main component unmounting. Removing listeners...');
for (const listener of listeners) {
listener.remove();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleAndroidPermissions = () => {
if (Platform.OS === 'android' && Platform.Version >= 31) {
PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
]).then(result => {
if (result) {
console.debug(
'[handleAndroidPermissions] User accepts runtime permissions android 12+',
);
} else {
console.error(
'[handleAndroidPermissions] User refuses runtime permissions android 12+',
);
}
});
} else if (Platform.OS === 'android' && Platform.Version >= 23) {
PermissionsAndroid.check(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
).then(checkResult => {
if (checkResult) {
console.debug(
'[handleAndroidPermissions] runtime permission Android <12 already OK',
);
} else {
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
).then(requestResult => {
if (requestResult) {
console.debug(
'[handleAndroidPermissions] User accepts runtime permission android <12',
);
} else {
console.error(
'[handleAndroidPermissions] User refuses runtime permission android <12',
);
}
});
}
});
}
};
const renderItem = ({item}: {item: Peripheral}) => {
const backgroundColor = item.connected ? '#069400' : Colors.white;
return (
<TouchableHighlight
underlayColor="#0082FC"
onPress={() => togglePeripheralConnection(item)}>
<View style={[styles.row, {backgroundColor}]}>
<Text style={styles.peripheralName}>
{/* completeLocalName (item.name) & shortAdvertisingName (advertising.localName) may not always be the same */}
{item.name} - {item?.advertising?.localName}
{item.connecting && ' - Connecting...'}
</Text>
<Text style={styles.rssi}>RSSI: {item.rssi}</Text>
<Text style={styles.peripheralId}>{item.id}</Text>
</View>
</TouchableHighlight>
);
};
return (
<>
<StatusBar />
<SafeAreaView style={styles.body}>
<Pressable style={styles.scanButton} onPress={startScan}>
<Text style={styles.scanButtonText}>
{isScanning ? 'Scanning...' : 'Scan Bluetooth'}
</Text>
</Pressable>
<Pressable style={styles.scanButton} onPress={retrieveConnected}>
<Text style={styles.scanButtonText}>
{'Retrieve connected peripherals'}
</Text>
</Pressable>
{Array.from(peripherals.values()).length === 0 && (
<View style={styles.row}>
<Text style={styles.noPeripherals}>
No Peripherals, press "Scan Bluetooth" above.
</Text>
</View>
)}
<FlatList
data={Array.from(peripherals.values())}
contentContainerStyle={{rowGap: 12}}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
</>
);
};
const boxShadow = {
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
};
const styles = StyleSheet.create({
engine: {
position: 'absolute',
right: 10,
bottom: 0,
color: Colors.black,
},
scanButton: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 16,
backgroundColor: '#0a398a',
margin: 10,
borderRadius: 12,
...boxShadow,
},
scanButtonText: {
fontSize: 20,
letterSpacing: 0.25,
color: Colors.white,
},
body: {
backgroundColor: '#0082FC',
flex: 1,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
peripheralName: {
fontSize: 16,
textAlign: 'center',
padding: 10,
},
rssi: {
fontSize: 12,
textAlign: 'center',
padding: 2,
},
peripheralId: {
fontSize: 12,
textAlign: 'center',
padding: 2,
paddingBottom: 20,
},
row: {
marginLeft: 10,
marginRight: 10,
borderRadius: 20,
...boxShadow,
},
noPeripherals: {
margin: 10,
textAlign: 'center',
color: Colors.white,
},
});
export default App;