Difference between revisions of "Pi"

From Wiki2
Line 1: Line 1:
==pi==
==pi==
{{:esp8266}}
===getting started===
===getting started===
*get sd formatter https://www.sdcard.org/downloads/formatter_4/eula_windows/index.html
*get sd formatter https://www.sdcard.org/downloads/formatter_4/eula_windows/index.html

Revision as of 12:45, 7 November 2015

pi

esp8266

Esp8266-OKpins.png

current projects

hvac

DHT shroom
humidity temp control for noah -dht11+2relays 1 input, 2output
temp
outdoor thermometer -ds18b20, 1 input
DSP18B20 hrc
heated roof control-1 relay, 2inputs, 1output
timerrelay
timer for plants 1relay 1 output
DHT irrig
gravity feed water release (moisture level input dht11(io14d5)), out timr1(io15d8)

using with HDT11

DHT11-Pinout.png

notes on esp8266

Hi Mitul,

My best esp8266 code is in https://github.com/mckennatim/demiot. A couple of notes on it.

You can always get it online by hard coding your SSID info ala...

   #include <ESP8266WiFi.h>
   #include <ESP8266WebServer.h>
   
   const char *ssid = "street_no_vale2";
   const char *pwd = "jjjjjjjj";
   
   ESP8266WebServer server(80);
   
   void handleRoot() {
     server.send(200, "text/html", "h1 root of espAPsb AP server /h1");
   }
   
   void getOnline(){
     WiFi.begin(ssid, pwd);
     int tries =0;
     int success=1;
     while (WiFi.status() != WL_CONNECTED ) {
       delay(500);
       Serial.print(".");
       tries++;
       if (tries==15){
         success=0;
         scan();
         setupAP();
         break;
       }
     }
     if (success){
       Serial.println("");
       Serial.println("WiFi connected");
       Serial.print("IP address: ");
       Serial.println(WiFi.localIP());    
     }   
   }
   void setup(){
     Serial.begin(115200);
     Serial.println();
     Serial.println("--------------------------");
     Serial.println("ESP8266 webconfig");
     Serial.println("--------------------------");
     getOnline();
   }
   void loop(){
     server.handleClient();
   }

but that is not at all interesting for a couple of reasons

  1. you shouldn't have to be reconnect and upload over USB every time you move to a new SSID
  2. this sets you up as a server instead of client. There are lots of downsides to that. (your customers have to open ports on their routers ala xbox, an outside server&clients needs to keep track of its IP...)

So you need to be able to webconfig the thing and then run it as a client.

In denmiot/essp8266/mqttall I broke out webconfig in `#include "config.h"` (excuse the `extern` globals).

setup calls getOnline() which reads a config from the EEPROM and connects but if that fails it jumps into webconfig mode, turning itself into and access point server with an SSID of `espAPsb` and an ip of 192.168.4.1 where you can send it a get string like

  http://192.168.4.1/config?ssid=street_no_vale2&pwd=jjjjjjjj&devid=CYURD001&ip=10.0.1.100&port=3332

once you send it that it reboots itself (sometimes you need to hit the reset or powerdown) as a client on your local wifi.

mqtt

mqtt is a very cool pu/sub/ protocol. For some reason though it won't automatically reconnect when you do a webconfig. You have to power down first

TLS on esp8266

refs

http://shinysparkly.com/blog/2015/05/31/node-in-apache/

https://github.com/mcollina/mosca/wiki/TLS-SSL-Configuration

https://github.com/esp8266/Arduino/issues/43 ssl on espe266

https://github.com/esp8266/Arduino/issues/2306


https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs

me: Normally one would want the baddest certifcate you can get, un-deciferable cifers, un-stealable keys ...

I have a different need, a dumbed down tls1.1 small key/cipher/cert that will work on esp8266's, these tiny, wifi enabled, mqtt protoocol running, $2, iot devices. OK so I made a 512byte private key. Now I need to make a cert and a sha-1 thumbprint that will work with small memory devices using tls1.1, TLSRSAWITHAES128CBCSHA or RC4-MD5 ciphers.

Any ideas on an oppenssl command to get that?


https://www.feistyduck.com/library/openssl-cookbook/online/ch-openssl.html#

https://www.openssl.org/docs/man1.0.2/apps/ciphers.html#CIPHER-LIST-FORMAT

http://unix.stackexchange.com/questions/140601/verifying-a-ssl-certificates-fingerprint


http://serverfault.com/questions/216814/wireshark-display-filter-protocol-tlsv1-and-packetlength

ssl.record.version == 0x0302

That tells Wireshark to only display packets that are SSL conversations using TLS semantics.


http://blog.abarbanell.de/raspberry/2016/01/09/arduino-nginx/

me: Doesn't the nginx proxy need crt's and key's? Will it just work like a browser and encrypt deencrypt automagically?

Tobias Abarbanell Hi Tim, in this process the nginx is a server receiving requests over http and then on the encrypted side it is a client, so it does not need to have certificates.

If you want traffic coming the other direction, from the outside to your devices you would need certificates on the nginx and I would recommend using letsencrypt (https://letsencrypt.org) for this purpose.

Hi Tobias,

Thanks. BTW I think I had already solved the "traffic coming the other direction" problem. I've been loving mqtt as a lightweight protocol to have my esp8266's converse with the world. On my outside nginx vps I am running mosca inside a node app. Mosca is a broker. Devices an clients subscribe and publish to topics and mosca routes them. So my guess is having the pi handle the tls stuff, I'd be able to get data in too.

Meanwhile if I've discovered (after lots of error and error) if I limit the ciphers and keysize I can get TLSv1.1 working rather reliably straight from the esp8266. I haven't dropped a handshake in an hour now. Having WiFiClientSecure just use a fingerprint of the certificate (512 bit certificate) it verifies and accepts the cert. Instead of letting node run with its TLSv1.2 super secure big bloated ciphers I start node like this: node --tls-cipher-list='TLS_RSA_WITH_AES_128_CBC_SHA:RC4-MD5' lib/index.js. Ok so I won't win any awards for TLS and can't use AWS IOT(req TLSv1.2 and big ciphers), but the sensors and relays all over my house and yard will be very hard to mess with nonetheless.

Mosca sends mqtt to web clients using websockets. That's the final piece of the puzzle for me to tackle, wss for apache(windows testmachine) and nginx(ubuntu16.04vps)

Your idea is brilliant and I can't wait to try it on a pi.



https://github.com/esp8266/Arduino/issues/2306

As you see from the list, two cipher suites supported by axTLS library on the ESP side (TLS_RSA_WITH_AES_128_CBC_SHA and TLS_RSA_WITH_AES_256_CBC_SHA) are not among the list of cipher suites supported by your server. This causes handshake failure, because if the server and client have no cipher suites in common, they can't talk to each other.

now the above post shows the current library supports RC4-MD5 (I believe) - but I'm not sure how to prioritize it in the handshake? That is, until SHA256 is added :)

https://github.com/esp8266/Arduino/issues/2201

http://nodemcu.readthedocs.io/en/latest/en/modules/crypto/

for nodemcu The crypto modules provides various functions for working with cryptographic algorithms.

The following encryption/decryption algorithms/modes are supported: - "AES-ECB" for 128-bit AES in ECB mode (NOT recommended) - "AES-CBC" for 128-bit AES in CBC mode

The following hash algorithms are supported: - MD2 (not available by default, has to be explicitly enabled in app/include/user_config.h) - MD5 - SHA1 - SHA256, SHA384, SHA512 (unless disabled in app/include/user_config.h)

http://security.stackexchange.com/questions/105766/openssl-generate-self-signed-certificates-with-different-cipher-suites

{"given_cipher_suites":["TLS_RSA_WITH_AES_128_CBC_SHA","TLS_RSA_WITH_AES_256_CBC_SHA","TLS_RSA_WITH_RC4_128_SHA","TLS_RSA_WITH_RC4_128_MD5"],"ephemeral_keys_supported":false,"session_ticket_supported":false,"tls_compression_supported":false,"unknown_cipher_suite_supported":false,"beast_vuln":false,"able_to_detect_n_minus_one_splitting":false,"insecure_cipher_suites":{"TLS_RSA_WITH_RC4_128_MD5":["use RC4 which has insecure biases in its output"],"TLS_RSA_WITH_RC4_128_SHA":["use RC4 which has insecure biases in its output"]},"tls_version":"TLS 1.1","rating":"Bad"}

{"pid":5768,"hostname":"tim-hp","name":"mosca","level":40,"time":1484804098536,"msg":"101057795:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:openssl\\ssl\\s3_pkt.c:1472:SSL alert number 40\n","type":"Error","stack":"Error: 101057795:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:openssl\\ssl\\s3_pkt.c:1472:SSL alert number 40\n\n at Error (native)","client":"ESP8266Client-e1e","v":1}

openssl s_client -connect sslvh.tm:8883 -tls1
CONNECTED(00000003)
depth=0 /C=US/ST=MA/L=Boston/O=sitebuilt.net/OU=dog/CN=sslvh.tm/emailAddress=mckenna.tim@gmail.com
verify error:num=18:self signed certificate
verify return:1
depth=0 /C=US/ST=MA/L=Boston/O=sitebuilt.net/OU=dog/CN=sslvh.tm/emailAddress=mckenna.tim@gmail.com
verify return:1
---
Certificate chain
 0 s:/C=US/ST=MA/L=Boston/O=sitebuilt.net/OU=dog/CN=sslvh.tm/emailAddress=mckenna.tim@gmail.com
   i:/C=US/ST=MA/L=Boston/O=sitebuilt.net/OU=dog/CN=sslvh.tm/emailAddress=mckenna.tim@gmail.com
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDkjCCAnoCCQDp7cwG8OKZBjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMC
VVMxCzAJBgNVBAgMAk1BMQ8wDQYDVQQHDAZCb3N0b24xFjAUBgNVBAoMDXNpdGVi
dWlsdC5uZXQxDDAKBgNVBAsMA2RvZzERMA8GA1UEAwwIc3NsdmgudG0xJDAiBgkq
hkiG9w0BCQEWFW1ja2VubmEudGltQGdtYWlsLmNvbTAeFw0xNzAxMTMyMjExMzla
Fw0xODAxMTMyMjExMzlaMIGKMQswCQYDVQQGEwJVUzELMAkGA1UECAwCTUExDzAN
BgNVBAcMBkJvc3RvbjEWMBQGA1UECgwNc2l0ZWJ1aWx0Lm5ldDEMMAoGA1UECwwD
ZG9nMREwDwYDVQQDDAhzc2x2aC50bTEkMCIGCSqGSIb3DQEJARYVbWNrZW5uYS50
aW1AZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtobF
4ubgPP4bEQlhXCIMA7vwi7oqjJZ6qhp80tMdhvcI/Cjz/BsGKtxbiLlivcJozV67
YOdidTS1CjH7vmxxxhIodF+g6LdoSJ75Sa2iRvCzbeGkrcNRL93jTkqQvYoG4GEz
t5aBLnFnVDCr299d+VchOGv1Q3ChvLNxAU6TqMzhPoHKPH7DnGF9wSR9qvRP7rI+
wq9+QeuLdQaQmUVnt80OZFp2Oq/9WGu5tiEie7JZcFqbNq2dFycIm2wa2/4mBJvA
5Qcw6aV5C0Al870go0O6OSIODZ+RQg/KRunXXtFcSqdi8iuF6R2tzNbd5Vh2+ANK
lTfStFJAH9IcXE/EVwIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQCmalVCojqvTHlE
guDhoRX98FldiCpAI40ZWODiClQe7IR6ANPc8rqsMtfyfwIsYdXqcZzj5NBrIGp1
SST7uVoA2YIy4eGs8AmKNKf4CkLEPM+7ST5mmpKtrUNmHrFjYUyn6C/iu8Vyx6lP
MadCPezDB8qeCj5Z3ylYTLIBog1f29gkmqTCJtt7FIhFECSUGrYVMmyaScXONV5y
UZSnGNoRWuqdcGu0a6PKBb270vpdUa2yPwFWwbMJxsCc/2sT7YQcAk++r6WFk1qF
7AiNdZYsEgmjnkGGHRbjKTxk1Osh+G8uV3e6KzE/G5d0K80dIX8jLSPH6yYCYfe5
msMayEMI
-----END CERTIFICATE-----
subject=/C=US/ST=MA/L=Boston/O=sitebuilt.net/OU=dog/CN=sslvh.tm/emailAddress=mckenna.tim@gmail.com
issuer=/C=US/ST=MA/L=Boston/O=sitebuilt.net/OU=dog/CN=sslvh.tm/emailAddress=mckenna.tim@gmail.com
---
No client certificate CA names sent
---
SSL handshake has read 1080 bytes and written 412 bytes
---
New, TLSv1/SSLv3, Cipher is AES256-SHA
Server public key is 2048 bit
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
    Cipher    : AES256-SHA
    Session-ID: EB450D46B951B96AB6D8F3B10762772F05D8D9E65998FEC796EAA852A335FFD2
    Session-ID-ctx:
    Master-Key: 6F9AA7D47D1E352283BC6D7715A4664E184E4B565B14F6288350E117D3D9F6FD6869F28E66481822B1B37CC35E252BE0
    Key-Arg   : None
    Start Time: 1484812097
    Timeout   : 7200 (sec)
    Verify return code: 18 (self signed certificate)

http://security.stackexchange.com/questions/119505/how-to-speed-up-slow-tls-handshake-on-esp8266-running-mbed-tls

https://www.bountysource.com/issues/28368887-compatibility-with-arduino-and-esp8266

http://superuser.com/questions/882638/sslciphersuite-settings-in-apache-for-supporting-tls-1-0-1-1-and-1-2

openssl

back to esp8266

https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs

in cd ../vhosts/somecerts/smallcerts/

Generate a Private Key and a CSR

openssl req -newkey rsa:512 -nodes -keyout domain.key -out domain.csr

Generate a Self-Signed Certificate from an Existing Private Key

openssl req -key domain.key -new -x509 -days 365 -out domain.crt

View CSR Entries

openssl req -text -noout -verify -in domain.csr

View Certificate Entries

openssl x509 -text -noout -in domain.crt

Verify a Certificate was Signed by a CA

openssl verify -verbose -CAFile ca.crt domain.crt
from https://www.feistyduck.com/library/openssl-cookbook/online/ch-openssl.html#
openssl genrsa -out fd.key 512                           //create private key (no pass)
openssl rsa -in fd.key -pubout -out fd-public.key        //to separate out the public key
openssl req -new -key fd.key -out fd.csr                 //create csr from key
openssl req -text -in fd.csr -noout                      //show your csr
openssl x509 -req -days 365 -in fd.csr -signkey fd.key -out fd.crt          // create a cert w/o questions
openssl x509 -text -in fd.crt -noout                     //view the cert
openssl x509 -text -noout -in fd.crt -fingerprint        //GET A CERTS FINGERPRINT

Ciphers

openssl ciphers -v 'ALL:COMPLEMENTOFALL'                 //list available

https://engineering.circle.com/https-authorized-certs-with-node-js-315e548354a2#.3atvisjhz

vis a vis letsencrypt

your key file will be privkey.pem
your cert file will be cert.pem
your ca file will be chain.pem or fullchain.pem ( depending exactly what you need )

creating a certificate signing authority ca (and cert and key)

https://jamielinux.com/docs/openssl-certificate-authority/create-the-root-pair.html

Acting as a certificate authority (CA) means dealing with cryptographic pairs of private keys and public certificates. The very first cryptographic pair we’ll create is the root pair. This consists of the root key (ca.key.pem) and root certificate (ca.cert.pem). This pair forms the identity of your CA.

in C:\wamp\vhosts\somecerts\caSetup create root certificates

 mkdir certs crl csr newcerts private
 touch index.txt
 echo 1000 > serial
put in a openssl.conf
openssl genrsa -aes256 -out private/ca.key.pem 4096 //pwd required 
openssl req -config openssl.conf -key private/ca.key.pem -new -x509 -days 12000 -sha256 -extensions v3_ca -out certs/ca.cert.pem //need privar pwd and Common Name hpTimCa
openssl x509 -noout -text -in certs/ca.cert.pem //verify root cert

create intermediate certs

 cd intermediate
 mkdir certs crl csr newcerts private
 touch index.txt
 echo 1000 > serial
 echo 1000 > crlnumber
openssl genrsa -aes256 -out intermediate/private/intermediate.key.pem 4096 //same pwd
openssl req -config intermediate/openssl.conf -new -sha256 -key intermediate/private/intermediate.key.pem -out intermediate/csr/intermediate.csr.pem
openssl ca -config openssl.conf -extensions v3_intermediate_ca -days 10900 -notext -md sha256 -in intermediate/csr/intermediate.csr.pem -out intermediate/certs/intermediate.cert.pem
openssl x509 -noout -text -in intermediate/certs/intermediate.cert.pem //verify
openssl verify -CAfile certs/ca.cert.pem intermediate/certs/intermediate.cert.pem //verify against root
cat intermediate/certs/intermediate.cert.pem certs/ca.cert.pem > intermediate/certs/ca-chain.cert.pem
openssl genrsa -out intermediate/private/sslvh.tm.key.pem 2048 //omitting aes256 creates a key without a password
openssl req -config intermediate/openssl.conf -key intermediate/private/sslvh.tm.key.pem -new -sha256 -out intermediate/csr/sslvh.tm.csr.pem
openssl ca -config intermediate/openssl.conf -extensions server_cert -days 9000 -notext -md sha256 -in intermediate/csr/sslvh.tm.csr.pem -out intermediate/certs/sslvh.tm.cert.pem
openssl x509 -noout -text -in intermediate/certs/sslvh.tm.cert.pem
openssl x509 -text -noout -in sslvh.tm.cert.pem -fingerprint 

The Issuer is the intermediate CA. The Subject refers to the certificate itself.

openssl verify -CAfile intermediate/certs/ca-chain.cert.pem intermediate/certs/sslvh.tm.cert.pem

You can now either deploy your new certificate to a server, or distribute the certificate to a client. When deploying to a server application (eg, Apache), you need to make the following files available:

C:\wamp\vhosts\somecerts\caSetup\intermediate\certs\ca-chain.cert.pem
C:\wamp\vhosts\somecerts\caSetup\intermediate\private\sslvh.tm.key.pem
C:\wamp\vhosts\somecerts\caSetup\intermediate\certs\sslvh.tm.cert.pem

you could but I didn't create a certifice revocation lis CRL

node

mosca uses the node TLS stuff

from https://nodejs.org/api/tls.html#tls_tls_ssl

This default cipher list can be replaced entirely using the --tls-cipher-list command line switch. For instance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS cipher suite:

node --tls-cipher-list="TLS_RSA_WITH_AES_128_CBC_SHA:RC4-MD5"

debug

sparkfun thing dev

http://frightanic.com/iot/comparison-of-esp8266-nodemcu-development-boards/

:back to breakout boards

wifi breakout board

refs

wiring

http://www.forward.com.au/pfod/ESP8266/GPIOpins/index.html

https://github.com/esp8266/Arduino/issues/1243

d1-mini-esp8266-board-sh_fixled.jpg

current sensing

http://www.esp8266-projects.com/2015/06/mailbag-arrival-acs712-current-sensor.html

getting started

setting up python

sudo apt-get update
sudo apt-get python-pip
sudo apt-get install python-dev
sudo pip install virtualenv

create a project directory

cd projdir
virtualenv venv

running in a virtualenv doesn't work because pi doesn't have access to /dev/mem which is used by GPIO

so all the following commmands need sudo

install flask

pip install Flask

install gevent

pip install gevent 
pip install RPi.GPIO
pip install -U flask-cors
sudo python cascada2.py

default

user pi passwd raspberry

login loop

-bash: error while loading shared libraries: libtinfo.so.5: cannot open shared object file or directory

http://raspberrypi.stackexchange.com/questions/36467/how-to-repair-login-loop-bash-error

https://www.raspberrypi.org/forums/viewtopic.php?uid=159601&f=28&t=120846&start=0

https://www.raspberrypi.org/forums/ucp.php

bluetooth 4.0 LE

http://www.ioncannon.net/linux/1570/bluetooth-4-0-le-on-raspberry-pi-with-bluez-5-x/

http://www.elinux.org/RPi_Bluetooth_LE

python

jupyter on python3

https://www.digitalocean.com/community/tutorials/how-to-set-up-a-jupyter-notebook-to-run-ipython-on-ubuntu-16-04


is installed in omen www/environments/jup

tim@omen:/d/fs/www/environments$ pyvenv jup
tim@omen:/d/fs/www$ cd environments/
tim@omen:/d/fs/www/environments$ . jup/bin/activate
(jup) tim@omen:/d/fs/www/environments$ jupyter notebook

(jup) tim@omen:/d/fs/www/environments/jup/bin$ deactivate

accessing object properties

status ={}
status['pond'] = {'spot': 'center', 'state': 'off', 'tleft': 0, 'nexton': 9}
status['pond']['tleft']= 16

parsing u'5'

basic tutorial

https://thenewcircle.com/static/bookshelf/python_fundamentals_tutorial/advanced_types_containers.html

running app forever - supervisorctl

cascada

port = 8087
/home/pi/mypi/cascada/server/cascada.py

cascada2

port = 8088
/home/pi/mypi/cascada/server/cascada2.py

<markdown>

sudo`supervisorctl` reads configuration from `/etc/supervisor/conf.d` and runs whatever files if finds there.

a typical `conf` ile looks like:

   [program:cascada2]
   command=/usr/bin/python /home/pi/mypi/cascada/server/cascada2.py
   directory=/home/pi/mypi/cascada/server
   autostart=true
   autorestart=true
   startretries=3
   stderr_logfile=/var/log/cascada/cascada2.err.log
   stdout_logfile=/var/log/cascada/cascada2.out.log
   user=root
   environment=SECRET_PASSPHRASE='this is secret',SECRET_TWO='another secret'

you may have to `>supervisor reload` then `ctrl c` the `sudo supervisorctl` to get a new program running forever

</markdown>

pi@raspberrypi ~ $ sudo supervisorctl
cascada                          RUNNING    pid 2273, uptime 7 days, 3:17:36


tail -f /var/log/cascada/cascada.out.log
tail -f /var/log/cascada/cascada.err.log

after changing cascada.py

pi@raspberrypi ~ $ sudo supervisorctl
cascada                          RUNNING    pid 2273, uptime 7 days, 3:17:36
supervisor> stop cascada

exit w ctrl C

sudo lsof -i :8087
sudo kill -9 21118 (kill whatever port lsof returns)
pi@raspberrypi ~ $ sudo supervisorctl
cascada                          STOPPED    Jul 16 04:34 PM
supervisor> start cascada
cascada: started
supervisor>

exit w ctrl C ??

  • nohup python app.py &
  • use screen
  • run supervisord(link) on system startup and control all through it (pythonic way :))

nohup means: do not terminate this process even when the stty is cut off.

& at the end means: run this command as a background task.

forever with supervisord

SSE - Server Side Events

http://flask.pocoo.org/snippets/116/

https://github.com/stevenewey/ssedemo


for node

https://www.npmjs.com/package/simple-sse (has room,haven't tried)

https://tomkersten.com/articles/server-sent-events-with-node/

http://www.futureinsights.com/home/real-time-the-easy-way-with-eventsource-angularjs-and-nodejs.html

SocketIO

http://stackoverflow.com/questions/17641602/how-to-emit-to-room-in-socket-io

flask socketio

https://flask-socketio.readthedocs.org/en/latest/

ibeacon

http://www.jaredwolff.com/blog/get-started-with-bluetooth-low-energy/ decribes gattr tool as well

xyfindit

00:eb:19:00:b7:b9,07775dd0111b11e491910800200c9a66,6400,47033,-59,-68

android

https://github.com/alt236/Bluetooth-LE-Library---Android

distance

http://stackoverflow.com/questions/20416218/understanding-ibeacon-distancing

http://en.wikipedia.org/wiki/DBm

The iBeacon output power is measured (calibrated) at a distance of 1 meter. Let's suppose that this is -59 dBm (just an example). The iBeacon will include this number as part of its LE advertisment.

The listening device (iPhone, etc), will measure the RSSI of the device. Let's suppose, for example, that this is, say, -72 dBm.

Since these numbers are in dBm, the ratio of the power is actually the difference in dB. So:

ratio_dB = txCalibratedPower - RSSI To convert that into a linear ratio, we use the standard formula for dB:

ratio_linear = 10 ^ (ratio_dB / 10) If we assume conservation of energy, then the signal strength must fall off as 1/r^2. So:

power = power_at_1_meter / r^2. Solving for r, we get:

r = sqrt(ratio_linear) In Javascript, the code would look like this:

function getRange(txCalibratedPower, rssi) {

   var ratio_db = txCalibratedPower - rssi;
   var ratio_linear = Math.pow(10, ratio_db / 10);
   var r = Math.sqrt(ratio_linear);
   return r;

} Note, that, if you're inside a steel building, then perhaps there will be internal reflections that make the signal decay slower than 1/r^2. If the signal passes through a human body (water) then the signal will be attenuated. It's very likely that the antenna doesn't have equal gain in all directions. Metal objects in the room may create strange interference patterns. Etc, etc... YMMV.

shareeditflag edited Feb 7 '14 at 2:19

answered Feb 7 '14 at 1:24

Mark Fassler 43135

http://stackoverflow.com/questions/15687332/bluetooth-le-rssi-for-proximity-detection-ios

estimote

Hi Wojtek,

Yep I got them and they are an exciting technology. But I must live in a 2.4 ghz jungle. That and the interesting variability you get between dog lying down, standing up and walking around can alter their signal markedly. Add to that the changes to the signal as I move about the house with my phone and you have a real puzzle.

I have better luck fixing by fixing my bluetooth receiver(s) and not detecting the beacons from mobile devices.

So I have set up raspberry pi's at key points in the yard to track the beacons. Using the libraries Bluez and Bluepy. I am able to estimate distance using the dB difference between the RSSI and the dB at 1 meter to get a power ratio that varies with the square of the distance. It is still cranky but once I put a few pi's in the yard I'll have boatloads of data to play around with.

It will be interesting to try out some filters, maybe put the data through a Hidden Markov Model or train up a neural network.

I have got some other beacons from other manufacturers and they all have similar variability. What would keep my concentration on Estimotes would be a bit of information on the Unknown Services that show up on scans. In particular, you advertise your beacons as standing out with capabilities like the accelerometer on board. How do I read that?

Meanwhile, the pi's are running a little restful API and some socket.io to communicate with my mobile devices and laptops. I'll have a mobile friendly responsive design HTML5/javascript app running soon. If I was doing dedicated I'd start on Android before IOS.

Thanks for your offer of help. Good luck with your product. The potential is enormous.