Bluetooth presence detection without Raspberry Pi 3

I use a Pi Zero (running Hassbian, can be raspbian) to do the job, it has built-in Bluetooth.

I run a little python rest api script to listen out for any BluetoothLE devices, in my case Tile keyrings.

It’s basic - just checks if the device is detectable or not. Might be of use:

Some things you might need to install

sudo apt-get install python3-pip libglib2.0-dev python-flask

sudo pip3 install bluepy

And the python script:

from flask import Flask
from bluepy.btle import Scanner, DefaultDelegate

class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        return()

scanner = Scanner().withDelegate(ScanDelegate())

app = Flask(__name__)

@app.route('/api/search/<string:mac_addr>', methods=['GET'])
def device_scan(mac_addr):
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan(3.0)
    for dev in devices:
        if dev.addr == mac_addr:
            return("true")
    return("false")

@app.errorhandler(404)
def not_found(error):
    return("Not Found ", error)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False)

For the sensors.yaml

## Presense / Tiles Sensor via Pi Zero Hassbian

  - platform: rest
    name: Car Keys
    resource: http://192.168.18.143:5000/api/search/a4:e8:27:f4:3e:2a

Where ‘a4:e8:27:f4:3e:2a’ is the MAC address of the BluetoothLE device you’re looking for:

sudo hcitool lescan

if you need to find it out.

The MAC address must be in Lower Case.

and 'http://192.168.18.143:5000 ’ the IP of your Pi Zero.

And a binary_sensor.yaml entry to make things easier:

- platform: template
  sensors:
      car_keys_boolean:
        friendly_name: "Car Keys"
        value_template: "{{ states.sensor.car_keys.state == 'true' }}"

Some might want to increase the scan time in the script, so 5 secs would look like this:

devices = scanner.scan(5.0)

The binary rest sensor option might look like a better fit here, but it will view the device as unavailable between boots if not seen at boot-time, hence the sensor to binary_sensor step.

9 Likes