This class provides a driver for the Bluetooth radio in the module. Currently, only basic BLE functionality is available.
from network import Bluetooth import time bt = Bluetooth() bt.start_scan(-1) while True: adv = bt.get_adv() if adv and bt.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL) == 'Heart Rate': try: conn = bt.connect(adv.mac) services = conn.services() for service in services: time.sleep(0.050) if type(service.uuid()) == bytes: print('Reading chars from service = {}'.format(service.uuid())) else: print('Reading chars from service = %x' % service.uuid()) chars = service.characteristics() for char in chars: if (char.properties() & Bluetooth.PROP_READ): print('char {} value = {}'.format(char.uuid(), char.read())) conn.disconnect() break except: print("Error while connecting or reading from the BLE device") break else: time.sleep(0.050)
Bluetooth low energy (BLE) is a subset of classic Bluetooth, designed for easy connecting and communicating between devices (in particular mobile platforms). BLE uses a methodology known as Generic Access Profile (GAP) to control connections and advertising.
GAP allows for devices to take various roles but generic flow works with devices that are either a Server (low power, resource constrained, sending small payloads of data) or a Client device (commonly a mobile device, PC or SG Device with large resources and processing power). SG devices can act as both a Client and a Server.
Create a Bluetooth object, and optionally configure it. See init for params of configuration.
Example:
from network import Bluetooth bluetooth = Bluetooth()
id
mode
Bluetooth.BLE
modem_sleep
antenna
bluetooth.INT_ANT
bluetooth.EXT_ANT
bluetooth.MAN_ANT
P12
secure
pin
privacy
secure_connections
mtu
23
200
With our development boards it defaults to using the internal antenna, but in the case of an OEM module, the antenna pin (P12) is not used, so it’s free to be used for other things. Initialises and enables the Bluetooth radio in BLE mode.
Disables the Bluetooth radio.
Starts performing a scan listening for BLE devices sending advertisements. This function always returns immediately, the scanning will be performed on the background. The return value is None. After starting the scan the function get_adv() can be used to retrieve the advertisements messages from the FIFO. The internal FIFO has space to cache 16 advertisements.
None
get_adv()
The arguments are:
timeout
Examples:
bluetooth.start_scan(10) # starts scanning and stop after 10 seconds bluetooth.start_scan(-1) # starts scanning indefinitely until bluetooth.stop_scan() is called
Stops an ongoing scanning process. Returns None.
Returns True if a Bluetooth scan is in progress. False otherwise.
True
False
Gets an named tuple with the advertisement data received during the scanning. The tuple has the following structure: (mac, addr_type, adv_type, rssi, data)
(mac, addr_type, adv_type, rssi, data)
mac
addr_type
adv_type
rssi
data
resolve_adv_data()
Example for getting MAC address of an advertiser:
import ubinascii bluetooth = Bluetooth() bluetooth.start_scan(20) # scan for 20 seconds adv = bluetooth.get_adv() # ubinascii.hexlify(adv.mac) # convert hexadecimal to ascii
Same as the get_adv() method, but this one returns a list with all the advertisements received.
Parses the advertisement data and returns the requested data_type if present. If the data type is not present, the function returns None.
data_type
Arguments:
import ubinascii from network import Bluetooth bluetooth = Bluetooth() bluetooth.start_scan(20) while bluetooth.isscanning(): adv = bluetooth.get_adv() if adv: # try to get the complete name print(bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_NAME_CMPL)) mfg_data = bluetooth.resolve_adv_data(adv.data, Bluetooth.ADV_MANUFACTURER_DATA) if mfg_data: # try to get the manufacturer data (Apple's iBeacon data is sent here) print(ubinascii.hexlify(mfg_data))
Configures a new PIN to be used by the device. The PIN is a 1-6 digit length decimal number, if less than 6 digits are given the missing leading digits are considered as 0. E.g. 1234 becomes 001234. When a new PIN is configured, the information of all previously bonded device is removed and the current connection is terminated. To restart advertisement the advertise() must be called after PIN is changed.
mac_addr
Bluetooth.timeout TimeoutError
GATTCConnection
bluetooth.connect('112233eeddff') # mac address is accepted as a string
Creates a callback that will be executed when any of the triggers occurs. The arguments are:
trigger
Bluetooth.NEW_ADV_EVENT
Bluetooth.CLIENT_CONNECTED
Bluetooth.CLIENT_DISCONNECTED
handler
arg
An example of how this may be used can be seen in the bluetooth.events() method.
bluetooth.events
()
Returns a value with bit flags identifying the events that have occurred since the last call. Calling this function clears the events.
Example of usage:
from network import Bluetooth bluetooth = Bluetooth() bluetooth.set_advertisement(name='LoPy', service_uuid=b'1234567890123456') def conn_cb (bt_o): events = bt_o.events() # this method returns the flags and clears the internal registry if events & Bluetooth.CLIENT_CONNECTED: print("Client connected") elif events & Bluetooth.CLIENT_DISCONNECTED: print("Client disconnected") bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb) bluetooth.advertise(True)
Configure the data to be sent while advertising. If left with the default of None the data won’t be part of the advertisement message.
name
manufacturer_data
service_data
service_uuid
bluetooth.set_advertisement(name="advert", manufacturer_data="lopy_v1")
Configure the parameters used when advertising.
adv_int_min
adv_int_max
own_addr_type
channel_map
adv_filter_policy
Start or stop sending advertisements. The set_advertisement() method must have been called prior to this one.
set_advertisement()
Create a new service on the internal GATT server. Returns a object of type BluetoothServerService.
BluetoothServerService
uuid
isprimary
bool
nbr_chars
start
bluetooth.service('abc123')
Closes the BLE connection with the client.
Gets or sets the TX Power level. If called with only type parameter it returns with the current value belonging to the given type. If both type and level parameters are given, it sets the TX Power.
type
level
Valid values for type: Bluetooth.TX_PWR_CONN -> for handling connection, Bluetooth.TX_PWR_ADV -> for advertising, Bluetooth.TX_PWR_SCAN -> for scan, Bluetooth.TX_PWR_DEFAULT -> default, if others not set Valid values for level: Bluetooth.TX_PWR_N12-> -12dbm,Bluetooth.TX_PWR_N9-> -9dbm,Bluetooth.TX_PWR_N6-> -6dbm,Bluetooth.TX_PWR_N3-> -3dbm,Bluetooth.TX_PWR_0-> 0dbm,Bluetooth.TX_PWR_P3-> 3dbm,Bluetooth.TX_PWR_P6-> 6dbm,Bluetooth.TX_PWR_P9` -> 9dbm
Bluetooth.TX_PWR_CONN
Bluetooth.TX_PWR_ADV
Bluetooth.TX_PWR_SCAN
Bluetooth.TX_PWR_DEFAULT
-> -12dbm,
-> -9dbm,
-> -6dbm,
-> -3dbm,
-> 0dbm,
-> 3dbm,
-> 6dbm,
Bluetooth.CONN_ADV
Bluetooth.CONN_DIR_ADV
Bluetooth.DISC_ADV
Bluetooth.NON_CONN_ADV
Bluetooth.SCAN_RSP
Bluetooth.PUBLIC_ADDR
Bluetooth.RANDOM_ADDR
Bluetooth.PUBLIC_RPA_ADDR
Bluetooth.RANDOM_RPA_ADDR
Bluetooth.ADV_FLAG
Bluetooth.ADV_16SRV_PART
Bluetooth.ADV_T16SRV_CMPL
Bluetooth.ADV_32SRV_PART
Bluetooth.ADV_32SRV_CMPL
Bluetooth.ADV_128SRV_PART
Bluetooth.ADV_128SRV_CMPL
Bluetooth.ADV_NAME_SHORT
Bluetooth.ADV_NAME_CMPL
Bluetooth.ADV_TX_PWR
Bluetooth.ADV_DEV_CLASS
Bluetooth.ADV_SERVICE_DATA
Bluetooth.ADV_APPEARANCE
Bluetooth.ADV_ADV_INT
Bluetooth.ADV_32SERVICE_DATA
Bluetooth.ADV_128SERVICE_DATA
Bluetooth.ADV_MANUFACTURER_DATA
Bluetooth.ADV_TYPE_IND
Bluetooth.ADV_TYPE_DIRECT_IND_HIGH
Bluetooth.ADV_TYPE_SCAN_IND
Bluetooth.ADV_TYPE_NONCONN_IND
Bluetooth.ADV_TYPE_DIRECT_IND_LOW
Bluetooth.ADV_BLE_ADDR_TYPE_PUBLIC
Bluetooth.ADV_BLE_ADDR_TYPE_RANDOM
Bluetooth.ADV_BLE_ADDR_TYPE_RPA_PUBLIC
Bluetooth.ADV_BLE_ADDR_TYPE_RPA_RANDOM
Bluetooth.ADV_CHNL_37
Bluetooth.ADV_CHNL_38
Bluetooth.ADV_CHNL_39
Bluetooth.ADV_CHNL_ALL
Bluetooth.ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY
Bluetooth.ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY
Bluetooth.ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST
Bluetooth.ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST
Bluetooth.PROP_BROADCAST
Bluetooth.PROP_READ
Bluetooth.PROP_WRITE_NR
Bluetooth.PROP_WRITE
Bluetooth.PROP_NOTIFY
Bluetooth.PROP_INDICATE
Bluetooth.PROP_AUTH
Bluetooth.PROP_EXT_PROP
Bluetooth.CHAR_READ_EVENT
Bluetooth.CHAR_WRITE_EVENT
Bluetooth.CHAR_NOTIFY_EVENT
Bluetooth.CHAR_SUBSCRIBE_EVENT
Bluetooth.INT_ANT
Bluetooth.EXT_ANT
Bluetooth.MAN_ANT
Bluetooth.TX_PWR_N12
Bluetooth.TX_PWR_N9
Bluetooth.TX_PWR_N6
Bluetooth.TX_PWR_N3
Bluetooth.TX_PWR_0
Bluetooth.TX_PWR_P3
Bluetooth.TX_PWR_P6
Bluetooth.TX_PWR_P9
Bluetooth.timeout