egmontr
egmontr

Reputation: 249

Triggering beacons by distance

As @davidgyoung suggested in Detect beacons exited a range, here my new question.

I would like to create a radius around beacons for entering and leaving that zone. In fact detecting beacons by distance. I understood how to check, when a beacon entered a radius. To test this I used:

public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
    if (beacons.size() > 0) {
        for (Beacon beacon: beacons) {
          logToDisplay("Beacon "+beacon.toString()+" is about "+beacon.getDistance()+" meters away, with Rssi: "+beacon.getRssi());
          if (beacon.getDistance() < 5.0) {
              logToDisplay("Beacon "+ beacon.toString()+" I see a beacon that is less than 5 meters away.");
          }
        }
    }
}

I did not understand, how to recognize the exit of a range. Please help.

Upvotes: 0

Views: 389

Answers (1)

davidgyoung
davidgyoung

Reputation: 64916

One technique you might use is this:

  • Use a flag variable to indicate whether you are inside or outside a distance-based proximity zone. Call the flag mInsideZone.

  • When the beacon is detected to be < 5 meters, and the app is not already inside the zone, execute your "entry" code, and set the flag to true. In this case, we just print out "Beacon became less than five meters away."

  • When the beacon is detected to be > 10 meters, and the app is already inside the zone, execute your "exit" code, and set the flag to false.

Why is the entry based on 5 meters and the exit based on 10 meters? Because distance estimates fluctuate, and you don't want it going back and forth between entry/exit when you are somewhere in the middle. You don't have to use these exact numbers, but you'll probably want to do something similar.

Here's the code:

private boolean mInsideZone = false;
@Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
    if (beacons.size() > 0) {
        for (Beacon beacon: beacons) {
            logToDisplay("Beacon "+beacon.toString()+" is about "+beacon.getDistance()+" meters away, with Rssi: "+beacon.getRssi());
            if (beacon.getDistance() < 5.0 && mInsideZone == false) {
                logToDisplay("Beacon "+ beacon.toString()+" Just became less than 5 meters away.");
                mInsideZone = true;
            }
            if (beacon.getDistance() > 10.0 && mInsideZone == true) {
                logToDisplay("Beacon "+ beacon.toString()+" Just became over 10 meters away.");
                mInsideZone = false;
            }
        }
    }
}

Upvotes: 1

Related Questions