#RaspberryPi – Listing nearby BLE devices using the onboard #bluetooth sensor

Hi !

I done this at least, 4 different times, and I never wrote it down. So, here it is.

import json
from bluepy.btle import Scanner

try:
    # based on http://ianharvey.github.io/bluepy-doc/scanner.html#sample-code

    scanner = Scanner() 
    devices = scanner.scan(10.0)

    devices_m = []

    for dev in devices:
        
        name = ""
        power = ""
        for (adtype, desc, value) in dev.getScanData():
            if (desc == "Complete Local Name"):
                name = str(value)
            elif (desc == "Tx Power"):
                power = str(value)

        # add device addr, addType and rssi to devices_m
        devices_m.append({'addr': dev.addr, 'addType': dev.addrType, 'rssi': dev.rssi, 'name': name, 'power': power})

    json_devices = json.dumps(devices_m)
    print(json_devices)

except Exception as ex:
    print ( "Unexpected error in BLE Scanner BLUEPY: %s" % ex )

The output is similar to this one. You can see that my standing desk is listed here. If you are nearby, you can hack and move my desk up or down !

listing BLE devices using raspberry pi bluetooth sensor

Important: The output JSON is using some tricks to make it readable in the console.

This is the code with the JSON formatted.

import json
import sys
from bluepy.btle import Scanner, DefaultDelegate
from pygments import highlight, lexers, formatters

try:
    # based on http://ianharvey.github.io/bluepy-doc/scanner.html#sample-code

    scanner = Scanner() 
    devices = scanner.scan(10.0)

    devices_m = []

    for dev in devices:
        name = ""
        power = ""
        for (adtype, desc, value) in dev.getScanData():
            if (desc == "Complete Local Name"):
                name = str(value)
            elif (desc == "Tx Power"):
                power = str(value)

        # add device addr, addType and rssi to devices_m
        devices_m.append({'addr': dev.addr, 'addType': dev.addrType, 'rssi': dev.rssi, 'name': name, 'power': power})

    # standard print
    # json_devices = json.dumps(devices_m)
    # print(json_devices)

    # colored print
    formatted_json = json.dumps(devices_m, indent=4)
    colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())
    print(colorful_json)

except Exception as ex:
    print ( "Unexpected error in BLE Scanner BLUEPY: %s" % ex )

Happy coding!

Greetings

El Bruno



¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.