forked from innoveit/react-native-ble-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
600 lines (548 loc) · 16.7 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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/**
* Sample BLE React Native App
*/
import React, {useState, useEffect} from 'react';
import {
ScrollView,
ImageBackground,
Image,
Animated,
SafeAreaView,
StyleSheet,
View,
Text,
StatusBar,
Dimensions,
NativeModules,
NativeEventEmitter,
Platform,
PermissionsAndroid,
TouchableHighlight,
Pressable,
FlatList,
} from 'react-native';
const AppHeader = () => {
const [currentTime, setCurrentTime] = useState(
new Date().toLocaleTimeString(),
);
useEffect(() => {
const interval = setInterval(() => {
setCurrentTime(new Date().toLocaleTimeString());
}, 1000);
return () => {
clearInterval(interval);
};
}, []);
return (
<SafeAreaView style={{backgroundColor: 'black'}}>
<View style={headerStyles.header}>
<Text style={headerStyles.headerText}>Transduce and Beautify</Text>
<Text style={headerStyles.timeText}>{currentTime}</Text>
</View>
</SafeAreaView>
);
};
const headerStyles = StyleSheet.create({
header: {
flexDirection: 'row',
justifyContent: 'space-between', // Restore the space-between layout
alignItems: 'center', // Ensures vertical alignment
backgroundColor: 'black',
padding: 10,
paddingTop: Platform.OS === 'android' ? 10 : 40,
width: '100%',
},
headerText: {
color: 'white',
fontSize: 20,
fontWeight: 'bold',
flex: 1, // Take up as much horizontal space as possible
textAlign: 'center', // Centers the text
},
timeText: {
color: 'white',
fontSize: 16,
textAlign: 'right', // Centers the text
paddingRight: 10, // Padding to separate time from the right edge
},
});
import {Colors} from 'react-native/Libraries/NewAppScreen';
const SECONDS_TO_SCAN_FOR = 7;
const SERVICE_UUIDS: string[] = [];
//TODO: more responsive when scanning, but may make establishing connection less reliable
const ALLOW_DUPLICATES = false;
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;
}
}
// Get the width of the screen
const screenWidth = Dimensions.get('window').width;
const RedPage: React.FC = () => {
return <Text>Hello</Text>;
};
const YellowPage: React.FC = () => {
return <Text>World</Text>;
};
const App = () => {
const [settingsButtonOpacity] = useState(new Animated.Value(1));
const [isScanning, setIsScanning] = useState(false);
const [peripherals, setPeripherals] = useState(
new Map<Peripheral['id'], Peripheral>(),
);
console.debug('peripherals map updated', [...peripherals.entries()]);
const openSettings = () => {
Animated.sequence([
Animated.timing(settingsButtonOpacity, {
toValue: 0.5,
duration: 100,
useNativeDriver: true,
}),
Animated.timing(settingsButtonOpacity, {
toValue: 1,
duration: 100,
useNativeDriver: true,
}),
]).start();
// TODO: Insert code to open settings or perform any other action
};
const addOrUpdatePeripheral = (id: string, updatedPeripheral: Peripheral) => {
// new Map() enables changing the reference & refreshing UI.
// TOFIX not efficient.
setPeripherals(map => new Map(map.set(id, updatedPeripheral)));
};
const toggleScan = async () => {
console.log('toggleScan');
if (isScanning) {
try {
await BleManager.stopScan();
console.log('Scan stopped successfully');
handleStopScan();
} catch (error) {
console.error('Error stopping the scan:', error);
}
} else {
try {
startScan();
} catch (error) {
console.error('Error starting the scan:', error);
}
}
};
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 => {
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,
) => {
let peripheral = peripherals.get(event.peripheral);
if (peripheral) {
console.debug(
`[handleDisconnectedPeripheral][${peripheral.id}] previously connected peripheral is disconnected.`,
event.peripheral,
);
addOrUpdatePeripheral(peripheral.id, {...peripheral, connected: false});
}
console.debug(
`[handleDisconnectedPeripheral][${event.peripheral}] disconnected.`,
);
};
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';
}
addOrUpdatePeripheral(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];
addOrUpdatePeripheral(peripheral.id, {...peripheral, connected: true});
}
} catch (error) {
console.error(
'[retrieveConnected] unable to retrieve connected peripherals.',
error,
);
}
};
const connectPeripheral = async (peripheral: Peripheral) => {
try {
if (peripheral) {
addOrUpdatePeripheral(peripheral.id, {...peripheral, connecting: true});
await BleManager.connect(peripheral.id);
console.debug(`[connectPeripheral][${peripheral.id}] connected.`);
addOrUpdatePeripheral(peripheral.id, {
...peripheral,
connecting: false,
connected: true,
});
// 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}] descriptor read as:`,
data,
);
} catch (error) {
console.error(
`[connectPeripheral][${peripheral.id}] failed to retrieve descriptor ${descriptor} for characteristic ${characteristic}:`,
error,
);
}
}
}
}
}
let p = peripherals.get(peripheral.id);
if (p) {
addOrUpdatePeripheral(peripheral.id, {...peripheral, rssi});
}
}
} 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 =>
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,
),
];
handleAndroidPermissions();
// Cleanup function
return () => {
console.debug('[app] main component unmounting. Removing listeners...');
for (const listener of listeners) {
listener.remove();
}
};
}, []);
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 (
<>
<AppHeader />
<SafeAreaView style={{flex: 1}}>
<StatusBar
barStyle="dark-content"
// ... any other StatusBar props you want ...
/>
<ScrollView
horizontal={true}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}>
{/* Main Screen */}
<View style={{width: screenWidth, flex: 1}}>
<Pressable style={styles.scanButton} onPress={toggleScan}>
<Text style={styles.scanButtonText}>
{isScanning ? 'Scanning...' : 'Scan Bluetooth'}
</Text>
</Pressable>
<FlatList
data={Array.from(peripherals.values())}
contentContainerStyle={{rowGap: 12}}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
{Array.from(peripherals.values()).length === 0 && (
<View style={styles.row}>
<Text style={styles.noPeripherals}>
No Peripherals, press "Scan Bluetooth" above.
</Text>
</View>
)}
</View>
{/* Yellow Page */}
<View style={{width: screenWidth, flex: 1, justifyContent: 'center'}}>
<ImageBackground
source={require('./assets/IMG_0034.jpeg')}
style={{flex: 1}}>
<Pressable style={styles.scanButton} onPress={retrieveConnected}>
<Text style={styles.scanButtonText}>
{'Retrieve connected peripherals'}
</Text>
</Pressable>
</ImageBackground>
<YellowPage />
</View>
{/* Red Page */}
<View style={{width: screenWidth, flex: 1, justifyContent: 'center'}}>
<ImageBackground
source={require('./assets/IMG_0034.jpeg')}
style={{flex: 1}}>
<Animated.View style={{opacity: settingsButtonOpacity}}>
<Pressable style={styles.scanButton} onPress={openSettings}>
<Text style={styles.scanButtonText}>Settings</Text>
</Pressable>
</Animated.View>
</ImageBackground>
<RedPage />
</View>
</ScrollView>
</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,
backgroundColor: 'black',
...boxShadow,
},
noPeripherals: {
margin: 10,
textAlign: 'center',
color: Colors.white,
},
});
export default App;