SlideShare a Scribd company logo
Howdy, I’m Blaine Carter
Oracle Corpora on
Developer Advocate for Open Source
Email: blaine.carter@oracle.com
Blog: learncodeshare.net
Twi er: @OraBlaineOS
YouTube: www.youtube.com/blainecarter
Team: community.oracle.com/docs/DOC-917690
Beacon Tracking on a Budget
Bluetooth Low Energy Beacon
Typical broadcast data:
Major: 4
Minor: 6597
UUID: 6b12c4274890
RSSI: -81
TX: -59
Calculate the distance to the beacon using tx and rssi
h ps://stackoverflow.com/a/20434019/1296150
function calculateDistance(uuid, rssi) {
var txPower = -59;
var distance;
if (rssi === 0) {
return -1.0;
}
var ratio = rssi * 1.0 / txPower;
if (ratio < 1.0) {
distance = Math.pow(ratio, 10);
} else {
distance = (0.89976) * Math.pow(ratio, 7.7095) + 0.111;
}
Rolling Average
var distanceQueues = {}; //Stored outside of the function
if (distanceQueues.hasOwnProperty(uuid) === false) {
distanceQueues[uuid] = (Array.apply(null, Array(5)))
.map(function() {return distance;});
} else {
distanceQueues[uuid].push(distance);
distanceQueues[uuid].shift();
}
{
"0d60a289203": [2.3, 2.5, 2.1, 2.4, 2.4],
"5a364a32456c": [1.7, 2.5, 1.6, 1.8, 1.4]
}
Weighted Average
NormalAverage:
WeightedAverage:
...
var sum = 0;
var weight = 0;
for (var i = 0; i < distanceQueues[uuid].length; i++) {
sum += (i + 1) * distanceQueues[uuid][i];
weight += i + 1;
}
var avg = sum / weight;
return avg;
}
= 3.4
(3 + 4 + 3 + 5 + 2)
5
= 3.3
((0 + 1) ∗ 3 + (1 + 1) ∗ 4 + (1 + 2) ∗ 3 + (1 + 3) ∗ 5 + (1 + 4) ∗ 2)
((0 + 1) + (1 + 1) + (1 + 2) + (1 + 3) + (1 + 4))
Install Raspbian using Etcher
Enable SSH
touch /boot/ssh
Authorize an RSA Key
Add your key to ~/.ssh/authorized_keys
install -d -m 700 /rootfs/home/pi/.ssh
cat ~/.ssh/id_rsa.pub >> /rootfs/home/pi/.ssh/authorized_keys
Setup WIFI
Edit /roo s/etc/wpa_supplicant/wpa_supplicant.conf
network={
ssid="Your SSID"
psk="YourWPAPassword"
key_mgmt=WPA-PSK
}
Update Raspbian
1. Put the SD card in your Raspberry Pi
2. Boot it up
3. SSH to pi
4. Change password (default password: raspberry)
5. Run an update
ssh pi@192.168.0.2
passwd
sudo apt-get update
Install Bluetooth Libraries
sudo apt-get install -y bluetooth bluez libbluetooth-dev libudev-dev
Install Node.js
Remove pre-installed Node (if any)
Node Version Manager
sudo apt-get remove --purge npm node nodejs
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
source .bashrc
nvm install node
node -v
npm -v
Allow Node to access bluetooth
sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
Setup Environment Variables
SCANNER_ID – The ID for this scanner.
BEACON_UUID – UUID of the beacon you’re tracking.
IFTTT_KEY – your account key for IFTTT
ORDS_URI – http://example.com/ords/beacon/beacon/alert/
Scan For a Beacon
var bu = require('./beaconUtil.js');
var bleacon = require('bleacon');
var beaconId = process.env.BEACON_UUID;
bleacon.startScanning(beaconId);
bleacon.on('discover', function(bleacon) {
var uuid = bleacon.uuid,
major = bleacon.major,
minor = bleacon.minor,
rssi = bleacon.rssi,
accuracy = bleacon.accuracy.toFixed(2),
proximity = bleacon.proximity,
distance = 0;
distance = bu.calculateDistance(uuid, rssi).toFixed(2);
console.log("UUID: " + uuid + "nMajor:" + major + "nMinor:" + minor +
"nrssi:" + bleacon.rssi + "naccuracy:" + accuracy +
"nProximity:" + proximity + "nDistance:" + distance + "nn");
});
Trigger an Ac on
var bu = require('./beaconUtil.js');
var bleacon = require('bleacon');
var beaconId = process.env.BEACON_UUID;
var scannerID = process.env.SCANNER_ID;
bleacon.startScanning(process.env.BEACON_UUID);
bleacon.on('discover', function(bleacon) {
var uuid = bleacon.uuid,
major = bleacon.major,
minor = bleacon.minor,
rssi = bleacon.rssi,
accuracy = bleacon.accuracy.toFixed(2),
proximity = bleacon.proximity,
distance = 0;
distance = bu.calculateDistance(bleacon.uuid, bleacon.rssi).toFixed(2);
//Process the alert action
if (distance < 2) {
bu.iftttNotify('LeftRoom', scannerID, beaconId, distance);
}
});
Home Automa on
Messages - IFTTT (If This Then That) - h ps://i .com
Home Assistant - h ps://home-assistant.io
Deadbolt
Sonos
Oracle REST Data Services
begin
ords.enable_schema(
p_enabled => true,
p_schema => 'BEACON',
p_url_mapping_type => 'BASE_PATH',
p_url_mapping_pattern => 'beacon',
p_auto_rest_auth => false);
ords.define_module(
p_module_name => 'Beacon',
p_base_path => '/beacon/',
p_items_per_page => 25,
p_status => 'PUBLISHED');
ords.define_template(
p_module_name => 'Beacon',
p_pattern => 'scan',
p_priority => 0,
p_etag_type => 'HASH',
p_etag_query => null);
ords.define_handler(
p_module_name => 'Beacon',
p_pattern => 'scan',
p_method => 'GET',
p_source_type => 'json/query',
p_items_per_page => 25,
p_mimes_allowed => '',
p_source => 'select *
from reading
order by created_on');
commit;
end;
Consume Rest API
var bu = require('./beaconUtil.js');
var bleacon = require('bleacon');
var beaconId = process.env.BEACON_UUID;
var scannerID = process.env.SCANNER_ID;
var request = require('request');
var ordsUri = process.env.ORDS_URI;
//get the alerts for this scanner
var alerts = [];
request.get({
url: ordsUri + 'alert/' + scannerID,
json: true
}, function(err, res, body) {
if (err) {
console.log(err);
}
alerts = body;
bleacon.startScanning(process.env.BEACON_UUID);
console.log('Scanning:', alerts);
});
bleacon.on('discover', function(bleacon) {
var uuid = bleacon.uuid,
major = bleacon.major,
minor = bleacon.minor,
i bl i
My beaconScan Repository
h ps://github.com/bcarter/beaconScan
There's more we could do
What if you want to map the beacon loca on?
Table Data
scanner_id beacon_id distance created_on
5 myBeacon 4.72 27-AUG-1704.19.58.082247PM
7 myBeacon 6.57 27-AUG-1704.19.58.780495PM
6 myBeacon 4.64 27-AUG-1704.19.58.780855PM
7 myBeacon 5.84 27-AUG-1704.19.59.270639PM
6 myBeacon 4.8 27-AUG-1704.19.59.279716PM
5 myBeacon 4.8 27-AUG-1704.19.59.489140PM
7 myBeacon 6.65 27-AUG-1704.19.59.538878PM
5 myBeacon 5.36 27-AUG-1704.20.00.187193PM
6 myBeacon 4.71 27-AUG-1704.20.00.239919PM
6 myBeacon 3.95 27-AUG-1704.20.00.240297PM
7 myBeacon 6.41 27-AUG-1704.20.00.908366PM
5 myBeacon 5.12 27-AUG-1704.20.00.949043PM
6 myBeacon 4.21 27-AUG-1704.20.01.072711PM
7 myBeacon 5.92 27-AUG-1704.20.01.630422PM
7 myBeacon 6.85 27-AUG-1704.20.01.667588PM
6 myBeacon 4.69 27-AUG-1704.20.02.347791PM
5 myBeacon 5.5 27-AUG-1704.20.02.348201PM
7 myBeacon 5.88 27-AUG-1704.20.02.349190PM
Round to the nearest X
Round mestamps to the nearest 5 seconds
1. (cast(created_on as date) - date '1970-01-01')
2. *24*60*60
3. round((...)/5)
4. * 5
h ps://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:13946369553642
select round(((cast(created_on as date) - date '1970-01-01')
*24*60*60)
/5)
* 5
from reading
order by 2;
Trilatera on
(d,0)
(0,0)
(i,j)
r1
d
r2
P2P1
P3
r3
i
j
Intersections
x positive
right
y positive
down
Scanning with Raspberry Pi
Raspberry Pi Zero W
Raspberry Pi Zero W
Raspberry Pi 3
Oracle Spa al
sdo_geometry OBJECT (SDO_GTYPE NUMBER,
SDO_SRID NUMBER,
SDO_POINT SDO_POINT_TYPE,
SDO_ELEM_INFO SDO_ELEM_INFO_ARRAY,
SDO_ORDINATES SDO_ORDINATE_ARRAY);
sdo_geometry(2003,
null,
null,
mdsys.sdo_elem_info_array(1, 1003, 3),
mdsys.sdo_ordinate_array(x,y,
x,y))
Draw a circle using x, y, radius
Convert x, y + radius into 3 points on the circle
mdsys.sdo_geometry(
2003,
null,
null,
mdsys.sdo_elem_info_array(1, 1003, 4),
mdsys.sdo_ordinate_array(
(x - rad), y,
x, (y + rad),
(x + rad), y
));
Intersec ng Polygons
SDO_GEOM.SDO_INTERSECTION(sdo_geometry(2003, null, null,
mdsys.sdo_elem_info_array(1, 1003, 3),
mdsys.sdo_ordinate_array(0,0, 10,10)),
beacon_tools.circle(0, 0, 5),
0.005)
Beacon Enters a Pre-Defined Zone
Define zones using polygons.
select zone
from restricted_areas
where SDO_OVERLAPBDYINTERSECT(zone,
beacon_tools.location('beacon1','someTimestamp'));
Recap
Bluetooth Beacon Tracking on a Budget

More Related Content

What's hot

Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
Sages
 
Monitoring with Syslog and EventMachine (RailswayConf 2012)
Monitoring  with  Syslog and EventMachine (RailswayConf 2012)Monitoring  with  Syslog and EventMachine (RailswayConf 2012)
Monitoring with Syslog and EventMachine (RailswayConf 2012)
Wooga
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
Jeff Smith
 

What's hot (20)

Profiling & Testing with Spark
Profiling & Testing with SparkProfiling & Testing with Spark
Profiling & Testing with Spark
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and Scheduling
 
NodeJs
NodeJsNodeJs
NodeJs
 
More than syntax
More than syntaxMore than syntax
More than syntax
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
Leveraging Hadoop for Legacy Systems
Leveraging Hadoop for Legacy SystemsLeveraging Hadoop for Legacy Systems
Leveraging Hadoop for Legacy Systems
 
Kernel Recipes 2015: Introduction to Kernel Power Management
Kernel Recipes 2015: Introduction to Kernel Power ManagementKernel Recipes 2015: Introduction to Kernel Power Management
Kernel Recipes 2015: Introduction to Kernel Power Management
 
Winform
WinformWinform
Winform
 
JPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APIJPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream API
 
Monitoring with Syslog and EventMachine (RailswayConf 2012)
Monitoring  with  Syslog and EventMachine (RailswayConf 2012)Monitoring  with  Syslog and EventMachine (RailswayConf 2012)
Monitoring with Syslog and EventMachine (RailswayConf 2012)
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
KubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume PluginsKubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume Plugins
 
Using docker for data science - part 2
Using docker for data science - part 2Using docker for data science - part 2
Using docker for data science - part 2
 
QCon 2015 Broken Performance Tools
QCon 2015 Broken Performance ToolsQCon 2015 Broken Performance Tools
QCon 2015 Broken Performance Tools
 
Using python and docker for data science
Using python and docker for data scienceUsing python and docker for data science
Using python and docker for data science
 
Parallel Computing With Dask - PyDays 2017
Parallel Computing With Dask - PyDays 2017Parallel Computing With Dask - PyDays 2017
Parallel Computing With Dask - PyDays 2017
 
Petascale Genomics (Strata Singapore 20151203)
Petascale Genomics (Strata Singapore 20151203)Petascale Genomics (Strata Singapore 20151203)
Petascale Genomics (Strata Singapore 20151203)
 
Tracing Parallel Execution (UKOUG 2006)
Tracing Parallel Execution (UKOUG 2006)Tracing Parallel Execution (UKOUG 2006)
Tracing Parallel Execution (UKOUG 2006)
 
ZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 Version
 

Similar to Bluetooth Beacon Tracking on a Budget

Similar to Bluetooth Beacon Tracking on a Budget (20)

Real World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js ApplicationsReal World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js Applications
 
Deep dive in container service discovery
Deep dive in container service discoveryDeep dive in container service discovery
Deep dive in container service discovery
 
AWS Study Group - Chapter 03 - Elasticity and Scalability Concepts [Solution ...
AWS Study Group - Chapter 03 - Elasticity and Scalability Concepts [Solution ...AWS Study Group - Chapter 03 - Elasticity and Scalability Concepts [Solution ...
AWS Study Group - Chapter 03 - Elasticity and Scalability Concepts [Solution ...
 
Prometheus on EKS
Prometheus on EKSPrometheus on EKS
Prometheus on EKS
 
Securing Prometheus exporters using HashiCorp Vault
Securing Prometheus exporters using HashiCorp VaultSecuring Prometheus exporters using HashiCorp Vault
Securing Prometheus exporters using HashiCorp Vault
 
Eddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All ObjectsEddystone Beacons - Physical Web - Giving a URL to All Objects
Eddystone Beacons - Physical Web - Giving a URL to All Objects
 
Giving a URL to All Objects using Beacons²
Giving a URL to All Objects using Beacons²Giving a URL to All Objects using Beacons²
Giving a URL to All Objects using Beacons²
 
Open stack pike-devstack-tutorial
Open stack pike-devstack-tutorialOpen stack pike-devstack-tutorial
Open stack pike-devstack-tutorial
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Couch to OpenStack: Nova - July, 30, 2013
Couch to OpenStack: Nova - July, 30, 2013Couch to OpenStack: Nova - July, 30, 2013
Couch to OpenStack: Nova - July, 30, 2013
 
Kubernetes internals (Kubernetes 해부하기)
Kubernetes internals (Kubernetes 해부하기)Kubernetes internals (Kubernetes 해부하기)
Kubernetes internals (Kubernetes 해부하기)
 
k8s practice 2023.pptx
k8s practice 2023.pptxk8s practice 2023.pptx
k8s practice 2023.pptx
 
Keep it simple web development stack
Keep it simple web development stackKeep it simple web development stack
Keep it simple web development stack
 
OpenStack API's and WSGI
OpenStack API's and WSGIOpenStack API's and WSGI
OpenStack API's and WSGI
 
OSGi and Eclipse RCP
OSGi and Eclipse RCPOSGi and Eclipse RCP
OSGi and Eclipse RCP
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUN
 
Easy Cloud Native Transformation using HashiCorp Nomad
Easy Cloud Native Transformation using HashiCorp NomadEasy Cloud Native Transformation using HashiCorp Nomad
Easy Cloud Native Transformation using HashiCorp Nomad
 
Alexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for DevelopersAlexander Reelsen - Seccomp for Developers
Alexander Reelsen - Seccomp for Developers
 
Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016Salesforce at Stacki Atlanta Meetup February 2016
Salesforce at Stacki Atlanta Meetup February 2016
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Recently uploaded (20)

Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 

Bluetooth Beacon Tracking on a Budget

  • 1. Howdy, I’m Blaine Carter Oracle Corpora on Developer Advocate for Open Source Email: blaine.carter@oracle.com Blog: learncodeshare.net Twi er: @OraBlaineOS YouTube: www.youtube.com/blainecarter Team: community.oracle.com/docs/DOC-917690
  • 3. Bluetooth Low Energy Beacon Typical broadcast data: Major: 4 Minor: 6597 UUID: 6b12c4274890 RSSI: -81 TX: -59
  • 4. Calculate the distance to the beacon using tx and rssi h ps://stackoverflow.com/a/20434019/1296150 function calculateDistance(uuid, rssi) { var txPower = -59; var distance; if (rssi === 0) { return -1.0; } var ratio = rssi * 1.0 / txPower; if (ratio < 1.0) { distance = Math.pow(ratio, 10); } else { distance = (0.89976) * Math.pow(ratio, 7.7095) + 0.111; } Rolling Average var distanceQueues = {}; //Stored outside of the function if (distanceQueues.hasOwnProperty(uuid) === false) { distanceQueues[uuid] = (Array.apply(null, Array(5))) .map(function() {return distance;}); } else { distanceQueues[uuid].push(distance); distanceQueues[uuid].shift(); } { "0d60a289203": [2.3, 2.5, 2.1, 2.4, 2.4], "5a364a32456c": [1.7, 2.5, 1.6, 1.8, 1.4] }
  • 5. Weighted Average NormalAverage: WeightedAverage: ... var sum = 0; var weight = 0; for (var i = 0; i < distanceQueues[uuid].length; i++) { sum += (i + 1) * distanceQueues[uuid][i]; weight += i + 1; } var avg = sum / weight; return avg; } = 3.4 (3 + 4 + 3 + 5 + 2) 5 = 3.3 ((0 + 1) ∗ 3 + (1 + 1) ∗ 4 + (1 + 2) ∗ 3 + (1 + 3) ∗ 5 + (1 + 4) ∗ 2) ((0 + 1) + (1 + 1) + (1 + 2) + (1 + 3) + (1 + 4)) Install Raspbian using Etcher
  • 7. Add your key to ~/.ssh/authorized_keys install -d -m 700 /rootfs/home/pi/.ssh cat ~/.ssh/id_rsa.pub >> /rootfs/home/pi/.ssh/authorized_keys Setup WIFI Edit /roo s/etc/wpa_supplicant/wpa_supplicant.conf network={ ssid="Your SSID" psk="YourWPAPassword" key_mgmt=WPA-PSK }
  • 8. Update Raspbian 1. Put the SD card in your Raspberry Pi 2. Boot it up 3. SSH to pi 4. Change password (default password: raspberry) 5. Run an update ssh pi@192.168.0.2 passwd sudo apt-get update Install Bluetooth Libraries sudo apt-get install -y bluetooth bluez libbluetooth-dev libudev-dev
  • 9. Install Node.js Remove pre-installed Node (if any) Node Version Manager sudo apt-get remove --purge npm node nodejs curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash source .bashrc nvm install node node -v npm -v Allow Node to access bluetooth sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)
  • 10. Setup Environment Variables SCANNER_ID – The ID for this scanner. BEACON_UUID – UUID of the beacon you’re tracking. IFTTT_KEY – your account key for IFTTT ORDS_URI – http://example.com/ords/beacon/beacon/alert/ Scan For a Beacon var bu = require('./beaconUtil.js'); var bleacon = require('bleacon'); var beaconId = process.env.BEACON_UUID;
  • 11. bleacon.startScanning(beaconId); bleacon.on('discover', function(bleacon) { var uuid = bleacon.uuid, major = bleacon.major, minor = bleacon.minor, rssi = bleacon.rssi, accuracy = bleacon.accuracy.toFixed(2), proximity = bleacon.proximity, distance = 0; distance = bu.calculateDistance(uuid, rssi).toFixed(2); console.log("UUID: " + uuid + "nMajor:" + major + "nMinor:" + minor + "nrssi:" + bleacon.rssi + "naccuracy:" + accuracy + "nProximity:" + proximity + "nDistance:" + distance + "nn"); }); Trigger an Ac on var bu = require('./beaconUtil.js'); var bleacon = require('bleacon'); var beaconId = process.env.BEACON_UUID; var scannerID = process.env.SCANNER_ID; bleacon.startScanning(process.env.BEACON_UUID); bleacon.on('discover', function(bleacon) { var uuid = bleacon.uuid, major = bleacon.major, minor = bleacon.minor, rssi = bleacon.rssi, accuracy = bleacon.accuracy.toFixed(2), proximity = bleacon.proximity, distance = 0; distance = bu.calculateDistance(bleacon.uuid, bleacon.rssi).toFixed(2); //Process the alert action if (distance < 2) { bu.iftttNotify('LeftRoom', scannerID, beaconId, distance); } });
  • 12. Home Automa on Messages - IFTTT (If This Then That) - h ps://i .com Home Assistant - h ps://home-assistant.io Deadbolt Sonos Oracle REST Data Services begin ords.enable_schema( p_enabled => true, p_schema => 'BEACON', p_url_mapping_type => 'BASE_PATH', p_url_mapping_pattern => 'beacon', p_auto_rest_auth => false); ords.define_module( p_module_name => 'Beacon', p_base_path => '/beacon/', p_items_per_page => 25, p_status => 'PUBLISHED'); ords.define_template( p_module_name => 'Beacon', p_pattern => 'scan', p_priority => 0, p_etag_type => 'HASH', p_etag_query => null); ords.define_handler( p_module_name => 'Beacon', p_pattern => 'scan', p_method => 'GET', p_source_type => 'json/query', p_items_per_page => 25,
  • 13. p_mimes_allowed => '', p_source => 'select * from reading order by created_on'); commit; end; Consume Rest API var bu = require('./beaconUtil.js'); var bleacon = require('bleacon'); var beaconId = process.env.BEACON_UUID; var scannerID = process.env.SCANNER_ID; var request = require('request'); var ordsUri = process.env.ORDS_URI; //get the alerts for this scanner var alerts = []; request.get({ url: ordsUri + 'alert/' + scannerID, json: true }, function(err, res, body) { if (err) { console.log(err); } alerts = body; bleacon.startScanning(process.env.BEACON_UUID); console.log('Scanning:', alerts); }); bleacon.on('discover', function(bleacon) { var uuid = bleacon.uuid, major = bleacon.major, minor = bleacon.minor, i bl i My beaconScan Repository h ps://github.com/bcarter/beaconScan
  • 14. There's more we could do What if you want to map the beacon loca on? Table Data scanner_id beacon_id distance created_on 5 myBeacon 4.72 27-AUG-1704.19.58.082247PM 7 myBeacon 6.57 27-AUG-1704.19.58.780495PM
  • 15. 6 myBeacon 4.64 27-AUG-1704.19.58.780855PM 7 myBeacon 5.84 27-AUG-1704.19.59.270639PM 6 myBeacon 4.8 27-AUG-1704.19.59.279716PM 5 myBeacon 4.8 27-AUG-1704.19.59.489140PM 7 myBeacon 6.65 27-AUG-1704.19.59.538878PM 5 myBeacon 5.36 27-AUG-1704.20.00.187193PM 6 myBeacon 4.71 27-AUG-1704.20.00.239919PM 6 myBeacon 3.95 27-AUG-1704.20.00.240297PM 7 myBeacon 6.41 27-AUG-1704.20.00.908366PM 5 myBeacon 5.12 27-AUG-1704.20.00.949043PM 6 myBeacon 4.21 27-AUG-1704.20.01.072711PM 7 myBeacon 5.92 27-AUG-1704.20.01.630422PM 7 myBeacon 6.85 27-AUG-1704.20.01.667588PM 6 myBeacon 4.69 27-AUG-1704.20.02.347791PM 5 myBeacon 5.5 27-AUG-1704.20.02.348201PM 7 myBeacon 5.88 27-AUG-1704.20.02.349190PM Round to the nearest X Round mestamps to the nearest 5 seconds 1. (cast(created_on as date) - date '1970-01-01') 2. *24*60*60 3. round((...)/5) 4. * 5 h ps://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:13946369553642 select round(((cast(created_on as date) - date '1970-01-01') *24*60*60) /5) * 5 from reading order by 2;
  • 17. Raspberry Pi Zero W Raspberry Pi Zero W
  • 19. Oracle Spa al sdo_geometry OBJECT (SDO_GTYPE NUMBER, SDO_SRID NUMBER, SDO_POINT SDO_POINT_TYPE, SDO_ELEM_INFO SDO_ELEM_INFO_ARRAY, SDO_ORDINATES SDO_ORDINATE_ARRAY); sdo_geometry(2003, null, null, mdsys.sdo_elem_info_array(1, 1003, 3), mdsys.sdo_ordinate_array(x,y, x,y))
  • 20. Draw a circle using x, y, radius Convert x, y + radius into 3 points on the circle mdsys.sdo_geometry( 2003, null, null, mdsys.sdo_elem_info_array(1, 1003, 4), mdsys.sdo_ordinate_array( (x - rad), y, x, (y + rad), (x + rad), y )); Intersec ng Polygons
  • 21. SDO_GEOM.SDO_INTERSECTION(sdo_geometry(2003, null, null, mdsys.sdo_elem_info_array(1, 1003, 3), mdsys.sdo_ordinate_array(0,0, 10,10)), beacon_tools.circle(0, 0, 5), 0.005) Beacon Enters a Pre-Defined Zone Define zones using polygons. select zone from restricted_areas where SDO_OVERLAPBDYINTERSECT(zone, beacon_tools.location('beacon1','someTimestamp')); Recap