How to build your own Apple iBeacon… with a Raspberry Pi

US department store Macy’s recently said it is implementing iPhone-based tracking tech the better to encourage browsing punters to buy. Of course, Macy has chosen to pitch this as an Apple technology – figuring, presumably, iPhone owners are more receptive to inducements delivered through technology and have more cash to splash than Android fans.

A Pi's UART pins, connected
Can this operate as an Apple iBeacon? Yes it can

But the fact is, the system Apple calls iBeacon simply makes use of features already part of the Bluetooth Low Energy (LE) spec.

This got me thinking: how difficult would it be to build a similar system of my own? Not very hard at all, it turns out. Choose the right kit and it can be quite cheap too. I created my beacon using a £30 Raspberry Pi and a £12 Bluetooth 4.0 USB dongle.

Bluetooth LE incorporates a protocol for beacon devices to identify themselves. Each sends out a short packet of data “advertising” which can contain up to 31 bytes of user-defined data. Apple’s iBeacon specification, such as it is, stores four values in this space: a “Proximity” 128-bit UUID (Universally Unique IDentifier) and two 16-bit numbers, “Major” and “Minor”.

Apple’s developer documentation presents a good example of how these variables are used: a department store chain — Macy’s, say — adopts a single UUID for all its beacons. It uses the value of the Major variable to distinguish one shop from another, and the value of the Minor variable to differentiate between beacons in one shop’s departments.

IoGear GBU521
IoGear’s GBU521 does Bluetooth LE and is supported by the Pi’s Linux OS

Not all Bluetooth dongles are Linux-friendly. A handy resource listing well-behaving ones can be found at the Embedded Linux Wiki. A branded one will set you back around a tenner, generic ones less. I used IoGear’s GBU521.

In fact, I first tried an Inateck CSR4B5 dongle, but couldn’t get it to work. It uses a CSR chipset, the 8510. The IoGear is based on a Broadcom chipset – like the Pi itself.

Next, prepare your Pi. You need to install the official Linux Bluetooth software stack, BlueZ, and various USB development packages, some using the apt-get tool at the command line, others by compiling the code.

First run this:

sudo apt-get install libusb-dev libdbus-1-dev libglib2.0-dev \
    libudev-dev libical-dev libreadline-dev

Next install BlueZ’s source files and compile it. The version at the time of writing was 5.11. Check its website for the latest release.

sudo wget www.kernel.org/pub/linux/bluetooth/bluez-5.11.tar.xz
sudo unxz bluez-5.11.tar.xz
sudo tar xvf bluez-5.11.tar
cd bluez-5.11
sudo ./configure --disable-systemd
sudo make
sudo make install

This will take a while, but when it’s done, you can reboot and plug in the dongle.

There’s no version of the uuidgen utility which I use on Mac OS X that is readily available for the Pi, so I used this website. The 16 pairs of two-digit hexadecimal values – each pair is dubbed an “octet” in the jargon – along with Major and Minor pair of octets, need to be punched into the Pi’s Bluetooth sub-system using BlueZ’s hcitool utility:

sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 [ 92 77 83 0A B2 EB 49 0F A1 DD 7F E3 8C 49 2E DE ] [ 00 00 ] [ 00 00 ] C5 00

Note that the square brackets are NOT part of the command – I’ve added them solely to show where the UUID, Major then Minor codes go. The ‘C5’ after them is a value representing transmitted power level. Just cut and paste the line above and replace the UUID with your own.

This is how you decode the command: the “hci0” identifies your Bluetooth dongle, “cmd” tells hcitool to send the following command data to the device. The “0x08” is the Bluetooth command group – the “OGF” in the official parlance – and “0x0008” is the specific command (“OCF”), HCI_LE_Set_Advertising_Data.

The first “1E” is the number of “significant” octets in the advertising data that follow — 30 in this case — up to a maximum of 31. The non-significant part should only comprise pairs of zeroes to take the number of octets up to 31 and which, to save power, are not transmitted.

The ad data is split into groups, each formatted with a single octet providing the number of remaining octets in the group — essentially it tells the Bluetooth sub-system how further along the list of octets is the next group. It’s followed by a single octet which defines the type of data, and then any number of octets holding the data itself. You can put as many of these groups into the advertising data packet as you can fit into the 31 octets allowed.

In my example, the first “02” in the sequence says the first block of ad data is two octets long. The next octet, “01” indicates that the advertising octet(s) following are Bluetooth flags, and the “1A” is the binary value derived when certain of those flags are set.

The second ‘1A’ says the next, second group is 26 octets long, and the “FF” identifies the group as manufacturer-specific data. The Bluetooth 4.0 specification says the next two octets have to expose the manufacturer: the “4C 00” is Apple’s Bluetooth manufacturer ID.

I’m not yet sure what the “02” and “15” signify, but as I say, the Proximity UUID, Major and Minor values, and the power level complete the 26 octets of manufacturer data – and also the 30 octets of the advertising data.

BlueZ’s hcitool command formats the iBeacon advertising signal. Telling the Pi to begin sending out that signal requires the following command:

sudo hciconfig hci0 leadv

Placing a ‘3’ at the end tells the dongle not to accept connections from other devices; leaving this value off causes hciconfig to use the default value, zero. This permits connections.

You can disable LE beacon activity with the command:

sudo hciconfig hci0 noleadv

If you don’t see your beacon after issuing the leadv command, try sudo hciconfig hci0 noscan which stops the dongle looking for other Bluetooth devices. This may interfere with the beacon operation. I also found that running dongles off even a good, Raspberry Pi-friendly USB hub caused problems.

It’s an obvious next step to create scripts to set all this up and activate LE advertising whenever the Pi boots up. Just create start and stop scripts that contain the commands I’ve listed above. Some other commands you may want to include are sudo hciconfig hci0 reset, which re-initialises the Bluetooth hardware, and sudo hciconfig hci0 down and sudo hciconfig hci0 up to disable and enable the dongle.

I won’t be covering such scripts here, but if you’d like to do that, there’s a very good tutorial written by Washington DC-based Radius Networks here.

With the Pi running as a beacon, the next stage is to create an app that will look for it and notify you when you’re there. I chose to work up an iOS app — I’m exploring Apple’s iBeacon, after all — but it should be possible to code it up in Android 4.3, which added Bluetooth LE support to the Google OS.

Apple added LE to iOS 7, which was released back in September. iOS’s existing CoreLocation framwork defines a CLLocationManager class that provides an interface for detecting iBeacons and a mechanism for dealing with events triggered by moving into and out a beacon’s zone of coverage, an extension of CLLocationManager’s already available ability to work with geographical regions.

CLLocationManager also defines methods for checking whether the device the app is running on has an OS and hardware able to handle Bluetooth LE: [CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]] returns a Boolean true if the device is beacon savvy.

Pass that test and a well-behaved app will then double-check that iOS’ Location Services have been enabled and that the app has permission to access them: the [CLLocationManager locationServicesEnabled] and [CLLocationManager authorizationStatus] methods do this, the latter returning the values kCLAuthorizationStatusDenied or kCLAuthorizationStatusAuthorized. The app can then start looking for beacons with the Proximity UUID, Major and Minor values punched into the Pi earlier:

{
    ...
    
    CLBeaconRegion *beaconRegion;
    NSUUID *beaconUUID;
    NSString *beaconIdent;
    
    ...
    
    beaconUUID = [[NSUUID alloc] initWithUUIDString:@"9277830A-B2EB-490F-A1DD-7FE38C492EDE"];
    beaconIdent = @"Vulture.Zone.1";
    beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID major:0 minor:0 identifier:beaconIdent];
        
    ...
        
    [appLocationManager startMonitoringForRegion:beaconRegion];
    
    ...
}

The indentifier value is a string that helps you find the right beaconRegion if you need to interrogate the Location Manager sub-system.

Core Location provides two handy delegate methods for dealing with events triggered by the beacon monitor: - (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region and - (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region. The object that owns the CLLocationManager must adhere to the CLLocationManagerDelegate protocol if it’s to receive these messages.

These two methods provide an easy way to alert the user he or she has entered the zone and to trigger actions accordingly. My test app, for instance, grabs a block of HTML code from a server and present it in a UIWebView: “Special Offer! The Editor will buy you a pint if you present this code…”, that kind of thing. Essentially, you use the beacon zone entry event to tell the use her or she is close to something interesting.

Searching for a Beacon
Searching for an iBeacon… then it’s found

iOS scans for regions even when the app that initiated the monitoring isn’t running. The app is automatically run in the background if the beacon is detected in those circumstances. Likewise, it’s woken from sleep if it is merely napping. You can control whether messages triggered when beacon region boundaries are crossed are delayed while the iDevice’s screen is off: the CLBeaconRegion object created above has a Boolean property, notifyEntryStateOnDisplay, you can use to enable this behaviour. It also has a Boolean property called notifyOnEntry, inherited from CLBeaconRegion’s superclass CLRegion, which you’ll need to set to NO in this case.

Once the phone knows it’s inside a beacon’s sphere of influence, the app can call the - (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region method to get a list of nearby beacons – they’re stored in an array, the closest beacon first – and from each entry, a beacon’s UUID, Major and Minor values to help identify which they are and, thanks to each beacon’s proximity property, roughly how close it is: CLProximityUnknown, CLProximityImmediate, CLProximityNear or CLProximityFar.

To keep things tidy, I added a switch to disable beacon scanning. By way of inter-object notifications, it calls [appLocationManager stopMonitoringForRegion:beaconRegion] to take the currently defined beacon off the system-wide monitoring list and clear all the beacon data variables.

Once all this is up and running, and the Pi-hosted iBeacon is operating in the background, it’s easy to test the system by walking out of range of the beacon and then turning round and coming back.

Found a beacon
Back in the app, the UI changes to reflect where you are

Android users keen to try this out without coding their own beacon detector can check out Radius Networks’ iBeacon Locate app in Google Play. There’s an iOS version in iTunes too. Radius also has an open-source library of iBeacon compatibility code for Android if you want to incorporate iBeacon support into an app of your own.

An edited version of this post originally appeared in The Register.

4 thoughts on “How to build your own Apple iBeacon… with a Raspberry Pi

  1. Yogesh

    Hi Tony, This is a great article indeed.
    My question to you is – Why Caliberated Tx Power is always C5? Can it be configurable? AFAIK , Caliberated Tx Power is supposed to be the average RSSI measured one meter away from the beacon. And it will always depend on external factors like interference by other devices, people standing in line of sight etc.

    On a side note, I have written a sample android code to read iBeacon PDU. It is availabe at :
    https://github.com/kumarryogeshh/ReadBeacon

    1. smittytone Post author

      I never researched calibrated power, Yogesh, but you’re right, there’s no reason why the value needs to be fixed at C5. The tricky thing is to measure the power level so you can set an appropriate value.

Comments are closed.