Home

Awesome

npm npm Gitter

react-native-beacons-manager

logo FOSSA Status

react-native-beacons-manager: add beacon technology in your React Native application for both iOS and Android.

This repository is born to keep alive and up to date these 3 original awesome:

If you want to know more about just have a look at my medium article.

If you want to test with a simulated beacon, there is a useful free application on android: beaconsimulator and MacOS: BeaconEmitter

Install (iOS and Android)

Ensure to have NodeJS >= v6.x.

You must run on real devices (don't forget to active Bluetooth when running).

Mobile Version compatibility:

1. get modules

via npm:

npm install react-native-beacons-manager

or via yarn:

yarn add react-native-beacons-manager

2. link to your application

react-native link react-native-beacons-manager

3.a configuration specific to iOS

If you plan to:

3.b configuration specific to Android

Nothing (lucky Android :smile:).

Just don't forget to activate

4. usage

NOTE: If simple examples below don't help you as much as you wanted, check detailed documentation depending on use-case + code samples here

4.a iOS

Simple example

import { DeviceEventEmitter } from 'react-native'
import Beacons from 'react-native-beacons-manager'

// 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: 'Estimotes',
    uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D'
};

// Request for authorization while the app is open
Beacons.requestWhenInUseAuthorization();

Beacons.startMonitoringForRegion(region);
Beacons.startRangingBeaconsInRegion(region);

Beacons.startUpdatingLocation();

// Listen for beacon changes
const subscription = DeviceEventEmitter.addListener(
  'beaconsDidRange',
  (data) => {
    // data.region - The current region
    // data.region.identifier
    // data.region.uuid

    // data.beacons - Array of all beacons inside a region
    //  in the following structure:
    //    .uuid
    //    .major - The major version of a beacon
    //    .minor - The minor version of a beacon
    //    .rssi - Signal strength: RSSI value (between -100 and 0)
    //    .proximity - Proximity value, can either be "unknown", "far", "near" or "immediate"
    //    .accuracy - The accuracy of a beacon
  }
);

API

MethodDescription
requestWhenInUseAuthorizationThis method should be called before anything else is called. It handles to request the use of beacons while the application is open. If the application is in the background, you will not get a signal from beacons. Either this method or Beacons.requestAlwaysAuthorization needs to be called to receive data from beacons.
requestAlwaysAuthorizationThis method should be called before anything else is called. It handles to request the use of beacons while the application is open or in the background. Either this method or Beacons.requestWhenInUseAuthorization needs to be called to receive data from beacons.
getAuthorizationStatusThis methods gets the current authorization status. While this methods provides a callback, it is not executed asynchronously. The values authorizedAlways and authorizedWhenInUse correspond to the methods requestWhenInUseAuthorization and requestAlwaysAuthorization respectively.
startMonitoringForRegionWhen starting monitoring for beacons, we need to define a region as the parameter. The region is an object, which needs to have at least two values: identifier and uuid. Additionally, it can also have a major, minor version or both. Make sure to not re-use the same identifier. In that case, we won't get the data for the beacons. The corresponding events are regionDidEnter and regionDidExit.
stopMonitoringForRegionStops monitoring for beacons. We pass a region as parameter, which has the same shape as the argument we pass in startMonitoringForRegion.
startRangingBeaconsInRegionWhen ranging for beacons, we need to define a region as the parameter. The region is an object, which needs to have at least two values: identifier and uuid. Additionally, it can also have a major, minor version or both. Make sure to not re-use the same identifier. In that case, we won't get the data for the beacons. The corresponding events are beaconsDidRange. The event will fire in every interval the beacon sends a signal, which is one second in most cases. If we are monitoring and ranging for beacons, it is best to first call startMonitoringForRegion and then call startRangingBeaconsInRegion.
stopRangingBeaconsInRegionStops ranging for beacons. We pass a region as parameter, which has the same shape as the argument we pass in startRangingBeaconsInRegion.
requestStateForRegionWhen requesting state for beacons, we need to define a region as the parameter. The region is an object, which needs to have at least two values: identifier and uuid. Additionally, it can also have a major, minor version or both. Make sure to not re-use the same identifier. In that case, we won't get the data for the beacons. The corresponding events are didDetermineState.
startUpdatingLocationThis call is needed for monitoring beacons and gets the initial position of the device.
stopUpdatingLocationThis method should be called when you don't need to receive location-based information and want to save battery power.
shouldDropEmptyRangesCall this method to stop sending the beaconsDidRange event when the beacon list is empty. This can be useful when listening to multiple beacon regions and can reduce cpu usage by 1-1.5%.
                                                                                                                                                                                                                         |
EventDescription
authorizationStatusDidChangeThis event will be called when authorization changed for receiving data location. PLEASE NOTE: starting a location service will not provide data location until authorization is given by the user ("authorizedAlways" or "authorizedWhenInUse").
beaconsDidRangeThis event will be called for every region in every beacon interval. If you have three regions you get three events every second (which is the default interval beacons send their signal). When we take a closer look at the parameter of the callback, we get information on both the region and the beacons.
regionDidEnterIf the device entered a region, regionDidEnter is being called. Inside the callback the parameter we can use returns an object with a property region that contains the region identifier value as a string. Additionally, we get the UUID of the region through its uuid property.
regionDidExitIn the same regionDidEnter is called if the device entered a region, regionDidExit will be called if the device exited a region and we can't get any signal from any of the beacons inside the region. As for the payload, we get a property called region that represents the region identifier and is a string as well as the uuid.
didDetermineStateIf there is a boundary transition for a region, didDetermineState is being called. Inside the callback the parameter we can use returns an object with a property region that contains the region identifier value as a string. Additionally, we get the UUID of the region through its uuid property.
authorizationDidChangeWhen the user permissions change, for example the user allows to always use beacons, this event will be called. The same applies when the user revokes the permission to use beacons. The payload is a string which can either be: "authorizedAlways", "authorizedWhenInUse", "denied", "notDetermined" or "restricted"

4.b Android

Simple example

import { DeviceEventEmitter } from 'react-native'
import Beacons from 'react-native-beacons-manager'

// Tells the library to detect iBeacons
Beacons.detectIBeacons()

// Start detecting all iBeacons in the nearby
try {
  await Beacons.startRangingBeaconsInRegion('REGION1')
  console.log(`Beacons ranging started succesfully!`)
} catch (err) {
  console.log(`Beacons ranging not started, error: ${error}`)
}

// Print a log of the detected iBeacons (1 per second)
DeviceEventEmitter.addListener('beaconsDidRange', (data) => {
  console.log('Found beacons!', data.beacons)
})

API

MethodDescription
detectCustomBeaconLayout(parser: string): voidAllows the detection of a custom beacon layout. For example detectCustomBeaconLayout('m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24') allows you to detect iBeacons beacons.
detectIBeacons(): voidAllows the detection of iBeacons. It's just like calling detectCustomBeaconLayout with the iBeacons layout.
detectEstimotes(): voidAllows the detection of Estimote beacons. It's just like calling detectCustomBeaconLayout with the Estimote layout.
checkTransmissionSupported(): promiseChecks if the device can use the Bluetooth to detect the beacons.
setForegroundScanPeriod(period: number): voidSets the duration in milliseconds of each Bluetooth LE scan cycle to look for beacons (in foreground). For more info take a look at the official docs
setBackgroundScanPeriod(period: number): voidSets the duration in milliseconds of each Bluetooth LE scan cycle to look for beacons (in background). For more info take a look at the official docs
setBackgroundBetweenScanPeriod(period: number): voidSets the duration in milliseconds spent not scanning between each Bluetooth LE scan cycle when no ranging/monitoring clients are in the foreground. For more info take a look at the official docs
setRssiFilter(filterType: int, avgModifier: number): voidSets the RSSI averaging method. The parameter filterType must be one of the exported constants ARMA_RSSI_FILTER or RUNNING_AVG_RSSI_FILTER. The avgModifier param changes the rate of the averaging function For the ARMA filter it's in the range 0.1-1.0, for the running average it's the filter window in milliseconds. For more info take a look at the docs
setHardwareEqualityEnforced(e: boolean): voidConfigures whether the bluetoothAddress (mac address) must be the same for two Beacons to be configured equal. This setting applies to all beacon instances in the same process. Defaults to false for backward compatibility. Useful when all the beacons you are working with have the same UUID, major and minor (they are only uniquely identifiable by their mac address), otherwise the module will detect all the beacons as if they were only one. For more info take a look at the official docs
getRangedRegions(): promiseReturns a promise that resolves in an array with the regions being ranged.
getMonitoredRegions(): promiseReturns a promise that resolves in an array with the regions being monitored.
startMonitoringForRegion({identifier: string, uuid: string, minor: int, major: int}): promiseStarts monitoring for beacons. The parameter identifier must be an unique ID. The parameter uuid is optional, it allows you to detect only the beacons with a specific UUID (if null every beacon will be detected). The parameters minor and major are optional, they allow you to monitor only the region of a specific beacon.
startRangingBeaconsInRegion(regionId: string, beaconsUUID: string): promiseStarts range scan for beacons. The parameter regionId must be an unique ID. The parameter beaconsUUID is optional, it allows you to detect only the beacons with a specific UUID (if null every beacon will be detected).
startRangingBeaconsInRegion({identifier: string, uuid: string}): promiseStarts range scan for beacons. The parameter identifier must be an unique ID. The parameter uuid is optional, it allows you to detect only the beacons with a specific UUID (if null every beacon will be detected). Prefer the use of this method over startRangingBeaconsInRegion(regionId: string, beaconsUUID: string), as this method signature more closely matches the signature for the equivalent iOS method. PLEASE NOTE: to listen EddyStone beacons on iOS, you have to pass an identifier as: EDDY_STONE_REGION_ID, (example: Beacons.startRangingBeaconsInRegion({identifier: 'EDDY_STONE_REGION_ID', ...restOptions})).
stopMonitoringForRegion({identifier: string, uuid: string, minor: int, major: int}): promiseStops the monitoring for beacons.
stopRangingBeaconsInRegion(regionId: string, beaconsUUID: string): promiseStops the range scan for beacons.
stopRangingBeaconsInRegion({identifier: string, uuid: string}): promiseStops the range scan for beacons. Prefer the use of this method over stopRangingBeaconsInRegion(regionId: string, beaconsUUID: string), as this method signature more closely matches the signature for the equivalent iOS method.
requestStateForRegion({identifier: string, uuid: string, minor: int, major: int}): voidRetrieves the state of a region asynchronously. The parameter identifier must be an unique ID. The parameter uuid is optional, it allows you to detect only the beacons with a specific UUID (if null every beacon will be detected). The parameters minor and major are optional, they allow you to monitor only the region of a specific beacon.

TODO:

Standardization of iOS and android to make library more coherent:

Improvements or new feature:

Donate

Do you use & like react-native-beacons-manager but you don’t find a way to show some love? If yes, please consider donating to support this project. Otherwise, no worries, regardless of whether there is support or not, I will keep maintaining this project. Still, if you buy me a cup of coffee I would be more than happy though 😄

Support via PayPal

license

The MIT License (MIT)

Copyright (c) 2019 Erwan DATIN

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

FOSSA Status