This class provides a driver for the Bluetooth radio in the module. Currently, only basic BLE functionality is available.
Quick Usage Example
from network import Bluetoothimport timebt =Bluetooth()bt.start_scan(-1)whileTrue: 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)iftype(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()breakexcept:print("Error while connecting or reading from the BLE device")breakelse: time.sleep(0.050)
Bluetooth Low Energy (BLE)
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 Pycom Device with large resources and processing power). Pycom devices can act as both a Client and a Server.
Constructors
class network.Bluetooth(id=0, ...)
Create a Bluetooth object, and optionally configure it. See init for params of configuration.
id Only one Bluetooth peripheral available so must always be 0
mode currently the only supported mode is Bluetooth.BLE
antenna selects between the internal and the external antenna. Can be either
Bluetooth.INT_ANT, Bluetooth.EXT_ANT.
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.
bluetooth.deinit()
Disables the Bluetooth radio.
bluetooth.start_scan(timeout)
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.
The arguments are:
timeout specifies the amount of time in seconds to scan for advertisements, cannot be zero. If timeout is > 0, then the BLE radio will listen for advertisements until the specified value in seconds elapses. If timeout < 0, then there’s no timeout at all, and stop_scan() needs to be called to cancel the scanning process.
Examples:
bluetooth.stop_scan()
Stops an ongoing scanning process. Returns None.
bluetooth.isscanning()
Returns True if a Bluetooth scan is in progress. False otherwise.
bluetooth.get_adv()
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 is the 6-byte ling mac address of the device that sent the advertisement.
addr_type is the address type. See the constants section below for more details.
adv_type is the advertisement type received. See the constants section below fro more details.
rssi is signed integer with the signal strength of the advertisement.
data contains the complete 31 bytes of the advertisement message. In order to parse the data and get the specific types, the method resolve_adv_data() can be used.
Example for getting mac address of an advertiser:
bluetooth.get_advertisements()
Same as the get_adv() method, but this one returns a list with all the advertisements received.
bluetooth.resolve_adv_data(data, data_type)
Parses the advertisement data and returns the requested data_type if present. If the data type is not present, the function returns None.
Arguments:
data is the bytes object with the complete advertisement data.
data_type is the data type to resolve from from the advertisement data. See constants section below for details.
Example:
bluetooth.connect(mac_addr, timeout=None)
mac_addr is the address of the remote device to connect
timeout specifies the amount of time in milliseconds to wait for the connection process to finish. If not given then no timeout is applied The function blocks until the connection succeeds or fails (raises OSError) or the given timeout expires (raises Bluetooth.timeout TimeoutError). If the connections succeeds it returns a object of type GATTCConnection.
from network import Bluetooth
bluetooth = Bluetooth()
bluetooth.start_scan(10) # starts scanning and stop after 10 seconds
bluetooth.start_scan(-1) # starts scanning indefinitely until bluetooth.stop_scan() is called
import ubinascii
bluetooth = Bluetooth()
bluetooth.start_scan(20) # scan for 20 seconds
adv = bluetooth.get_adv() #
ubinascii.hexlify(adv.mac) # convert hexadecimal to ascii
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))
bluetooth.connect('112233eeddff') # mac address is accepted as a string
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)