Python bluetooth low energy

Finding Bluetooth low energy with python

Is it possible for this code to be modified to include Bluetooth Low Energy devices as well? https://code.google.com/p/pybluez/source/browse/trunk/examples/advanced/inquiry-with-rssi.py?r=1 I can find devices like my phone and other bluetooth 4.0 devices, but not any BLE. If this cannot be modified, is it possible to run the hcitool lescan and pull the data from hci dump within python? I can use the tools to see the devices I am looking for and it gives an RSSI in hcidump, which is what my end goal is. To get a MAC address and RSSI from the BLE device. Thanks!

That code has no support for BLE functionality. it’d require a HUGE amount of changes to support BLE.

Do you know of any functional BLE scanning code out there? I have searched quite a bit, but have not found one. Thanks!

2 Answers 2

As I said in the comment, that library won’t work with BLE.

Here’s some example code to do a simple BLE scan:

import sys import os import struct from ctypes import (CDLL, get_errno) from ctypes.util import find_library from socket import ( socket, AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI, SOL_HCI, HCI_FILTER, ) if not os.geteuid() == 0: sys.exit("script only works as root") btlib = find_library("bluetooth") if not btlib: raise Exception( "Can't find required bluetooth libraries" " (need to install bluez)" ) bluez = CDLL(btlib, use_errno=True) dev_id = bluez.hci_get_route(None) sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI) sock.bind((dev_id,)) err = bluez.hci_le_set_scan_parameters(sock.fileno(), 0, 0x10, 0x10, 0, 0, 1000); if err < 0: raise Exception("Set scan parameters failed") # occurs when scanning is still enabled from previous call # allows LE advertising events hci_filter = struct.pack( "<>".format( errno.errorcode[errnum], os.strerror(errnum) )) while True: data = sock.recv(1024) # print bluetooth address from LE Advert. packet print(':'.join("".format(x) for x in data[12:6:-1])) 

I had to piece all of that together by looking at the hcitool and gatttool source code that comes with Bluez. The code is completely dependent on libbluetooth-dev so you’ll have to make sure you have that installed first.

A better way would be to use dbus to make calls to bluetoothd , but I haven’t had a chance to research that yet. Also, the dbus interface is limited in what you can do with a BLE connection after you make one.

EDIT:

Martin Tramšak pointed out that in Python 2 you need to change the last line to print(‘:’.join(«».format(ord(x)) for x in data[12:6:-1]))

Источник

BLE-GATT 0.5.0

The goal of this library is to only have a small number of dependencies and to be easily installable (even in a Python virtual environment without –system-site-packages ).

The commands should be installed and run by the user without sudo privileges.

Install

$ python3 -m venv venv_ble . venv_ble/bin/activate pip3 install BLE_GATT

tl;dr

Example of connecting and reading and writing without notifications or asynchronous data

Example of connecting and interacting with characteristics asynchronously

Basics of BLE

Hopefully you are here you are here with some basic knowledge of Bluetooth and you understand that Bluetooth Classic and Bluetooth BLE are different.

Читайте также:  Блютуз колонка havit e30

There is an introduction to BLE at:

This library is only going to work with BLE. It will also only be a Central device connecting to a Peripheral device.

The two key things that you will need to know about the peripheral device you want to connect to is its address and the UUID of the GATT characteristic you want to interact with.

Addreess

This will be in the form of a mac address. This is 6 pairs of numbers separate by colons. e.g. 11:22:33:44:55:66 This should be unique to each device.

UUID

A UUID is a 128-bit value that are written in groups 0f 8-4-4-4-12. For example 00002A00-0000-1000-8000-00805F9B34FB.

Each characteristic will have a UUID that represents what it is. The number above is for the Device Name Characteristic .

Writing those long numbers is cumbersome so Bluetooth official characteristics can be shortened to 16-bits. This means you will often see the above Device Name Characteristic written as 0x2A00 although on the system it will still be the 128-bit value. The official Bluetooth base UUID is: 0000xxxx-0000-1000-8000-00805F9B34FB and the 16-bit value replaces the x’s.

One-time provisioning of peripheral device

A BLE peripheral device will be advertising some summary information, such as what services it offers, and our Central device needs to have read this advertisement before it can connect. Some devices will also need to exchange security information before they can connect and exchange information securely.

This security information exchange is called pairing or bonding. As this is a one-time provisioning step this library does not do the discovery or pairing step. Those can be done with the Linux bluetoothctl tool.

To start and stop the discovery of nearby advertising peripherals:

[bluetooth]# scan on [bluetooth]# scan off

Discovered devices will scroll up the screen. Once you stop discovery, to get a list of devices use:

If you need to pair with the peripheral then the commands are:

[bluetooth]# agent KeyboardDisplay [bluetooth]# pair 11:22:33:44:55:66

If you don’t need to pair, then doing a connect will save the device in the Bluetooth information on the machine:

[bluetooth]# connect 11:22:33:44:55:66 [Name Of Device]# disconnect

Getting Started

Now you have the peripheral device address, UUID’s of interest, and have done the provisioning of the device we are ready to do some coding.

Create a device object

Import the library to you code and tell it about the address of the peripheral device to connect to.

Connect and disconnect

Establish (or remove) a Bluetooth connection between the Linux computer your code runs on and the peripheral device.

Exchange Information

The API uses the structure of the command name is the activity you want to perform on the characteristic. The first parameter is the UUID of the characteristic you want to perform that on. To save us keep writing the long UUID, it is a good idea to create a constant/variable with the UUID value

Bluetooth data is always an array of unsigned bytes. We can represent that in Python as a list of values between 0 and 255. Numbers that are bigger than 255 will take multiple bytes. We can connect these together in Python with int.from_bytes or struct.unpack.

To create the values to write we can use int.to_bytes or stuct.pack

Читайте также:  Блютуз для mi band

Expect Bluetooth data to be in little endian format.

Asynchronous Data

As well as reading and writing data, it is also possible get notifications from a Bluetooth peripheral when the value of a characteristic has changed. This is very efficient on Bluetooth traffic and also the battery of the peripheral as it can turn the radio off when there isn’t new data. For programming the client it means we don’t know when there is going to be data to handle. This requires us to code using asynchronous technique.

We do this be using the on_value_change command for the GATT characteristic UUID of interest. We give it a function that will get called when the value changes. We also need to use wait_for_notifications to stop the code exiting. This runs an event loop listening for updates.

If you want to stop getting notifications from a GATT characteristic UUID then there is:
There is also a command that will remove all notifications, exit the event loop, and disconnect from the peripheral device.

Bytes and Values

With Bluetooth values will always be in bytes which isn’t very readable to humans so most of the time we will want to covert them to an integer or floating point number.

Let’s use an example from GATT Specification Supplement at https://www.bluetooth.com/specifications/specs/

We will use Electric Current Specification (0x2AF0) which has three fields within the characteristic each two bytes (octets) in size. Those three fields are minimum, typical and maximum electric current. With current being defined as:

  • Unit: org.bluetooth.unit.electric_current.ampere
  • Minimum value: 0
  • Maximum value: 655.34
  • Represented values: M = 1, d = -2, b = 0
  • Unit is degrees with a resolution of 0.01

The represented value information helps us convert an integer to a floating point number:

  • M = multiplier, positive or negative integer (between -10 and +10)
  • d = decimal exponent, positive or negative integer
  • b = binary exponent, positive or negative integer

From bytes

If we had three values of 12.34, 23.45, 34.56 they would arrive as [210, 4, 41, 9, 128, 13] . Let’s see how we could covert them using firstly struct .

And doing the same using int.from_bytes

To Bytes

If we were sending this data then it needs to go from being floating point numbers to a list of bytes.

Advanced Information

The BlueZ D-Bus API’s used in making this library is documented at:

You can get help on accessing those full APIs with the following commands:

Источник

bluezero 0.7.1

The aim of this library is to provide an API to access to Bluez with zero boilerplate code.

Goal

To provide a simplified API to people that want to use Bluetooth functionality in their code. The library will use calls to the BlueZ D-Bus API and use ‘sensible’ defaults to help with that simplification. It aims to support the ability to create interesting STEM activities without needing to explain the BlueZ API or write an event loop.

In addition to the API, it will contain examples of how to connect to common Bluetooth Smart (BLE) objects around them (or at least easily accessible to them). These examples will need to be written without the need to sign (or break) non-disclosure agreements.

Status

While we want this to be easy to use it does not mean it easy to create. This library is still in the early stages so things might change and break. Apologies in advance! We will try to make it as stable as possible. However much of the functionality that is in BlueZ is still flagged as experimental. The library assumes you are using a Linux release with BlueZ 5.50. For example Raspberry Pi OS Buster

Читайте также:  Microsoft bluetooth mouse forest camo special edition

Getting Started

If you are here for the time, and especially if you are new to Bluetooth Low Energy, then a tutorial might be a good place to start. The following tutorial has been created based on the readily available hardware of a Raspberry Pi and a micro:bit. More details available at: https://ukbaz.github.io/howto/ubit_workshop.html

Examples

There are some other examples in the library if you are feeling adventurous

Adapter

This will check that it can find the Bluetooth adapter on the computer running the code. It will print to screen various information and check it is powered before scanning for nearby devices

GATT Client (Central role)

This example uses the micro:bit API that has been written in bluezero. You will need a buzzer attached to pin 0 to get play_beep to work.

Beacon

A Simple Eddystone URL beacon. You can be read the URL being broadcast with any Physical Web application on your Phone

Scanner

This example scans for beacons using the common beacon formats of Eddystone URL, Eddystone UID, AltBeacon and iBeacon.

GATT Server (Peripheral role)

You will need to have modified the dbus configuration file to open the permissions for ‘ukBaz.bluezero’. This is covered in the System Setup section of the documentation

cpu_temperature.py

This example transmits the temperature of the CPU over the single characteristic. The method get_cpu_temperature() function creates randomly generated temperature values. Values are only updated when notification are switched on.

ble_uart.py

This example simulates a basic UART connection over two lines, TXD and RXD.

It is based on a proprietary UART service specification by Nordic Semiconductors. Data sent to and from this service can be viewed using the nRF UART apps from Nordic Semiconductors for Android and iOS.

It uses the Bluezero peripheral file (level 10) so should be easier than the previous CPU Temperature example that was a level 100.

Источник

bleak 0.20.2

Bleak Logo

Bleak is an acronym for Bluetooth Low Energy platform Agnostic Klient.

Bleak is a GATT client software, capable of connecting to BLE devices acting as GATT servers. It is designed to provide a asynchronous, cross-platform Python API to connect and communicate with e.g. sensors.

Installation

Features

  • Supports Windows 10, version 16299 (Fall Creators Update) or greater
  • Supports Linux distributions with BlueZ >= 5.43
  • OS X/macOS support via Core Bluetooth API, from at least OS X version 10.11
  • Android backend compatible with python-for-android

Bleak supports reading, writing and getting notifications from GATT servers, as well as a function for discovering BLE devices.

Usage

To discover Bluetooth devices that can be connected to:

Connect to a Bluetooth device and read its model number:
 DO NOT NAME YOUR SCRIPT bleak.py ! It will cause a circular import error.

See examples folder for more code, for instance example code for connecting to a TI SensorTag CC2650

Источник

Оцените статью
Adblock
detector