forked from MacKentoch/react-native-beacons-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ios.js
327 lines (290 loc) · 10.1 KB
/
index.ios.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
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
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow weak
*/
import React, {
Component
} from 'react';
import {
AppRegistry,
StyleSheet,
View,
Text,
ListView
} from 'react-native';
import Beacons from 'react-native-beacons-manager';
import BluetoothState from 'react-native-bluetooth-state';
import moment from 'moment';
/**
* uuid of YOUR BEACON (change to yours)
* @type {String} uuid
*/
const UUID = '7b44b47b-52a1-5381-90c2-f09b6838c5d4';
const IDENTIFIER = '123456';
const TIME_FORMAT = 'HH:mm:ss';
const EMPTY_BEACONS_LISTS = {
rangingList: [],
monitorEnterList: [],
monitorExitList: []
};
const deepCopyBeaconsLists = beaconsLists => {
const initial = {};
return Object
.keys(beaconsLists)
.map(key => ({ [key]: [...beaconsLists[key]] }))
.reduce(
(prev, next) => {
return {...prev, ...next};
}
, initial
);
};
class BeaconsDemo extends Component {
// will be set as list of beacons to update state
_beaconsLists = null;
// will be set as a reference to "beaconsDidRange" event:
beaconsDidRangeEvent = null;
// will be set as a reference to "regionDidEnter" event:
regionDidEnterEvent = null;
// will be set as a reference to "regionDidExit" event:
regionDidExitEvent = null;
// will be set as a reference to "authorizationStatusDidChange" event:
authStateDidRangeEvent = null;
state = {
// region information
uuid: UUID,
identifier: IDENTIFIER,
// check bluetooth state:
bluetoothState: '',
message: '',
beaconsLists: new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
sectionHeaderHasChanged: (s1, s2) => s1 !== s2
}).cloneWithRowsAndSections(EMPTY_BEACONS_LISTS)
};
componentWillMount(){
this._beaconsLists = EMPTY_BEACONS_LISTS;
const { identifier, uuid } = this.state;
// MANDATORY: you have to request ALWAYS Authorization (not only when in use) when monitoring
// you also have to add "Privacy - Location Always Usage Description" in your "Info.plist" file
// otherwise monitoring won't work
Beacons.requestAlwaysAuthorization();
Beacons.shouldDropEmptyRanges(true);
// Define a region which can be identifier + uuid,
// identifier + uuid + major or identifier + uuid + major + minor
// (minor and major properties are numbers)
const region = { identifier, uuid };
// Monitor for beacons inside the region
Beacons
.startMonitoringForRegion(region) // or like < v1.0.7: .startRangingBeaconsInRegion(identifier, uuid)
.then(() => console.log('Beacons monitoring started succesfully'))
.catch(error => console.log(`Beacons monitoring not started, error: ${error}`));
// Range for beacons inside the region
Beacons
.startRangingBeaconsInRegion(region) // or like < v1.0.7: .startRangingBeaconsInRegion(identifier, uuid)
.then(() => console.log('Beacons ranging started succesfully'))
.catch(error => console.log(`Beacons ranging not started, error: ${error}`));
// update location to be able to monitor:
Beacons.startUpdatingLocation();
}
componentDidMount() {
// OPTIONAL: listen to authorization change
this.authStateDidRangeEvent = Beacons.BeaconsEventEmitter.addListener(
'authorizationStatusDidChange',
(info) => console.log('authorizationStatusDidChange: ', info)
);
// Ranging: Listen for beacon changes
this.beaconsDidRangeEvent = Beacons.BeaconsEventEmitter.addListener(
'beaconsDidRange',
(data) => {
this.setState({ message: 'beaconsDidRange event'});
// console.log('beaconsDidRange, data: ', data);
const updatedBeaconsLists = this.updateBeaconList(data.beacons, 'rangingList');
this._beaconsLists = updatedBeaconsLists;
this.setState({ beaconsLists: this.state.beaconsLists.cloneWithRowsAndSections(this._beaconsLists)});
}
);
// monitoring events
this.regionDidEnterEvent = Beacons.BeaconsEventEmitter.addListener(
'regionDidEnter',
({uuid, identifier}) => {
this.setState({ message: 'regionDidEnter event'});
console.log('regionDidEnter, data: ', {uuid, identifier});
const time = moment().format(TIME_FORMAT);
const updatedBeaconsLists = this.updateBeaconList({uuid, identifier, time}, 'monitorEnterList');
this._beaconsLists = updatedBeaconsLists;
this.setState({ beaconsLists: this.state.beaconsLists.cloneWithRowsAndSections(this._beaconsLists)});
}
);
this.regionDidExitEvent = Beacons.BeaconsEventEmitter.addListener(
'regionDidExit',
({ identifier, uuid, minor, major }) => {
this.setState({ message: 'regionDidExit event'});
console.log('regionDidExit, data: ', {identifier, uuid, minor, major});
const time = moment().format(TIME_FORMAT);
const updatedBeaconsLists = this.updateBeaconList({ identifier, uuid, minor, major, time }, 'monitorExitList');
this._beaconsLists = updatedBeaconsLists;
this.setState({ beaconsLists: this.state.beaconsLists.cloneWithRowsAndSections(this._beaconsLists)});
}
);
// listen bluetooth state change event
BluetoothState.subscribe(
bluetoothState => this.setState({ bluetoothState: bluetoothState })
);
BluetoothState.initialize();
}
componentWillUnMount() {
const { uuid, identifier } = this.state;
const region = { identifier, uuid }; // minor and major are null here
// stop monitoring beacons:
Beacons
.stopMonitoringForRegion(region)
.then(() => console.log('Beacons monitoring stopped succesfully'))
.catch(error => console.log(`Beacons monitoring not stopped, error: ${error}`));
// stop ranging beacons:
Beacons
.stopRangingBeaconsInRegion(region)
.then(() => console.log('Beacons ranging stopped succesfully'))
.catch(error => console.log(`Beacons ranging not stopped, error: ${error}`));
// stop updating locationManager:
Beacons.stopUpdatingLocation();
// remove auth state event we registered at componentDidMount:
this.authStateDidRangeEvent.remove();
// remove monitiring events we registered at componentDidMount::
this.regionDidEnterEvent.remove();
this.regionDidExitEvent.remove();
// remove ranging event we registered at componentDidMount:
this.beaconsDidRangeEvent.remove();
}
render() {
const {
bluetoothState,
beaconsLists,
message
} = this.state;
return (
<View style={styles.container}>
<Text style={styles.btleConnectionStatus}>
Bluetooth connection status: { bluetoothState ? bluetoothState : 'NA' }
</Text>
<Text>
{ message }
</Text>
<View style={styles.justFlex}>
<ListView
dataSource={ beaconsLists }
enableEmptySections={ true }
renderRow={this.renderBeaconRow}
renderSectionHeader={this.renderBeaconSectionHeader}
/>
</View>
</View>
);
}
renderBeaconRow = (rowData) => (
<View style={styles.row}>
<Text style={styles.smallText}>
Identifier: {rowData.identifier ? rowData.identifier : 'NA'}
</Text>
<Text style={styles.smallText}>
UUID: {rowData.uuid ? rowData.uuid : 'NA'}
</Text>
<Text style={styles.smallText}>
Major: {rowData.major ? rowData.major : 'NA'}
</Text>
<Text style={styles.smallText}>
Minor: {rowData.minor ? rowData.minor : 'NA'}
</Text>
<Text style={styles.smallText}>
time: { rowData.time ? rowData.time : 'NA'}
</Text>
<Text style={styles.smallText}>
RSSI: {rowData.rssi ? rowData.rssi : 'NA'}
</Text>
<Text style={styles.smallText}>
Proximity: {rowData.proximity ? rowData.proximity : 'NA'}
</Text>
<Text style={styles.smallText}>
Distance: {rowData.accuracy ? rowData.accuracy.toFixed(2) : 'NA'}m
</Text>
</View>
)
renderBeaconSectionHeader = (sectionData, header) => (
<Text style={styles.rowSection}>
{header}
</Text>
);
updateBeaconList = (detectedBeacons = [], listName = '') => {
// just a deep copy of "this._beaconsLists":
const previousLists = deepCopyBeaconsLists(this._beaconsLists);
const listNameIsValid = Object.keys(EMPTY_BEACONS_LISTS).some(header => header === listName);
const updateMatchingList = beacon => {
if (beacon.uuid.length > 0) {
const uuid = beacon.uuid.toUpperCase();
const major = parseInt(beacon.major, 10) ? beacon.major : 0;
const minor = parseInt(beacon.minor, 10) ? beacon.minor : 0;
const hasEqualProp = (left, right) => (String(left).toUpperCase() === String(right).toUpperCase());
const isNotTheSameBeacon = beaconDetail => {
return !hasEqualProp(beaconDetail.uuid, uuid)
|| !hasEqualProp(beaconDetail.major, major)
|| !hasEqualProp(beaconDetail.minor, minor);
};
const otherBeaconsInSameList = previousLists[listName].filter(isNotTheSameBeacon);
previousLists[listName] = [...otherBeaconsInSameList, beacon];
}
};
if (!listNameIsValid) {
return previousLists;
}
if (!Array.isArray(detectedBeacons)) {
if (detectedBeacons instanceof Object) {
updateMatchingList(detectedBeacons);
return previousLists;
} else {
return previousLists;
}
}
detectedBeacons.forEach(updateMatchingList);
return previousLists;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 60,
margin: 5,
backgroundColor: '#F5FCFF',
},
justFlex: {
flex: 1
},
contentContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
btleConnectionStatus: {
fontSize: 20,
paddingTop: 20
},
headline: {
fontSize: 20,
paddingTop: 20,
marginBottom: 20
},
row: {
padding: 8,
paddingBottom: 16
},
smallText: {
fontSize: 11
},
rowSection: {
fontWeight: '700'
}
});
AppRegistry.registerComponent(
'BeaconsDemo',
() => BeaconsDemo
);