BLE (canvas_ble)
The modules described in this chapter provide the interface to the Bluetooth Low Energy (BLE) stack in the radio module.
- class canvas_ble.Advertiser
The Advertiser class provides for two buffers that can be populated by the application: an advertising buffer and a scan response buffer. The application cannot inspect or modify in-place either of these buffers. Instead, methods are provided to clear the buffer and to add data to the buffer. When advertising is started with
start()
or updated withupdate()
, the current contents of the buffer is copied into the BLE stack to be used. Until eitherstart()
orupdate()
are called, the application can clear/update the buffers at will without any consequence.Data in the buffers needs to be in the BLE LTV (length, tag, value) format. The methods
add_ltv()
andadd_tag_string()
will assist with this by adding the length and tag fields. Additional care needs to be taken with theadd_data()
method to ensure that the data is in the proper format.Constants for some of the possible tag (sometimes also called type) values exist in the
canvas_ble
module. The application can also use any other value that is valid for the BLE LTV format. See the canvas_ble.AD_TYPE_* constants.The size of the advertising buffer is platform- and configuration-dependent. Legacy advertising (non-extended) is limited to 31 bytes in each of the advertising and scan response buffers. Extended advertising allows for considerably larger buffers, but the size is still platform-dependent.
Only one instance of the Advertiser class should ever be created. Multiple advertising sets is not currently implemented.
- add_canvas_data(config_version: int, network_id: int, scan: bool)
Add Canvas-specific data to a buffer. This is a convenience function that adds the Canvas-specific data to the buffer. The Canvas-specific data helps to identify the device as a Canvas device that a common set of tools can use.
The Canvas data will take 23 bytes in the buffer. The application should chose to use either the advertising buffer or the scan response buffer to add the Canvas data depending on how the application will be using the advertisement data. There is no reason to include the Canvas data in both buffers.
- Parameters:
config_version (int) – Configuration version of the device. This is a 8-bit value that is incremented each time the configuration is changed. The parameter is required, but if an application is not using the configuration version, it can be set to 0.
network_id (int) – Network ID of the device. The parameter is required, but if an application is not using the network ID, it can be set to 0.
scan (bool) – Buffer to which to add. False to add to advertising buffer or True to add to scan response buffer.
- add_data(data: any, scan: bool)
Add data to a buffer. This function adds raw data bytes into the selected buffer. The application must ensure that the buffer contents contain proper BLE TLVs.
- Parameters:
data (bytes) – Bytes to add to the buffer
scan (bool) – Buffer to which to add. False to add to advertising buffer or True to add to scan response buffer.
- add_ltv(tag: int, data: any, scan: bool)
Add a byte-based LTV to a buffer.
Add manufacturer-specific data to the advertising buffer using a manufacturer ID of 0x0201 and data of 0x03, 0x04:
>>> advertiser = canvas_ble.Advertiser() >>> advertiser.add_ltv(canvas_ble.AD_TYPE_MANU_SPECIFIC, b'\x01\x02\x03\x04', False)
- Parameters:
tag (int) – Tag is a one-byte value defined by the BLE specification
data (bytes) – Data to add to the buffer
scan (bool) – Buffer to which to add. False to add to advertising buffer or True to add to scan response buffer.
- add_smp_uuid(scan: bool)
Add the SMP UUID to a buffer. This is a convenience function that adds the SMP UUID to the buffer. The SMP UUID is a 128-bit value defined by the BLE specification.
- Parameters:
scan (bool) – Buffer to which to add. False to add to advertising buffer or True to add to scan response buffer.
- add_tag_string(tag: int, string: str, scan: bool)
Add a string-based LTV to a buffer.
Add a device name to the scan response:
>>> advertiser = canvas_ble.Advertiser() >>> advertiser.add_tag_string(canvas_ble.AD_TYPE_NAME_COMPLETE, "Canvas", True)
- Parameters:
tag (int) – Tag is a one-byte value defined by the BLE specification
string (str) – String to add to the buffer
scan (bool) – Buffer to which to add. False to add to advertising buffer or True to add to scan response buffer.
- clear_buffer(scan: bool)
Clears a buffer
- Parameters:
scan (bool) – Buffer to clear. False to clear advertising buffer or True to clear scan response buffer
- set_channel_mask(mask: any)
Set the channel mask to be used for advertising. The mask is a 37-bit value with each bit corresponding to a channel. A value of 1 indicates that the channel will be used. A value of 0 indicates that the channel will not be used.
- Parameters:
mask (bytes) – Channel mask to use for advertising. Should be 5 bytes in length. The first byte is the LSB of the mask (channel 0).
- set_directed(directed: bool, mac: any)
Set the directed advertisement flag and the MAC address of the target device.
- Parameters:
directed (bool) – True if the advertisement should be directed
mac (bytes) – MAC address of the target device. This is a required parameter if directed is True. If directed is False, then this parameter must be None.
- set_interval(min: int, max: int)
Set the advertising interval range to be used by the BLE stack. Many stacks require a range of values here to allow for some flexibility in the scheduling of advertisement packets. The min and max values are specified in milliseconds and cannot be the same.
Advertise interval set to a value between 100 and 200 milliseconds (selected by the BLE stack):
>>> advertiser = canvas_ble.Advertiser() >>> advertiser.set_interval(100, 200)
- Parameters:
min (int) – Minimum advertising interval in milliseconds
max (int) – Maximum advertising interval in milliseconds
- set_phys(primary: int, secondary: int)
Set the PHYs that will be used for advertising. Values for PHYs should be taken from the canvas_ble.PHY_* constants. Only one primary PHY and one secondary PHY can be used at a time (not a bitmask of PHYs).
For legacy (non-extended) advertising, only the 1M PHY can be used and there is no secondary PHY. For extended advertising, the 1M PHY is the default primary PHY and the 2M PHY is the default secondary PHY.
Valid combinations of PHYs:
Primary PHY
Secondary PHY
Lyra 24
Sera NX040
1M
1M
Yes
Yes
1M
2M
Yes
Yes
1M
Coded
Yes
No
2M
1M
No, 2M cannot be used as primary
2M
2M
2M
Coded
Coded
1M
Yes
No
Coded
2M
Yes
No
Coded
Coded
Yes
Yes
Advertise using only the 1M PHY for both primary and secondary:
>>> advertiser = canvas_ble.Advertiser() >>> advertiser.set_properties(True, False, True) >>> advertiser.set_phys(canvas_ble.PHY_1M, canvas_ble.PHY_1M)
- param int primary:
Primary PHY to use for advertising
- param int secondary:
Secondary PHY to use for advertising
- set_properties(connectable: bool, scannable: bool, extended: bool)
Set the advertisement properties.
A connectable advertisement allows a BLE central device to connect to this device.
A scannable advertisement allows a BLE central device to scan for this device and receive additional scan response data from the device on top of the regular advertisement data.
An extended advertisement allows the use of PHYs other than the 1M PHY for advertising. Extended advertising is required for the use of the 2M PHY or the coded PHY. The extended advertisement also allows for a considerably larger advertisement buffer (platform-dependent).
An extended advertisement cannot be both connectable and scannable.
For the Lyra products, if a non-extended advertisement is connectable, it must also be scannable.
Use legacy advertising:
>>> advertiser = canvas_ble.Advertiser() >>> advertiser.set_properties(True, False, False)
Use extended advertising with a connectable advertisement:
>>> advertiser = canvas_ble.Advertiser() >>> advertiser.set_properties(True, False, True)
- Parameters:
connectable (bool) – True if the advertisement should be connectable
scannable (bool) – True if the advertisement should be scannable
extended (bool) – True if extended advertising should be used
- start()
Start advertising. The advertising buffer is copied into the BLE stack and the advertising is started. The application can continue to update the advertising buffer and call update() to change the advertising data.
- stop()
Stop advertising.
- update()
Update the advertising data. The advertising buffer is copied into the BLE stack and the advertising continues.
- validate_data() bool
Perform a validation test on the advertising and scan buffers.
- Returns:
True if the buffers contain valid LTVs or False if there is an error in either buffer.
- class canvas_ble.Connection
The Connection class provides handling of connections to other BLE devices. Connections can be in either Central or Peripheral roles.
When in a Peripheral role, the
set_periph_callbacks()
function is used to set up callbacks for connection and disconnection events.The
Connection
object is passed into this callback so it can be saved by the script for later use.When in a Central role, the
connect()
function is used to initiate a connection. This function takes individual callback functions for when this particular connection is fully connected and for when it is fully disconnected.The
Connection
object should not be created directly. Instead, it is created by the BLE stack when a connection is made.- change_security(level: int)
Change the security level of the connection.
- Parameters:
level – The new security level to use.
- delete_pairing(all: bool)
Delete the pairing information for the connection.
This will cause the device to forget the pairing information and require a new pairing to be established.
- Parameters:
all – If True, delete all pairing information for the device. If False, only delete the pairing information for this connection.
- disconnect()
Disconnect the connection.
The
Connection
object should no longer be used after this method is called.
- get_addr() any
Return the address of the connected device for this connection
- Returns:
The address of the connected device as a bytes array
- get_rssi() int
Return the RSSI of the connection
- Returns:
The RSSI of the connection as a signed value in dBm.
- set_security_cb(cb: any)
Set the callback to be used when the security level of the connection changes.
The callback function will take a :py:class:`Connection object and an integer representing the new security level.
Example:
>>> def security_cb(conn, level): ... print("Security level changed to {}".format(level)) ... >>> conn.set_security_cb(security_cb)
- Parameters:
cb – A callback used when the security level changes
- class canvas_ble.GattClient(connection: Connection)
The GattClient class allows a device to discover and interact with the GATT server on a remotely-connected BLE device.
All functions use __errCode to return a standard error code.
- Parameters:
connection (Connection) – The
Connection
object associated with the BLE connection to use for the GATT client.
- configure_subscription(identifier: str, flags: int)
Map enable to a better name, but preserve compatibility.
- discover()
Before interaction with a remote GATT server, the GATT database must be discovered. This discovery creates and populates an internal database of GATT services, characteristics, and descriptors.
The discovered database can be augmented by assigning friendly names to UUIDs after discovery by using the
set_name()
method.
- enable(identifier: str, enable: int)
Enable or disable a CCCD with the given identifier. A CCCD enables or disables a notification or indication
Example:
>>> gatt_client.enable("b8d00002-6329-ef96-8a4d-55b376d8b25a", ... gatt_client.CCCD_STATE_NOTIFY)
- Parameters:
uuid (str) – A string representation of an identifier present within the GATT database that is to be set. If this identifier is not present in the GATT database or is not for a CCCD an error will occur.
enable (int) –
The value of this parameter should be set to:
canvas_ble.GattClient.CCCD_STATE_DISABLE
to disable notifications and indications.canvas_ble.GattClient.CCCD_STATE_NOTIFY
to enable only notifications.canvas_ble.GattClient.CCCD_STATE_INDICATE
to enable only indications.canvas_ble.GattClient.CCCD_STATE_BOTH
to enable both notifications and indications. Server decides what type to send. Only one type can be sent at a time.
- get_dict() any
Returns a dictionary describing the discovered GATT database.
- Returns:
a dictionary describing the discovered GATT database.
- read(identifier: str) any
Read the value of a characteristic identified by the given UUID.
- Parameters:
identifier (str) – A string representation of an identifier present within the GATT database that is to be read. If this identifier is not present in the GATT database or is not of a readable type an error will occur.
- Returns:
bytes containing the data read.
- set_callbacks(notify: any, indicate: any)
Callbacks can be set for any notifications or indications the GATT Server might make.
The callback function will be passed a named tuple containing the following entries:
- connection
The
Connection
object for which the event was caused.- UUID
The UUID if the characteristic that this event is associated with.
- name
If a name has been set for the UUID, it is included.
- data
bytes data attached to the event.
Example:
>>> def notify_cb(event): ... print("Notification from {} on UUID {} with data {}".format( ... canvas_ble.addr_to_str(event.connection.get_addr()), ... event.uuid, binascii.hexlify(event.data).decode())) ... >>> client.set_callbacks(notify_cb, None)
- Parameters:
notify – A callback to be called when a notification is received from the connected server.
indicate – A callback to be called when an indication is received from the connected server.
- set_name(uuid: str, name: str)
Once a GATT database has been discovered a more descriptive name can be given to the services, characteristics and descriptors stored in it. These names can be given in place of a UUID for identifier parameters to methods.
- Parameters:
uuid (str) – A string representation of a UUID present in the GATT database.
name (str) – A unique, within the GATT database, string that can be used to refer to GATT object instead of its UUID.
- write(identifier: str, data: any)
Write a value to a characteristic identified by the given identifier.
- Parameters:
identifier (str) – A string representation of a identifier present within the GATT database that is to be written. If this identifier is not present in the GATT database or is not of a writable type an error will occur.
data (bytes) – bytes containing the data to be written
- CCCD_STATE_BOTH: int
Enable both notifications and indications. Server decides what type to send Only one type can be sent at a time.
- CCCD_STATE_DISABLE: int
Disable notifications and indications
- CCCD_STATE_INDICATE: int
Enable Indications
- CCCD_STATE_NOTIFY: int
Enable Notifications
- class canvas_ble.GattServer
The GattServer class allows creation and use of a GATT Server on the device.
Only one instance of the GattServer class can ever be created. Multiple GattServer instances are not supported at this time.
“Read” and “Write” functionality are from the CLIENT perspective. e.g. A “Read”able characteristic will have data written to it by this GattServer class and be read by the client and vice versa.
All functions use __errCode to return a standard error code.
GATT Server Event Constants
The GATT server can cause the stack to raise a number of different events for each characteristic. These events can be received by the caller by use of a callback (see
build_from_dict()
).As only a single callback is available for each event, the EVENT_* constants are used to indicate the specific event that caused the callback to be triggered.
GATT Server Callbacks
Characteristics can sometimes need to respond to events. This is achieved through the use of a callback system. A callback can be specified when defining a characteristic in the GATT Server dictionary.
A callback is a Python function that recieves a named tuple as a parameter:
def my_callback(event):
Depending on the underlying event causing the callback to be called the event tuple will have various named members. These can be one or more of:
- type
The type of event. This is always present.
- connection
The connection object of the connection that caused the event. This is always present.
- name
The name of the characteristic that caused the event. This is present in:
- data
The characteristics new value as bytes. This is present in:
If
canvas_ble.GattServer.EVENT_INDICATION_TIMEOUT
is received, the connection concerned is deemed to have failed. If the disconnect callback fromConnection
has not been recieved and dealt with then the connection should be closed and deleted when an event of typecanvas_ble.GattServer.INDICATION_TIMEOUT
is received.- build_from_dict(description: dict)
Builds the GATT server from a correctly formatted dictionary.
The format of the GATT server dictionary is as follows. Services are a dictionary containing description keys and a dictionary of Characteristics Characteristics are a dictionary containing only description keys.
The GATT server is NOT started after this function is used.
Available description keys are:
- “Service N”
Indicates a Service dictionary where N is a unique identifier within the GATT server dictionary.
- “Characteristic N”
Indicates a Characteristic dictionary where N is a unique identifier within the Service dictionary.
- “UUID”
A string hexadecimal representation of the service or characteristics UUID. 16 and 128 bit UUIDs are supported. 128 bit UUIDS can be formatted using ‘-’ characters for clarity (e.g., “b8d00002-6329-ef96-8a4d-55b376d8b25a”).
- “Name”
A unique name for the service or characteristic. This is best kept short yet descriptive and is used to reference that individual item.
- “Capability”
Defines the characteristic type. Available types are currently:
- “Read”
The characteristic can be read by the connected client.
- “Write”
The characteristic can be written to by the connected client. No acknowledgement is provided by the server. (Write without response)
- “WriteAck”
The characteristic can be written to by the connected client. The write will be acknowledged by the server. (Write with response)
- “Notify”
The characteristic can be used to notify the connected client of a changed value. The notification is not acknowledged by the client. An applicable CCCD will automatically be created for this characteristic.
- “Indicate”
The characteristic can be used to notify the connected client of a changed value. The notification will be acknowledged by the client. An applicable CCCD will automatically be created for this characteristic.
Note some types can be combined. Currently, these are:
“Read Write”
“Read WriteAck”
- “Length”
The length the data in the characteristic in bytes. The data is initialised to zeros upon the GATT server being started.
- “Read Encryption”
Defines the level of read encryption for this characteristic. Available values are:
- “None”
No encryption
- “Encrypt”
Requires bonding and encrypted connection.
- “Mitm”
Requires authenticated pairing and encrypted connection.
- “Write Encryption”
Defines the level of write encryption for this characteristic. Values as per “Read Encryption”.
- “Callback”
Provides the facility to supply a callback to allow the script to receive events pertaining to the characteristic.
- Parameters:
description – The dictionary containing the GATT server description.
- indicate(connection: Connection, name: str, value: any)
Indicates to the client through the named characteristic with a value. The characteristic must have the “Indicate” capability.
- Parameters:
connection (Connection) – The connection to be used. This is the
Connection
class object.name (str) – The name of the characteristic to use for the indication.
value (bytes) – The value to be used in the indication.
- notify(connection: Connection, name: str, value: any)
Notifies the client through the named characteristic with a value. The characteristic must have the “Notify” capability.
- Parameters:
connection (Connection) – The connection to be used. This is the
Connection
class object.name (str) – The name of the characteristic to use for the notification.
value (bytes) – The value to be used in the notification.
- read(name: str) any
Reads the current value of a “Write” characteristic.
- Parameters:
name (str) – The “Name” of the characteristic to be read
- Returns:
bytes containing the data read.
- start()
Starts the GATT server.
- stop()
Stops the GATT server.
- write(name: str, value: any)
Writes a new value into a “Read” characteristic
- Parameters:
name (str) – The “Name” of the characteristic to be written
value (bytes) – The new value to be written.
- EVENT_ATTR_VALUE: int
Raised when a client writes to a writeable characteristic.
- EVENT_CCCD_BOTH: int
Raised when a client sets a Characteristics CCCD so both notifications and indications are enabled.
- EVENT_CCCD_INDICATE: int
Raised when a client sets a Characteristics CCCD so indications are enabled.
- EVENT_CCCD_NONE: int
Raised when a client sets a Characteristics CCCD so both notifications and indications are disabled.
- EVENT_CCCD_NOTIFY: int
Raised when a client sets a Characteristics CCCD so notifications are enabled.
- EVENT_INDICATION_OK: int
Raised when an indication is acknowledged
- EVENT_INDICATION_TIMEOUT: int
Raised when an indication exceeds it’s acknowlegement timeout
- class canvas_ble.Scanner
Class for BLE scanning. This class is a singleton, only one scanner can be instantiated at a time. Attempting to instantiate a second scanner will return the existing instance.
Example:
>>> def scan_cb(event): ... print("Received advertisement from {}".format(canvas_ble.addr_to_str(event.addr))) ... print(" RSSI: {}".format(event.rssi)) ... print(" Type: {}".format(event.type)) ... print(" Data: {}".format(binascii.hexlify(event.data).decode())) ... >>> scanner = canvas_ble.Scanner(scan_cb) >>> scanner.start(True)
- Parameters:
cb –
Callback function to be called when a BLE advertisement is received. The callback function must accept a single argument, which will be a named tuple of the form (rssi, type, data, addr). The rssi is the received signal strength indicator, the type is the advertisement type, the data is the advertisement data, and the addr is the MAC address of the device that sent the advertisement. ‘type’ will be a bitmask of one or more of the following values:
canvas_ble.Scanner.TYPE_CONNECTABLE
: Connectable advertisement.canvas_ble.Scanner.TYPE_SCANNABLE
: Scannable advertisement.canvas_ble.Scanner.TYPE_DIRECTED
: Directed advertisement.canvas_ble.Scanner.TYPE_SCAN_RESPONSE
: Scan response.canvas_ble.Scanner.TYPE_LEGACY
: Legacy advertisement.canvas_ble.Scanner.TYPE_EXTENDED
: Extended advertisement.
- filter_add(type: int, data: any)
Add a filter to the scanner.
In areas where there is a lot of BLE advertisements, it may be desirable to filter the advertisements. This function allows the user to set filters on the scanner to only receive advertisements that match the filter. This helps to reduce the processing time needed to handle advertisements and allows the Python application to focus only on the advertisements that are of interest.
The type parameter is the type of the filter to set on the advertisement data. The data parameter is particular to the type of filter being set.
The following filter types are supported:
canvas_ble.Scanner.FILTER_NAME
: The data parameter is a string. The name of the device in the advertisement must match the string in its entirety.canvas_ble.Scanner.FILTER_UUID
: The data parameter is a UUID string. The size of the data determines the UUID type to filter on. Two bytes of data are required for a 16-bit UUID, four bytes of data are required for a 32-bit UUID, and 16 bytes of data are required for a 128-bit UUID.canvas_ble.Scanner.FILTER_ADDR
: The data parameter is a BLE address byte string.canvas_ble.Scanner.FILTER_MANUF_DATA
: The data parameter is a byte string of manufacturer data. This data is compared to the manufacturer data in the advertisement. The first two bytes of the data are always the manufacturer ID. The filter data can be smaller than the advertisement data to allow matching only on the manufacturer ID or manufacturer ID and a portion of the manufacturer- specific data.canvas_ble.Scanner.FILTER_DATA
: The data parameter is a byte string of generic data. The filter matches if the data in the advertisement contains the filter data in its entirety at any location.
Example to filter on device name:
>>> scanner = canvas_ble.Scanner(scan_cb) >>> scanner.filter_add(canvas_ble.Scanner.FILTER_NAME, "Canvas".encode())
- Parameters:
type (int) – Type of filter to set.
data (bytes) – Filter data.
- filter_reset()
Remove all of the filters from the scanner.
- set_phys(phys: int)
Set the PHYs to scan on. The phys parameter is a bitmask of the PHYs to scan on. The bitmask is a combination of the following values:
canvas_ble.PHY_1M
,canvas_ble.PHY_2M
, andcanvas_ble.PHY_CODED
.Example:
>>> scanner = canvas_ble.Scanner(scan_cb) >>> scanner.set_phys(canvas_ble.PHY_1M | canvas_ble.PHY_2M)
- Parameters:
phys (int) – Bitmask of the PHYs to scan on.
- set_timing(interval_ms: int, window_ms: int)
Set the scan timing. The interval_ms parameter is the scan interval in milliseconds, and the window_ms parameter is the scan window in milliseconds. The scan window must be less than or equal to the scan interval.
Example to scan roughly 50% of the time (50 milliseconds out of every 100 milliseconds):
>>> scanner = canvas_ble.Scanner(scan_cb) >>> scanner.set_timing(100, 50)
- Parameters:
interval_ms (int) – Scan interval in milliseconds.
window_ms (int) – Scan window in milliseconds.
- start(active: bool)
Start the scanner. The active parameter is a boolean value that indicates whether the scanner should be active or passive. If the value is True, the scanner will send scan requests to devices that advertise with a scannable advertisement type. If the value is False, the scanner will not send scan requests.
- Parameters:
active (bool) – Boolean value indicating whether the scanner should be active (True) or passive (False).
- stop()
Stop the scanner.
- FILTER_ADDR: int
Filter on device MAC address.
- FILTER_DATA: int
Filter on generic bytes in advertisement.
- FILTER_MANUF_DATA: int
Filter on bytes from manufacturer-specific data in advertisement.
- FILTER_NAME: int
Filter on device name in advertisement.
- FILTER_UUID: int
Filter on UUID in advertisement.
- TYPE_CONNECTABLE: int
Connectable advertisement.
- TYPE_DIRECTED: int
Directed advertisement.
- TYPE_EXTENDED: int
Extended advertisement.
- TYPE_LEGACY: int
Legacy (not extended) advertisement.
- TYPE_SCANNABLE: int
Scannable advertisement.
- TYPE_SCAN_RESPONSE: int
Scan response data
- canvas_ble.addr_to_str(addr: any) str
Convert a BLE address into a printable string.
Example:
>>> mine = canvas_ble.my_addr() >>> mine b'\x01\xd3\xae\\~\xa8\xf7' >>> canvas_ble.addr_to_str(mine) '01f7a87e5caed3'
- Parameters:
addr (bytes) – The BLE address to convert.
- Returns:
A string representation of the address.
- canvas_ble.connect(addr: any, phy: int, cb_con: any, cb_discon: any) Connection
Initiate a connection when in a Central role.
Example:
>>> def connection_cb(conn): ... print("Connection established with {}".format( ... canvas_ble.addr_to_str(conn.get_addr()))) ... >>> def disconnection_cb(conn): ... print("Connection closed with {}".format( ... canvas_ble.addr_to_str(conn.get_addr()))) ... >>> addr = canvas_ble.str_to_addr("01f7a87e5caed3") >>> conn = canvas_ble.connect(addr, canvas_ble.PHY_1M, connection_cb, disconnection_cb) Connection established with 01f7a87e5caed3 >>> conn->disconnect()
- Parameters:
addr (bytes) – A bytes object containing the BLE address to connect to.
canvas_ble.str_to_addr()
can be used to create this from an appropriate string.phy (int) – The PHY to use (one of the canvas_ble.PHY_* constants)
cb_con – A callback used when a connection has been established
cb_discon – A callback used when the connection ends
- Returns:
The
Connection
object for the new connection or None on error.
- canvas_ble.find_ltv(type: int, ad: any) any
Find the first LTV (length, type, value) tuple in the advertisement data that matches the given type. The type parameter is the type of the LTV to find. The ad parameter is the advertisement data to search.
Example:
>>> def scan_cb(data): ... ltv = canvas_ble.find_ltv(canvas_ble.AD_TYPE_NAME_COMPLETE, data.data) ... if ltv is not None: ... print("Device name: {}".format(ltv.decode())) ... >>> scanner = canvas_ble.Scanner(scan_cb) >>> scanner.start(True)
- Parameters:
type (int) – Type of LTV to find.
ad (bytes) – Advertisement data to search.
- Returns:
A bytes object containing the value of the LTV tuple found or None if no LTV tuple matches the given type. If a matching LTV occurs more than once in the advertising data, only the first occurrence will be returned.
- canvas_ble.get_actual_tx_power() int
Get the current actual TX power. This returns the value the module is actually transmitting at. In the example below the region is set to UK, for certain modules this will limit the maximum TX power to 7.0dbm even if a higher power is requested. This function returns that limited value.
- Example::
>>> canvas_ble.set_region(canvas_ble.REGION_UK) >>> canvas_ble.set_tx_power(100) >>> canvas_ble.get_actual_tx_power() >>> 70
- Returns:
The curent actual TX power in 0.1dbm steps.
- canvas_ble.get_region() int
Get the currnt BLE regulatory region
- Example::
>>> canvas_ble.set_region(canvas_ble.REGION_UK) >>> canvas_ble.get_region() >>> 2
- Returns:
The current BLE regulatory region
- canvas_ble.get_tx_power() int
Get the current requested TX power. This returns the value set by the previous set_tx_power call, or the default value for the module if there has been no previous set_tx_power call.
- Example::
>>> canvas_ble.set_tx_power(100) >>> canvas_ble.get_tx_power() >>> 100
- Returns:
The last requested BLE TX power value in 0.1dbm steps.
- canvas_ble.init()
Initialize the BLE stack. This function must be called before any other function in this module. It should only be called once.
- canvas_ble.my_addr() any
Get the local BLE address.
Example:
>>> mine = canvas_ble.my_addr() >>> mine b'\x01\xd3\xae\\~\xa8\xf7' >>> canvas_ble.addr_to_str(mine) '01f7a87e5caed3'
- Returns:
The BLE address of the local device.
- canvas_ble.set_periph_callbacks(con: any, discon: any)
Set the callbacks to be used when the device is operating in a Peripheral role. The callback functions will take a
Connection
object as their parameter.Example:
>>> def connection_cb(conn): ... print("Connection established with {}".format( ... canvas_ble.addr_to_str(conn.get_addr()))) ... >>> def disconnection_cb(conn): ... print("Connection closed with {}".format( ... canvas_ble.addr_to_str(conn.get_addr()))) ... >>> canvas_ble.set_periph_callbacks(connection_cb, disconnection_cb)
- Parameters:
con – A callback used when a connection is made
discon – A callback used when a disconnection is made
- canvas_ble.set_region(region: int)
Set the BLE regulatory region Note: This can only be called successfully when the BLE system is not advertising, scanning, connected, etc. Note: On Zephyr/nRF devices, the region is fixed to :py:data:canvas_ble.REGION_GLOBAL.
- Example::
>>> canvas_ble.set_region(canvas_ble.REGION_UK)
- Parameters:
region (int) – The region to be used
- canvas_ble.set_tx_power(power_dbm10: int)
Set the power used for BLE transmission in 0.1dbm steps. The power level set may differ from that actually used due to the regulatory region set and the module used. This can only be called successfully when the BLE system is not advertising, scanning, connected, etc. Note: On Zephyr/nRF devices, TX power defaults to 0dbm. Fractional power values may be rounded before being applied. Use :py:meth:get_tx_power to see the applied tx power value.
- Example::
>>> canvas_ble.set_tx_power(70)
- Parameters:
power_dbm10 (int) – The power to be used in 0.1 dbm steps. For example 25 is 2.5dbm
- canvas_ble.str_to_addr(addr_str: str) any
Convert a BLE address string into a binary representation usable by the BLE stack.
Example:
>>> mine = canvas_ble.my_addr() >>> mine b'\x01\xd3\xae\\~\xa8\xf7' >>> mine_str = canvas_ble.addr_to_str(mine) >>> mine_str '01f7a87e5caed3' >>> canvas_ble.str_to_addr(mine_str) b'\x01\xd3\xae\\~\xa8\xf7'
- Parameters:
addr_str (str) – The BLE address string to convert.
- Returns:
A binary representation of the address.
- canvas_ble.AD_TYPE_FLAGS: int
Advertisement type value for flags
- canvas_ble.AD_TYPE_MANU_SPECIFIC: int
Advertisement type value for manufacturer-specific data
- canvas_ble.AD_TYPE_NAME_COMPLETE: int
Advertisement type value for a complete device name
- canvas_ble.AD_TYPE_NAME_SHORT: int
Advertisement type value for a shortened device name
- canvas_ble.AD_TYPE_UUID128_COMPLETE: int
Advertisement type value for a complete list of 128-bit UUIDs
- canvas_ble.AD_TYPE_UUID128_INCOMPLETE: int
Advertisement type value for an incomplete list of 128-bit UUIDs
- canvas_ble.AD_TYPE_UUID16_COMPLETE: int
Advertisement type value for a complete list of 16-bit UUIDs
- canvas_ble.AD_TYPE_UUID16_INCOMPLETE: int
Advertisement type value for an incomplete list of 16-bit UUIDs
- canvas_ble.AD_TYPE_UUID32_COMPLETE: int
Advertisement type value for a complete list of 32-bit UUIDs
- canvas_ble.AD_TYPE_UUID32_INCOMPLETE: int
Advertisement type value for an incomplete list of 32-bit UUIDs
- canvas_ble.PHY_125K: int
Coded PHY at 125kbits/sec
- canvas_ble.PHY_1M: int
1M PHY
- canvas_ble.PHY_2M: int
2M PHY
- canvas_ble.PHY_500K: int
Coded PHY at 500kbits/sec
- canvas_ble.PHY_CODED: int
Coded PHY, generic
- canvas_ble.REGION_AUSTRALIA: int
Australia region
- canvas_ble.REGION_CANADA: int
Canada region
- canvas_ble.REGION_EU: int
EU region
- canvas_ble.REGION_GLOBAL: int
Global region
- canvas_ble.REGION_JAPAN: int
Japan region
- canvas_ble.REGION_NEW_ZEALAND: int
New Zealand region
- canvas_ble.REGION_SOUTH_KOREA: int
South Korea region
- canvas_ble.REGION_UK: int
UK region
- canvas_ble.REGION_USA: int
USA region