This code is used as part of a BLE scavenger hunt game where multiple BLE beacons are scattered around an area, hidden. The user has to walk around and find them with their phone, collecting passphrases as they go from the server the beacons point to. Each beacon passes its MAC address in the query string to the server to uniqly identify it.

Dependencies:   BLE_API mbed nRF51822

Fork of BLE_URIBeacon by Bluetooth Low Energy

Intro

This code demonstrates one possible use of BLE URIBeacons. In this demo multiple beacons are loaded with the same piece of code. Each beacon will add its mac address to the query string to be sent to the server. This allows each board to be paired wtih unique information in the server database. In this instance a company ID and passphrase are associated with each beacon. This information is then displayed either in the notification tray on the phone or on the webpage when connected to.

Using it

To use the app please make sure the shortened URL in the mbed code points to a server running the server code (in this case we are providing Google App Engine codeas an example). When a board is first connected to the server the user will need assign it a company ID and a passphrase. On later connections to the server this information will be returned to the requesting device (usually a smartphone / tablet)

In short there are two phases of operation, setup and use.

Setup:

  1. make sure shortened url in mbed code points to app engine server running code
  2. load code to mbed enabled BLE board
  3. load app engine with provided code
  4. connect for first time to server via physical web app and register the device

Use:

  1. scan with physical web app
  2. uribeacon is found, companyID and passphrase are displayed in notification bar (alternatively can connect to webpage for same info)

Examples

This photo shows information from the server being shown in the notification drawer on android. There are 2 beacons shown, the first beacon is in phase 2: Use, it has been initialized on the server with a company name of 'Random company' and a passphrase of 'Wombats are awesome!!'. The other beacon is in phase 1: setup, and has not been initialized, so it displays the "please configure me" message. /media/uploads/mbedAustin/screenshot_2015-04-16-21-10-16-1-.png

Constraints

This example relies on passing along a query string '?q=" from the shortened url to the long url. Not all shortening services do this. We recommend using tiny.cc or snurl.com as they will pass along the '?q=.....' to the server. Currently the shortened URL in the example points to mbeduribeacon.appspot.com . The duration of the shortened URL is not guaranteed, so it may revert back to nothing in the future. Also the appspot server may go down in the future, thus we have provided the source code for both sides to the user.

This example also relies on the Physical Web app (available for iOS and Android). As of the date of this writing it works just fine, but since we at mbed do not control this app, this may change in the future.

Sometimes something will take a little time to buffer things, im not sure if its the google app engine or the proxy that URIBeacons are run through on the PhyscialWeb app. This means there may be up to a 20min delay between when you do the initial setup of the device and when it starts showing up correctly on your devices notification tray, but if you click through to the webpage it should work immediately after being setup.

Technical Details

This example works by forwarding the mac address of the device in the query string '?q=MACADDR' to the server. The server will return a webpage based on the mac address in the query string. Not all url shortening services do this, so we used snurl.com, because it does. The PhysicalWeb phone app will scan the beacon, ping the server, and display the MetaData (description, favicon, title, url) fields in the notification drawer and in the physical web app. This entire demo relies on the PhysicalWeb app to handle the phone side interaction.

Summary

This is a cool demo of how to use URIBeacons to facilitate connecting the physical and digital worlds. It is by no means an end all be all, but is just one way to use them. Go build something awesome!

Other things

This is the the google app engine code necessary to run this example. If you would like to run your own server you can sign up for a free app engine account and use this python code as your example code.

ServerCode.py

from google.appengine.api import users
import cgi

import webapp2

import pprint

register = {
	'test':{'companyid':'Awesomeness Inc.','passphrase':'wombats of the doom'},
}

ADD_PAGE_HTML = '''\
<html>
	<head>
		<title>mbed Powered Scavenger Hunt</title>
		<meta name="description" content="This device is not recognized. Please click to add device to database.">
	</head>
  <body>
  	<h2>This device is not recognized by the web server, please register it.</h2>
    <form action="/add" method="post">
      <div>Board:<textarea name="boardid">DEFAULTKEY</textarea></div>
      <div>CompanyID:<textarea name="companyid" rows="1" cols="60"></textarea></div>
      <div>passphrase<textarea name="passphrase" rows="1" cols="60"></textarea></div>
      <div><input type="submit" value="submit"></div>
    </form>
  </body>
</html>
'''

RESPONSE_PAGE_HTML = '''\
<html>
	<head>
		<title>mbed Powered Scavenger Hunt</title>
		<meta name="description" content="DEFAULTCOMPANY's password is 'DEFAULTVALUE'">
	</head>
	<body>
		<b>DEFAULTCOMPANY</b>'s password is '<i>DEFAULTVALUE</i>'

	</body>

</html>
'''

# main page checks dictionary 
#	if key exists display value
#	if key doesnt exist add it to dictionary
class MainPage(webapp2.RequestHandler):
	def get(self):
		x = self.request.get('q').lower()
		if x in register.keys():
			self.response.write(RESPONSE_PAGE_HTML.replace('DEFAULTVALUE',register[x]['passphrase']).replace('DEFAULTCOMPANY',register[x]['companyid']))
		else:
			self.response.write(ADD_PAGE_HTML.replace('DEFAULTKEY',x))


# the debug page prints out all key value pairs
class DebugPage(webapp2.RequestHandler):
	def get(self):
		pp = pprint.pformat(register,indent=6)
		self.response.write(pp)

# the add page takes a post message and adds the keys and values to the dictionary
class AddPage(webapp2.RequestHandler):
	def post(self):
		boardid   	= cgi.escape(self.request.get('boardid'))
		companyid 	= cgi.escape(self.request.get('companyid'))
		passphrase 	= cgi.escape(self.request.get('passphrase'))
		register[boardid] = {'passphrase':passphrase,'companyid':companyid}
		self.response.write("Added company:'<b>"+companyid+"</b>' with passphrase:'<i>"+passphrase+"</i>'")

application = webapp2.WSGIApplication(
	[
    	('/', MainPage),
    	('/debug',DebugPage),
    	('/add',AddPage),
], debug=True)
Committer:
mbedAustin
Date:
Thu Apr 16 20:27:05 2015 +0000
Revision:
21:3c518a637de6
Parent:
20:8f63cbf19f7f
Fixed mac address conversion issue

Who changed what in which revision?

UserRevisionLine numberNew contents of line
rgrover1 14:868a1207022d 1 /* mbed Microcontroller Library
rgrover1 14:868a1207022d 2 * Copyright (c) 2006-2013 ARM Limited
rgrover1 0:790a27ffc99b 3 *
rgrover1 0:790a27ffc99b 4 * Licensed under the Apache License, Version 2.0 (the "License");
rgrover1 0:790a27ffc99b 5 * you may not use this file except in compliance with the License.
rgrover1 0:790a27ffc99b 6 * You may obtain a copy of the License at
rgrover1 0:790a27ffc99b 7 *
rgrover1 13:b82d8db73633 8 * http://www.apache.org/licenses/LICENSE-2.0
rgrover1 0:790a27ffc99b 9 *
rgrover1 0:790a27ffc99b 10 * Unless required by applicable law or agreed to in writing, software
rgrover1 0:790a27ffc99b 11 * distributed under the License is distributed on an "AS IS" BASIS,
rgrover1 0:790a27ffc99b 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rgrover1 0:790a27ffc99b 13 * See the License for the specific language governing permissions and
rgrover1 0:790a27ffc99b 14 * limitations under the License.
rgrover1 0:790a27ffc99b 15 */
rgrover1 0:790a27ffc99b 16
rgrover1 0:790a27ffc99b 17 #include "mbed.h"
mbedAustin 20:8f63cbf19f7f 18 #include <string>
rgrover1 0:790a27ffc99b 19 #include "BLEDevice.h"
rgrover1 13:b82d8db73633 20 #include "URIBeaconConfigService.h"
rgrover1 11:c77cc2b74101 21 #include "DFUService.h"
rgrover1 11:c77cc2b74101 22 #include "DeviceInformationService.h"
rgrover1 16:1daa78939a3b 23 #include "ConfigParamsPersistence.h"
rgrover1 13:b82d8db73633 24
rgrover1 0:790a27ffc99b 25 BLEDevice ble;
rgrover1 13:b82d8db73633 26 URIBeaconConfigService *uriBeaconConfig;
rgrover1 13:b82d8db73633 27
rgrover1 17:e2c0a1696e39 28 /**
rgrover1 17:e2c0a1696e39 29 * URIBeaconConfig service can operate in two modes: a configuration mode which
rgrover1 17:e2c0a1696e39 30 * allows a user to update settings over a connection; and normal URIBeacon mode
rgrover1 17:e2c0a1696e39 31 * which involves advertising a URI. Constructing an object from URIBeaconConfig
rgrover1 17:e2c0a1696e39 32 * service sets up advertisements for the configuration mode. It is then up to
rgrover1 17:e2c0a1696e39 33 * the application to switch to URIBeacon mode based on some timeout.
rgrover1 17:e2c0a1696e39 34 *
rgrover1 17:e2c0a1696e39 35 * The following help with this switch.
rgrover1 17:e2c0a1696e39 36 */
mbedAustin 20:8f63cbf19f7f 37 static const int CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS = 5; // Duration after power-on that config service is available.
rgrover1 17:e2c0a1696e39 38 Ticker configAdvertisementTimeoutTicker;
rgrover1 17:e2c0a1696e39 39
rgrover1 17:e2c0a1696e39 40 /**
rgrover1 17:e2c0a1696e39 41 * Stop advertising the UriBeaconConfig Service after a delay; and switch to normal URIBeacon.
rgrover1 17:e2c0a1696e39 42 */
rgrover1 17:e2c0a1696e39 43 void timeout(void)
rgrover1 17:e2c0a1696e39 44 {
rgrover1 17:e2c0a1696e39 45 Gap::GapState_t state;
rgrover1 17:e2c0a1696e39 46 state = ble.getGapState();
rgrover1 17:e2c0a1696e39 47 if (!state.connected) { /* don't switch if we're in a connected state. */
rgrover1 17:e2c0a1696e39 48 uriBeaconConfig->setupURIBeaconAdvertisements();
rgrover1 17:e2c0a1696e39 49 ble.startAdvertising();
rgrover1 17:e2c0a1696e39 50
rgrover1 17:e2c0a1696e39 51 configAdvertisementTimeoutTicker.detach(); /* disable the callback from the timeout Ticker. */
rgrover1 17:e2c0a1696e39 52 }
rgrover1 17:e2c0a1696e39 53 }
rgrover1 17:e2c0a1696e39 54
rgrover1 17:e2c0a1696e39 55 /**
rgrover1 17:e2c0a1696e39 56 * Callback triggered upon a disconnection event. Needs to re-enable advertisements.
rgrover1 17:e2c0a1696e39 57 */
rgrover1 16:1daa78939a3b 58 void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
rgrover1 16:1daa78939a3b 59 {
rgrover1 6:31b65d4ea67d 60 ble.startAdvertising();
rgrover1 6:31b65d4ea67d 61 }
rgrover1 0:790a27ffc99b 62
rgrover1 0:790a27ffc99b 63 int main(void)
rgrover1 0:790a27ffc99b 64 {
rgrover1 0:790a27ffc99b 65 ble.init();
rgrover1 6:31b65d4ea67d 66 ble.onDisconnection(disconnectionCallback);
rgrover1 13:b82d8db73633 67
mbedAustin 20:8f63cbf19f7f 68 uint8_t mac[6] = {};
mbedAustin 20:8f63cbf19f7f 69 ble.getAddress(0,mac);
mbedAustin 20:8f63cbf19f7f 70
mbedAustin 20:8f63cbf19f7f 71 printf("MAC Address = ");
mbedAustin 20:8f63cbf19f7f 72 for(int x =0; x<7; x++) {
mbedAustin 20:8f63cbf19f7f 73 printf("%x",mac[x]);
mbedAustin 20:8f63cbf19f7f 74 }
mbedAustin 20:8f63cbf19f7f 75 printf("\n\r");
mbedAustin 20:8f63cbf19f7f 76
mbedAustin 21:3c518a637de6 77 // string url = "http://snurl.com/ub?q=" ;
mbedAustin 21:3c518a637de6 78 string url = "http://snurl.com/u6?q=" ;
mbedAustin 21:3c518a637de6 79 url += ((mac[0] & 0xF0) >> 4) + 'A';
mbedAustin 21:3c518a637de6 80 url += ((mac[0] & 0x0F) >> 0) + 'A';
mbedAustin 21:3c518a637de6 81 url += ((mac[1] & 0xF0) >> 4) + 'A';
mbedAustin 21:3c518a637de6 82 url += ((mac[1] & 0x0F) >> 0) + 'A';
mbedAustin 21:3c518a637de6 83 url += ((mac[2] & 0xF0) >> 4) + 'A';
mbedAustin 21:3c518a637de6 84 url += ((mac[2] & 0x0F) >> 0) + 'A';
mbedAustin 21:3c518a637de6 85 url += ((mac[3] & 0xF0) >> 4) + 'A';
mbedAustin 21:3c518a637de6 86 url += ((mac[3] & 0x0F) >> 0) + 'A';
mbedAustin 21:3c518a637de6 87 url += ((mac[4] & 0xF0) >> 4) + 'A';
mbedAustin 21:3c518a637de6 88 url += ((mac[4] & 0x0F) >> 0) + 'A';
mbedAustin 21:3c518a637de6 89
mbedAustin 20:8f63cbf19f7f 90 for(int y=0; y<6; y++) {
mbedAustin 21:3c518a637de6 91 printf("\n\rmac[%d]=0x%x, d%d, c%c,modH=%c, modL=%c",y,mac[y],mac[y],mac[y],((mac[y] & 0xF0) >> 4) + 'A',((mac[y] & 0x0F) >> 0) + 'A');
mbedAustin 20:8f63cbf19f7f 92 }
mbedAustin 20:8f63cbf19f7f 93 // printf("\n\r0x%x->%c, 0x%x->%c\n\r%s\n\r",mac[4],(mac[4]%(122-32))+32,mac[5],(mac[5]%(122-32))+32,url);
mbedAustin 20:8f63cbf19f7f 94 printf("\n\rurl = %s\n\r",url);
mbedAustin 20:8f63cbf19f7f 95
rgrover1 16:1daa78939a3b 96 /*
rgrover1 16:1daa78939a3b 97 * Load parameters from (platform specific) persistent storage. Parameters
rgrover1 16:1daa78939a3b 98 * can be set to non-default values while the URIBeacon is in configuration
rgrover1 16:1daa78939a3b 99 * mode (within the first 60 seconds of power-up). Thereafter, parameters
rgrover1 16:1daa78939a3b 100 * get copied out to persistent storage before switching to normal URIBeacon
rgrover1 16:1daa78939a3b 101 * operation.
rgrover1 16:1daa78939a3b 102 */
rgrover1 16:1daa78939a3b 103 URIBeaconConfigService::Params_t params;
rgrover1 17:e2c0a1696e39 104 bool fetchedFromPersistentStorage = loadURIBeaconConfigParams(&params);
rgrover1 13:b82d8db73633 105
rgrover1 16:1daa78939a3b 106 /* Initialize a URIBeaconConfig service providing config params, default URI, and power levels. */
rgrover1 16:1daa78939a3b 107 static URIBeaconConfigService::PowerLevels_t defaultAdvPowerLevels = {-20, -4, 0, 10}; // Values for ADV packets related to firmware levels
mbedAustin 20:8f63cbf19f7f 108 uriBeaconConfig = new URIBeaconConfigService(ble, params, !fetchedFromPersistentStorage, (const char*)&url[0], defaultAdvPowerLevels);
rgrover1 13:b82d8db73633 109 if (!uriBeaconConfig->configuredSuccessfully()) {
rgrover1 6:31b65d4ea67d 110 error("failed to accommodate URI");
rgrover1 6:31b65d4ea67d 111 }
rgrover1 17:e2c0a1696e39 112 configAdvertisementTimeoutTicker.attach(timeout, CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS);
rgrover1 0:790a27ffc99b 113
rgrover1 13:b82d8db73633 114 // Setup auxiliary services to allow over-the-air firmware updates, etc
rgrover1 13:b82d8db73633 115 DFUService dfu(ble);
rgrover1 16:1daa78939a3b 116 DeviceInformationService deviceInfo(ble, "ARM", "UriBeacon", "SN1", "hw-rev1", "fw-rev1", "soft-rev1");
rgrover1 11:c77cc2b74101 117
rgrover1 16:1daa78939a3b 118 ble.startAdvertising(); /* Set the whole thing in motion. After this call a GAP central can scan the URIBeaconConfig
rgrover1 18:569257e0af4e 119 * service. This can then be switched to the normal URIBeacon functionality after a timeout. */
rgrover1 0:790a27ffc99b 120
mbedAustin 20:8f63cbf19f7f 121
rgrover1 0:790a27ffc99b 122 while (true) {
rgrover1 0:790a27ffc99b 123 ble.waitForEvent();
rgrover1 0:790a27ffc99b 124 }
rgrover1 0:790a27ffc99b 125 }