This page show some code samples to retrieve the real-time location of a BLE device using the Bluetooth Beacon Tracker API. To run these examples you need:
- a set of Accuware credentials (username and password).
- the SiteID.
- the pMAC of the BLE device registered with your Accuware site.
Objective-C
Source code
NSString *site_id = @"0000"; NSString *station_mac = @"00:00:00:00:00:00"; NSURLCredential *credential = [NSURLCredential credentialWithUser: @"username" password: @"password" persistence: NSURLCredentialPersistenceForSession]; NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost: @"its.accuware.com" port: 80 protocol: @"http" realm: @"Bluetooth Beacon Tracker" authenticationMethod: NSURLAuthenticationMethodHTTPBasic]; [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential: credential forProtectionSpace: protectionSpace]; [protectionSpace release]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"https://its.accuware.com/api/v1/sites/%@/stations/%@/", site_id, station_mac]]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL: url]; NSURLResponse *response = nil; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error]; NSLog(@"Station: %@", [jsonObj objectForKey:@"mac"]); NSLog(@"loc.lat: %.6f", [[[jsonObj objectForKey: @"loc"] objectForKey: @"lat"] doubleValue]); NSLog(@"loc.lng: %.6f", [[[jsonObj objectForKey: @"loc"] objectForKey: @"lng"] doubleValue]);
Java
The Restlet framework provides a convenient access the API from Java. Download the Java SE edition archive and extracts the files in a directory of your choice.
Locate and add to your CLASSPATH the following JAR files:
org.restlet.jar org.restlet.ext.json.jar org.json.jar
Source Code
import org.json.JSONObject;
import org.restlet.data.ChallengeScheme;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.resource.ClientResource;
public class ItsClient {
private final static String BASE_URL = "https://its.accuware.com/api/v1/";
private final static String SITE_ID = "0000"; // Your site ID here
private final static String STATION_MAC = "00:00:00:00:00:00"; // The station's MAC address
private final static String USERNAME = "username"; // Your username
private final static String PASSWORD = "password"; // Your password
public static void main(String[] args) throws Exception {
// Set the request parameters
String url = BASE_URL + "sites/" + SITE_ID + "/stations/" + STATION_MAC + "/";
ClientResource itsClient = new ClientResource(url);
itsClient.setChallengeResponse(ChallengeScheme.HTTP_BASIC, USERNAME, PASSWORD);
// Retrieve and parse the JSON representation
JsonRepresentation jsonRep = new JsonRepresentation(itsClient.get());
JSONObject jsonObj = jsonRep.getJsonObject();
// Output results
System.out.printf("Station: %s\n", jsonObj.getString("mac"));
System.out.printf("loc.lat: %.6f\n", jsonObj.getJSONObject("loc").getDouble("lat"));
System.out.printf("loc.lng: %.6f\n", jsonObj.getJSONObject("loc").getDouble("lng"));
}
}
C#
The C# example uses JSON.NET to parse the response. The library is available at json.codeplex.com.
Source Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
namespace ItsClient
{
class Program
{
private const string BASE_URL = "https://its.accuware.com/api/v1/";
private const string SITE_ID = "0000"; // Your site ID here
private const string STATION_MAC = "00:00:00:00:00:00"; // The station's MAC address
private const string USERNAME = "username"; // Your username
private const string PASSWORD = "password"; // Your password
static void Main(string[] args)
{
// Set the request parameters
string url = BASE_URL + "sites/" + SITE_ID + "/stations/" + STATION_MAC + "/";
HttpWebRequest webreq = (HttpWebRequest)System.Net.HttpWebRequest.Create(url);
string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(USERNAME + ":" + PASSWORD));
webreq.Headers["Authorization"] = "Basic " + authInfo;
// Retrieve and parse the JSON representation
StreamReader strReader = new StreamReader(webreq.GetResponse().GetResponseStream());
String response = strReader.ReadToEnd();
JObject jsonObj = JObject.Parse(response);
// Output results
Console.Out.WriteLine("Station: " + (string) jsonObj["mac"]);
Console.Out.WriteLine("loc.lat: " + (double) (jsonObj["loc"])["lat"]);
Console.Out.WriteLine("loc.lng: " + (double) (jsonObj["loc"])["lng"]);
}
}
}
Ruby
This example uses the JSON library for Ruby available as a gem:
gem install json
Source Code
require 'rubygems'
require 'json'
require 'net/http'
SERVER = 'its.accuware.com'
SITE_ID = '0000' # Your site ID here
STATION_MAC = '00:00:00:00:00:00' # The station's MAC address
USERNAME = 'username' # Your username
PASSWORD = 'password' # Your password
Net::HTTP.start(SERVER) {|http|
# Set the request parameters
req = Net::HTTP::Get.new("/api/v1/sites/#{SITE_ID}/stations/#{STATION_MAC}/")
req.basic_auth USERNAME, PASSWORD
# Retrieve and parse the JSON representation
response = http.request(req)
obj = JSON.parse(response.body)
# Output the results
puts "Station: #{obj['mac']}"
puts "loc.lat: #{obj['loc']['lat']}"
puts "loc.lng: #{obj['loc']['lng']}"
}
HTML/Javascript
The source code for the Base 64 library is available at this page. To run this example save the code in a file named Base64.js in the same directory as the HTML file below.
Source Code
<!DOCTYPE html>
<html>
<head>
<title>Bluetooth Beacon Tracker Javascript Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="Base64.js"></script>
</head>
<body>
<h1>Bluetooth Beacon Tracker Javascript Example</h1>
<div id="results"></div>
<script type="text/javascript">
$(document).ready(function() {
var BASE_URL = "https://its.accuware.com/api/v1/",
SITE_ID = "0000", // Your site ID here
STATION_MAC = "00:00:00:00:00:00", // The station's MAC address
USERNAME = "username", // Your username
PASSWORD = "password"; // Your password
// Send the request
jQuery.support.cors = true; // enable cross-site scripting
$.ajax({
type: "GET",
url: BASE_URL + "sites/" + SITE_ID + "/stations/" + STATION_MAC + "/",
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(station) {
// Output the results
if (typeof station === "string") {
station = JSON.parse(station);
}
$("#results").html(
"Station: " + station.mac + "<br />" +
"loc.lat: " + station.loc.lat + "<br />" +
"loc.lng: " + station.loc.lng + "<br />"
);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
});
</script>
</body>
</html>