BLUEPY(1)
π BLUEPY(1) β bluepy π
πΈ NAME πΈ
Okay bestie, welcome to the BLUEPY(1) manual β this whole thing is literally about bluepy, no cap.
bluepy is a Python module that lets you communicate with Bluetooth Low Energy devices. The current implementation runs on Linux β internally it uses code from the BlueZ project at http://www.bluez.org/ β although it can be ported to other platforms. π
To browse the API documentation, it is recommended to start with The Peripheral class (#peripheral). β¨
Contents:
π THE PERIPHERAL CLASS π
Bluepyβs Peripheral class encapsulates a connection to a Bluetooth LE peripheral. You create a Peripheral object directly by specifying its MAC address; when the connection is established, the services and characteristics offered by that device can be discovered and read or written. π¦
π οΈ Constructor π οΈ
Peripheral([deviceAddr=None[, addrType=ADDR_TYPE_PUBLIC[, iface=None]]])β IfdeviceAddris notNone, this creates aPeripheralobject and makes a connection to the device indicated bydeviceAddr.deviceAddrshould be a string comprising six hex bytes separated by colons, e.g."11:22:33:ab:cd:ed". π₯
If deviceAddr is None, it creates an un-connected Peripheral object. You must call the connect() method on this object β passing it a device address β before it will be usable. π«Ά
The addrType parameter can be used to select between fixed (btle.ADDR_TYPE_PUBLIC) and random (btle.ADDR_TYPE_RANDOM) address types, depending on what the target peripheral requires. See section 10.8 of the Bluetooth 4.0 specification for more details. π
The iface parameter allows the Bluetooth interface on which to make the connection to be set. On Linux, 0 means /dev/hci0, 1 means /dev/hci1 and so on. π
deviceAddr may also be a ScanEntry object. In this case the device address, address type, and interface number are all taken from the ScanEntry values, and the addrType and iface parameters are ignored. π§
The constructor will throw a BTLEException if connection to the device fails. π
π« Instance Methods π«
connect(addr[, addrType=ADDR_TYPE_PUBLIC[, iface=None]])β Makes a connection to the device indicated byaddr, with address typeaddrTypeand interface numberiface(see thePeripheralconstructor for details). You should only call this method if thePeripheralis un-connected (i.e. you did not pass anaddrto the constructor); a given peripheral object cannot be re-connected once connected. πdisconnect()β Drops the connection to the device, and cleans up associated OS resources. Although the Python destructor for aPeripheralwill attempt to call this method, you should not rely on this happening at any particular time. Therefore, always explicitly calldisconnect()if you have finished communicating with a device. π
Fr fr, the destructor is not your bestie here β call disconnect() yourself.
getState()β Returns a string indicating device state. Possible states are:"conn"β connected,"disc"β disconnected,"scan"scanning and"tryconn"β connecting. πgetServices()β Returns a list ofServiceobjects representing the services offered by the peripheral. This will perform Bluetooth service discovery if this has not already been done; otherwise it will return a cached list of services immediately. β¨
On Python 3.x, this returns a dictionary view object, not a list. π«Ά
getServiceByUUID(uuidVal)β Returns an instance of aServiceobject which has the indicated UUID.uuidValcan be aUUIDobject, or any string or integer which can be used to construct aUUIDobject. The method will return immediately if the service was previously discovered (e.g. bygetServices()), and will query the peripheral otherwise. It raises aBTLEEExceptionif the service is not found. πgetCharacteristics(startHnd=1, endHnd=0xFFFF, uuid=None)β Returns a list containingCharacteristicobjects for the peripheral. If no arguments are given, will return all characteristics. IfstartHndand/orendHndare given, the list is restricted to characteristics whose handles are within the given range β note that itβs usually more convenient to useService.getCharacteristics()to get the characteristics associated with a particular service. Alternatively,uuidmay be specified to locate a characteristic with a particular UUID value.uuidmay be any string, integer, orUUIDtype which can be used to construct aUUIDobject. πΈ
If no matching characteristics are found, returns an empty list. π
getDescriptors(startHnd=1, endHnd=0xFFFF)β Returns a list containingDescriptorobjects for the peripheral. If no arguments are given, will return all descriptors. IfstartHndand/orendHndare given, the list is restricted to descriptors whose handles are within the given range. Again, itβs usually more convenient to useService.getDescriptors()to get the descriptors associated with a particular service. π¦
If no matching descriptors are found, returns an empty list. π
withDelegate(delegate)β This stores a reference to a "delegate" object, which is called when asynchronous events such as Bluetooth notifications occur. This should be a subclass of theDefaultDelegateclass. See Working with notifications (#notifications) for more information. This method returns thePeripheralobject. πsetDelegate(delegate)β (deprecated since 0.9.10) Same aswithDelegate(). πwaitForNotifications(timeout)β Blocks until a notification is received from the peripheral, or until the given timeout (in seconds) has elapsed. If a notification is received, the delegate objectβshandleNotification()method will be called, andwaitForNotifications()will then returnTrue. β
If nothing is received before the timeout elapses, this will return False. π
writeCharacteristic(handle, val, withResponse=False)β Writes the dataval(of typestron Python 2.x,byteon 3.x) to the characteristic identified by handlehandle, which should be an integer in the range 1 to 65535. This is useful if you know a characteristicβs GATT handle, but do not have aCharacteristicobject. π₯
If withResponse is true, will await confirmation that the write was successful from the device. β
readCharacteristic(handle)β Reads the current value of the characteristic identified byhandle. This is useful if you know the handle for the characteristic but do not have a suitableCharacteristicobject. π
π Properties π
All the properties listed below are read-only. π
addrβ Device MAC address (as a hex string separated by colons). πaddrTypeβ Device address type β one ofADDR_TYPE_PUBLICorADDR_TYPE_RANDOM; this will be a printable string. πifaceβ Bluetooth interface number (0=/dev/hci0) used for the connection. π
π THE SCANNER CLASS π
Okay so a Scanner object is your little LE-device detective π΅οΈββοΈ β it scans for LE devices that are broadcasting advertising data. In most situations this gives you a set of devices that are available for connection. But bestie, plot twist: Bluetooth LE devices may accept connections without broadcasting advertising data, or they may broadcast advertising data but may not accept connections. So don't @ me when the vibes don't match the list. π
β¨ Constructor β¨
Scanner([index=0])β Creates and initialises a new scanner object.indexidentifies the Bluetooth interface to use (where0is/dev/hci0etc). Scanning does not start until thestart()orscan()methods are called β see below for details.
π Instance Methods π
withDelegate(delegate)β Stores a reference to a delegate object, which receives callbacks when broadcasts from devices are received. See the documentation forDefaultDelegatefor details.scan([timeout = 10])β Scans for devices for the given timeout in seconds. During this period, callbacks to the delegate object will be called. When the timeout ends, scanning will stop and the method will return a list (or a view on Python 3.x) ofScanEntryobjects for all devices discovered during that time.
scan() is equivalent to calling the clear(), start(), process() and stop() methods in order.
clear()β Clears the current set of discovered devices.start()β Enables reception of advertising broadcasts from peripherals. Should be called before callingprocess().process([timeout = 10])β Waits for advertising broadcasts and calls the delegate object when they are received. Returns after the given timeout period in seconds. This may be called multiple times (between calls tostart()andstop()).stop()β Disables reception of advertising broadcasts. Should be called afterprocess()has returned.getDevices()β Returns a list (a view on Python 3.x) ofScanEntryobjects for all devices which have been discovered (since the lastclear()call).
π Sample code π
Basic code to run a LE device scan for 10 seconds follows this example:
# import the necessary parts of the bluepy library
from bluepy.btle import Scanner, DefaultDelegate
# create a delegate class to receive the BLE broadcast packets
class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
# when this python script discovers a BLE broadcast packet, print a message with the device's MAC address
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
print "Discovered device", dev.addr
elif isNewData:
print "Received new data from", dev.addr
# create a scanner object that sends BLE broadcast packets to the ScanDelegate
scanner = Scanner().withDelegate(ScanDelegate())
# create a list of unique devices that the scanner discovered during a 10-second scan
devices = scanner.scan(10.0)
# for each device in the list of devices
for dev in devices:
# print the device's MAC address, its address type,
# and Received Signal Strength Indication that shows how strong the signal was when the script received the broadcast.
print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
# For each of the device's advertising data items, print a description of the data type and value of the data itself
# getScanData returns a list of tupples: adtype, desc, value
# where AD Type means βadvertising data type,β as defined by Bluetooth convention:
# https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile
# desc is a human-readable description of the data type and value is the data itself
for (adtype, desc, value) in dev.getScanData():
print " %s = %s" % (desc, value)
For continuous scanning, follow this example:
# import the necessary parts of the bluepy library
from bluepy.btle import Scanner, DefaultDelegate
# create a delegate class to receive the BLE broadcast packets
class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
# when this python script discovers a BLE broadcast packet, print a message with the device's MAC address
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
print "Discovered device", dev.addr
elif isNewData:
print "Received new data from", dev.addr
# create a scanner object that sends BLE broadcast packets to the ScanDelegate
scanner = Scanner().withDelegate(ScanDelegate())
# start the scanner and keep the process running
scanner.start()
while True:
print "Still running..."
scanner.process()
β οΈ NOTE that (1) LE scanning must be run as root and (2) the continuous scanning code never completes, so you'll need to do useful things in the handleDiscovery() method of your delegate.
See the documentation for ScanEntry for the information available via the dev parameter passed to the delegate.
π¦ THE SCANENTRY CLASS π¦
A ScanEntry object contains information received from a Bluetooth LE device during Scanner operation. This includes parameters needed to connect to the device (MAC address, address type), and advertising data (such as its name or available services) supplied in the device's broadcasts. It's giving "receipts from the BLE world." π§
πΈ Constructor πΈ
ScanEntry objects are created by the Scanner class, and should not be created by the user. No DIY-ing this one, bestie.
π Instance Methods π
getDescription(adtype)β Returns a human-readable description of the advertising data 'type' codeadtype. For instance, anadtypevalue of9would return the string"Complete Local Name". See the Generic Access Profile assigned numbers at<https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile>for a complete list.getValueText(adtype)β Returns a human-readable string representation of the advertising data for codeadtype. Values such as the 'local name' are returned as strings directly; other values are converted to hex strings. If the requested data is not available,Noneis returned.getScanData()β Returns a list of tuples (adtype,description,value) containing the AD type code, human-readable description and value (as reported bygetDescription()andgetValueText()) for all available advertising data items.
π Properties π
All the properties listed below are read-only. Read-only means look, don't touch. π
addrβ Device MAC address (as a hex string separated by colons).addrTypeβ Device address type β one ofADDR_TYPE_PUBLICorADDR_TYPE_RANDOM.ifaceβ Bluetooth interface number (0=/dev/hci0) on which advertising information was seen.rssiβ Received Signal Strength Indication for the last received broadcast from the device. This is an integer value measured in dB, where0 dBis the maximum (theoretical) signal strength, and more negative numbers indicate a weaker signal.connectableβ Boolean value βTrueif the device supports connections, andFalseotherwise (typically used for advertising 'beacons').updateCountβ Integer count of the number of advertising packets received from the device so far (sinceclear()was called on theScannerobject which found it).
π THE DEFAULTDELEGATE CLASS π
bluepy functions which receive Bluetooth messages asynchronously β such as notifications, indications, and advertising data β pass this information to the user by calling methods on a 'delegate' object. It's literally the bat-signal but for BLE events. π¦
To be useful, the delegate object will be from a class created by the user. Bluepy's DefaultDelegate is a base class for this β you should override some or all of the methods here with your own application-specific code. Customize bestie, don't just leave it bland.
β¨ Constructor β¨
DefaultDelegate()β Initialises the object instance.
π Instance Methods π
handleNotification(cHandle, data)β Called when a notification or indication is received from a connectedPeripheralobject.cHandleis the (integer) handle for the characteristic β this can be used to distinguish between notifications from multiple sources on the same peripheral.datais the characteristic data (astrtype on Python 2.x, andbyteson 3.x).handleDiscovery(scanEntry, isNewDev, isNewData)β Called when advertising data is received from an LE device while aScannerobject is active.scanEntrycontains device information and advertising data β see theScanEntryclass for details.isNewDevisTrueif the device (as identified by its MAC address) has not been seen before by the scanner, andFalseotherwise.isNewDataisTrueif new or updated advertising data is available.
π THE UUID CLASS π
π Constructor π
UUID(value)β Constructs aUUIDobject with the given value. This may be:- an
intvalue in the range0to0xFFFFFFFF - a
strvalue - another
UUIDobject - any other value which can be converted to hex digits using
str()
- an
π Instance Methods π
getCommonName()β Returns string describing that UUID. If the UUID is one listed in Assigned Numbers (<#assignednumbers>) this will be a human-readable name e.g."Cycling Speed and Cadence". Otherwise, it will be a hexadecimal string.
π Properties π
All the properties listed below are read-only.
binValβ The UUID expressed in binary (astrobject on Python 2.x,byteson 3.x).
π THE SERVICE CLASS π
Okay so a Bluetooth LE Service object is basically a little squad of characteristics and descriptors that all belong to one particular function of the peripheral. The point? You can discover just the characteristics you care about instead of enumerating literally everything the peripheral offers. Slay.
More info about standard services lives at https://www.bluetooth.org/en-us/specification/adopted-specifications π¦
π Constructor
Do not construct Service objects directly, bestie. Use the getServices() or getServiceByUUID() methods of a connected Peripheral object instead. That's the vibe.
β¨ Instance Methods
getCharacteristics([forUUID=None])β returns a list of Characteristic objects associated with the service. If this hasn't been done before, the peripheral gets queried. Otherwise, you get the cached list back. IfforUUIDis given, it may be a UUID object or a value used to construct one. In that case the returned list β which may be empty β contains any characteristics associated with the service that match that UUID.
πΈ Properties
All the properties listed below are read-only. No cap.
uuidβ the Bluetooth UUID for this service.peripheralβ the Peripheral object for the device to which the service belongs.
π THE CHARACTERISTIC CLASS π
A Bluetooth LE "characteristic" is a short data item that can be read or written. These can be fixed (e.g. a string representing the manufacturer name) or change dynamically (like the current temperature or state of a button). Most interaction with Bluetooth LE peripherals is done by reading or writing characteristics. It's giving main character energy, fr fr.
π Constructor
You should not construct Characteristic objects directly. Instead, use the getCharacteristics() method of a connected Peripheral object. That's the move.
β¨ Instance Methods
read()β reads the current value of a characteristic as a string of bytes. For Python 2.x this is a value of typestr, and on Python 3.x this is of typebytes. This may be used with thestructmodule to extract integer values from the data.write(data[, withResponse=False])β writes the given data to the characteristic.datashould be of typestrfor Python 2.x, and typebytesfor Python 3.x. Bluetooth LE allows the sender to request the peripheral to send a response to confirm that the data has been received. Setting thewithResponseparameter toTruewill make this request. ABTLEExceptionwill be raised if the confirmation process fails.supportsRead()β returnsTrueif the characteristic can be read (as indicated by its properties) andFalseotherwise.propertiesToString()β returns a string describing the characteristic properties ('READ','WRITE', etc).getHandle()β returns the 16-bit integer value used to identify the characteristic in the underlying GATT protocol. This may be useful to distinguish between notifications from different characteristics (see Working with notifications (#notifications) for further information).
πΈ Properties
All the properties listed below are read-only. Periodt.
uuidβ the Bluetooth UUID for this characteristic.peripheralβ the Peripheral object for the device to which the characteristic belongs.propertiesβ a bitmask of properties for the characteristic.
π THE DESCRIPTOR CLASS π
The Descriptor class is a placeholder. bluepy does not currently support any useful operations with descriptors. That's it. That's the whole section. π
π WORKING WITH NOTIFICATIONS π
In bluepy, notifications are processed by creating a "delegate" object and registering it with the Peripheral. A method in the delegate is called whenever a notification is received from the peripheral, as shown below:
π¬ handleNotification(cHandle, data)
Called when a notification has been received from a Peripheral. Normally you will call the peripheral's waitForNotifications() method to allow this, but note that a Bluetooth LE device may transmit notifications at any time. This means handleNotification() can potentially be called when any BluePy call is in progress. Keep that in mind, bestie.
The cHandle parameter is the GATT 'handle' for the characteristic which is sending the notification. If a peripheral sends notifications for more than one characteristic, this may be used to distinguish them. The 'handle' value can be found by calling the getHandle() method of a Characteristic object.
The data parameter is a str (Python 2.x) or bytes (Python 3.x) value containing the notification data. It is recommended you use Python's struct module to unpack this, to allow portability between language versions. Very demure, very portable. π
It is recommended that the class used for the delegate object is derived from btle.DefaultDelegate. This will ensure that an appropriate default method exists for any future calls which may be added to the delegate interface.
π§ Example code
Code to receive notifications from a peripheral can follow the outline below:
import btle
class MyDelegate(btle.DefaultDelegate):
def __init__(self, params):
btle.DefaultDelegate.__init__(self)
# ... initialise here
def handleNotification(self, cHandle, data):
# ... perhaps check cHandle
# ... process 'data'
# Initialisation -------
p = btle.Peripheral( address )
p.setDelegate( MyDelegate(params) )
# Setup to turn notifications on, e.g.
# svc = p.getServiceByUUID( service_uuid )
# ch = svc.getCharacteristics( char_uuid )[0]
# ch.write( setup_data )
# Main loop --------
while True:
if p.waitForNotifications(1.0):
# handleNotification() was called
continue
print "Waiting..."
# Perhaps do something else here
π ASSIGNED NUMBERS π
The AssignedNumbers object is a convenient way to refer to common Bluetooth-related Assigned Numbers by using textual names. So, for instance AssignedNumbers.firmwareRevisionString is a UUID object for the Firmware Revision String characteristic identifier (0x2A26). Iconic.
The complete list of Bluetooth assigned numbers is given at https://www.bluetooth.org/en-us/specification/assigned-numbers
The current version of bluepy includes the following defined values:
alertNotificationServicebatteryLevelbatteryServicebloodPressurecurrentTimeServicecyclingPowercyclingSpeedAndCadencedeviceInformationdeviceNamefirmwareRevisionStringgenericAccessgenericAttributeglucosehardwareRevisionStringhealthThermometerheartRatehumanInterfaceDeviceimmediateAlertlinkLosslocationAndNavigationmanufacturerNameStringmodelNumberStringnextDstChangeServicephoneAlertStatusServicereferenceTimeUpdateServicerunningSpeedAndCadencescanParametersserialNumberStringsoftwareRevisionStringtxPowertxPowerLeveluserData
Tiny doc-nav bits on the page: Index, Module Index, Search Page.
π Author
Ian Harvey
Β© Copyright
2014, Ian Harvey
π And that's the whole BLUEPY(1) page, bestie! Source/version: 0.9, dated Dec 14, 2025. You ate that. Periodt. π
β¨
π¦ where this page comes from
- arch rolling: python-bluepy 1.3.0-12 Β· GPL2
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms