Skip to content

Commit 95dd07f

Browse files
authored
Merge pull request #233 from geza-pycom/Bluetooth_sync
Synchronize Bluetooth documentation between development-publish and publish branch
2 parents 77f02a9 + 61bb260 commit 95dd07f

File tree

3 files changed

+86
-64
lines changed

3 files changed

+86
-64
lines changed

content/firmwareapi/pycom/network/bluetooth/_index.md

Lines changed: 58 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
---
22
title: "Bluetooth"
33
aliases:
4+
- chapter/firmwareapi/pycom/network/bluetooth
45
---
56

67
This class provides a driver for the Bluetooth radio in the module. Currently, only basic BLE functionality is available.
@@ -60,14 +61,18 @@ bluetooth = Bluetooth()
6061

6162
## Methods
6263

63-
### bluetooth.init(id=0, mode=Bluetooth.BLE, antenna=None, secure=False)
64+
#### bluetooth.init(id=0, mode=Bluetooth.BLE, antenna=None, modem\_sleep=True, pin=None, privacy=True, secure\_connections=True, mtu=200)
6465

65-
* `id` Only one Bluetooth peripheral available so must always be 0
66-
* `mode` currently the only supported mode is `Bluetooth.BLE`
67-
* `antenna` selects between the internal and the external antenna. Can be either`Bluetooth.INT_ANT`, `Bluetooth.EXT_ANT`.
68-
* `secure` enables or disables the GATT Server security features.
66+
* `id` Only one Bluetooth peripheral available so must always be 0.
67+
* `mode` currently the only supported mode is `Bluetooth.BLE`.
68+
* `antenna` selects between the internal and the external antenna. Can be either `Bluetooth.INT_ANT`, `Bluetooth.EXT_ANT`.
69+
* `modem_sleep` Enables or Disables BLE modem sleep, Disable modem sleep as a workaround when having Crashes due to flash cache being disabled, as this prevents BLE task saving data in external RAM while accesing external flash for R/W.
70+
* `pin` a one to six digit number (`0`-`9`) to connect to the GATT Sever. Setting any valid pin, GATT Server security features are activated.
71+
* `privacy` Enables or Disables local privacy settings so address will be random or public.
72+
* `secure_connections` Enables or Disables Secure Connections and MITM Protection.
73+
* `mtu` Maximum Transmission Unit (MTU) is the maximum length of an ATT packet. Value must be between `23` and `200`.
6974

70-
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.
75+
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.
7176

7277
Initialises and enables the Bluetooth radio in BLE mode.
7378

@@ -84,7 +89,7 @@ Pin('P12', mode=Pin.OUT)(True)
8489

8590
Disables the Bluetooth radio.
8691

87-
### bluetooth.start\_scan(timeout)
92+
#### bluetooth.start\_scan(timeout)
8893

8994
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.
9095

@@ -95,20 +100,19 @@ The arguments are:
95100
Examples:
96101

97102
```python
98-
99103
bluetooth.start_scan(10) # starts scanning and stop after 10 seconds
100104
bluetooth.start_scan(-1) # starts scanning indefinitely until bluetooth.stop_scan() is called
101105
```
102106

103-
### bluetooth.stop\_scan()
107+
#### bluetooth.stop\_scan()
104108

105109
Stops an ongoing scanning process. Returns `None`.
106110

107-
### bluetooth.isscanning()
111+
#### bluetooth.isscanning()
108112

109113
Returns `True` if a Bluetooth scan is in progress. `False` otherwise.
110114

111-
### bluetooth.get\_adv()
115+
#### bluetooth.get\_adv()
112116

113117
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)`
114118

@@ -121,7 +125,6 @@ Gets an named tuple with the advertisement data received during the scanning. Th
121125
Example for getting `mac` address of an advertiser:
122126

123127
```python
124-
125128
import ubinascii
126129

127130
bluetooth = Bluetooth()
@@ -131,11 +134,11 @@ adv = bluetooth.get_adv() #
131134
ubinascii.hexlify(adv.mac) # convert hexadecimal to ascii
132135
```
133136

134-
### bluetooth.get\_advertisements()
137+
#### bluetooth.get\_advertisements()
135138

136139
Same as the `get_adv()` method, but this one returns a list with all the advertisements received.
137140

138-
### bluetooth.resolve\_adv\_data(data, data\_type)
141+
#### bluetooth.resolve\_adv\_data(data, data\_type)
139142

140143
Parses the advertisement data and returns the requested `data_type` if present. If the data type is not present, the function returns `None`.
141144

@@ -147,7 +150,6 @@ Arguments:
147150
Example:
148151

149152
```python
150-
151153
import ubinascii
152154
from network import Bluetooth
153155
bluetooth = Bluetooth()
@@ -166,18 +168,20 @@ while bluetooth.isscanning():
166168
print(ubinascii.hexlify(mfg_data))
167169
```
168170

169-
### bluetooth.connect(mac\_addr)
171+
#### bluetooth.set\_pin()
170172

171-
Opens a BLE connection with the device specified by the `mac_addr` argument. This function blocks until the connection succeeds or fails. If the connections succeeds it returns a object of type `GATTCConnection`.
173+
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.
172174

173-
Connections are initiated by the central device. There is a maximum of 4 simultaneous connections.
175+
#### bluetooth.connect(mac\_addr, timeout=None)
174176

175-
```python
177+
* `mac_addr` is the address of the remote device to connect
178+
* `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`.
176179

180+
```python
177181
bluetooth.connect('112233eeddff') # mac address is accepted as a string
178182
```
179183

180-
### bluetooth.callback(trigger=None, handler=None, arg=None)
184+
#### bluetooth.callback(trigger=None, handler=None, arg=None)
181185

182186
Creates a callback that will be executed when any of the triggers occurs. The arguments are:
183187

@@ -187,14 +191,13 @@ Creates a callback that will be executed when any of the triggers occurs. The ar
187191

188192
An example of how this may be used can be seen in the [`bluetooth.events()`](./#bluetooth-events) method.
189193

190-
### bluetooth.events()
194+
#### bluetooth.events()
191195

192196
Returns a value with bit flags identifying the events that have occurred since the last call. Calling this function clears the events.
193197

194198
Example of usage:
195199

196200
```python
197-
198201
from network import Bluetooth
199202

200203
bluetooth = Bluetooth()
@@ -212,7 +215,7 @@ bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONN
212215
bluetooth.advertise(True)
213216
```
214217

215-
### bluetooth.set\_advertisement(\* , name=None, manufacturer\_data=None, service\_data=None, service\_uuid=None)
218+
#### bluetooth.set\_advertisement(\* , name=None, manufacturer\_data=None, service\_data=None, service\_uuid=None)
216219

217220
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.
218221

@@ -226,15 +229,27 @@ The arguments are:
226229
Example:
227230

228231
```python
229-
230232
bluetooth.set_advertisement(name="advert", manufacturer_data="lopy_v1")
231233
```
232234

233-
### bluetooth.advertise(\[Enable\])
235+
#### bluetooth.set\_advertisement\_params(\* , adv\_int\_min=0x20, adv\_int\_max=0x40, adv\_type=Bluetooth.ADV\_TYPE\_IND, own\_addr\_type=Bluetooth.BLE\_ADDR\_TYPE\_PUBLIC, channel\_map=Bluetooth.ADV\_CHNL\_ALL, adv\_filter\_policy=Bluetooth.ADV\_FILTER\_ALLOW\_SCAN\_ANY\_CON\_ANY)
236+
237+
Configure the parameters used when advertising.
238+
239+
The arguments are:
240+
241+
* `adv_int_min` is the minimum advertising interval for undirected and low duty cycle directed advertising.
242+
* `adv_int_max` is the maximum advertising interval for undirected and low duty cycle directed advertising.
243+
* `adv_type` is the advertising type.
244+
* `own_addr_type` is the owner bluetooth device address type.
245+
* `channel_map` is the advertising channel map.
246+
* `adv_filter_policy` is the advertising filter policy.
247+
248+
#### bluetooth.advertise(\[Enable\])
234249

235250
Start or stop sending advertisements. The `set_advertisement()` method must have been called prior to this one.
236251

237-
### bluetooth.service(uuid, \* , isprimary=True, nbr\_chars=1, start=True)
252+
#### bluetooth.service(uuid, \* , isprimary=True, nbr\_chars=1, start=True)
238253

239254
Create a new service on the internal GATT server. Returns a object of type `BluetoothServerService`.
240255

@@ -246,20 +261,35 @@ The arguments are:
246261
* `start` if `True` the service is started immediately.
247262

248263
```python
249-
250264
bluetooth.service('abc123')
251265
```
252266

253-
### bluetooth.disconnect\_client()
267+
#### bluetooth.disconnect\_client()
254268

255269
Closes the BLE connection with the client.
256270

271+
### bluetooth.tx\_power(type, level)
272+
273+
Gets or sets the TX Power level.
274+
If called with only `type` parameter it returns with the current value belonging to the given type.
275+
If both `type` and `level` parameters are given, it sets the TX Power.
276+
277+
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
278+
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
279+
257280
## Constants
258281

259282
* Bluetooth mode: `Bluetooth.BLE`
260283
* Advertisement type: `Bluetooth.CONN_ADV`, `Bluetooth.CONN_DIR_ADV`, `Bluetooth.DISC_ADV`, `Bluetooth.NON_CONN_ADV`, `Bluetooth.SCAN_RSP`
261284
* Address type: `Bluetooth.PUBLIC_ADDR`, `Bluetooth.RANDOM_ADDR`, `Bluetooth.PUBLIC_RPA_ADDR`, `Bluetooth.RANDOM_RPA_ADDR`
262285
* Advertisement data type: `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`
286+
* Advertisement parameters: `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`
263287
* Characteristic properties (bit values that can be combined): `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`
264288
* Characteristic callback events: `Bluetooth.CHAR_READ_EVENT`, `Bluetooth.CHAR_WRITE_EVENT`, `Bluetooth.NEW_ADV_EVENT`, `Bluetooth.CLIENT_CONNECTED`, `Bluetooth.CLIENT_DISCONNECTED`, `Bluetooth.CHAR_NOTIFY_EVENT`
265289
* Antenna type: `Bluetooth.INT_ANT`, `Bluetooth.EXT_ANT`
290+
* TX Power type: `Bluetooth.TX_PWR_CONN`, `Bluetooth.TX_PWR_ADV`, `Bluetooth.TX_PWR_SCAN`, `Bluetooth.TX_PWR_DEFAULT`
291+
* TX Power level: `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`
292+
293+
## Exceptions
294+
295+
* `Bluetooth.timeout`

content/firmwareapi/pycom/network/bluetooth/gattscharacteristic.md

Lines changed: 27 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -21,70 +21,63 @@ characteristic.value(123) # set characteristic value to an integer with the valu
2121
characteristic.value() # get characteristic value
2222
```
2323

24+
#### characteristic.events()
25+
26+
Returns a value with bit flags, identifying the events that have occurred since the last call. Calling this function clears the events.
27+
2428
#### characteristic.callback(trigger=None, handler=None, arg=None)
2529

26-
Creates a callback that will be executed when any of the triggers occurs. The arguments are:
30+
Creates a callback that will be executed when any of the triggers occur. The arguments are:
2731

2832
* `trigger` can be either `Bluetooth.CHAR_READ_EVENT` or `Bluetooth.CHAR_WRITE_EVENT`.
2933
* `handler` is the function that will be executed when the callback is triggered.
3034
* `arg` is the argument that gets passed to the callback. If nothing is given, the characteristic object that owns the callback will be used.
3135

32-
An example of how this could be implemented can be seen in the [`characteristic.events()` ](gattscharacteristic.md#characteristic-events)section.
36+
Beyond the `arg` a tuple (called `data`) is also passed to `handler`. The tuple consists of (event, value), where `event` is the triggering event and `value` is the value strictly belonging to the `event` in case of a WRITE event. If the `event` is not a WRITE event, the `value` has no meaning.
3337

34-
#### characteristic.events()
35-
36-
Returns a value with bit flags identifying the events that have occurred since the last call. Calling this function clears the events.
38+
We recommend getting both the `event` and new `value` of the characteristic via this tuple, and not via `characteristic.event()` and `characteristic.value()` calls in the context of the `handler` to make sure no event and value is lost.
39+
The reason behind this is that `characteristic.event()` and `characteristic.value()` return with the very last event received and with the current value of the characteristic, while the input parameters are always linked to the specific event triggering the `handler`. If the device is busy executing other operations, the `handler` of an incoming event may not be called before the next event occurs and is processed.
3740

38-
An example of advertising and creating services on the device:
41+
An example of how this can be implemented is shown below, via an example of advertising and creating services on the device:
3942

4043
```python
4144

4245
from network import Bluetooth
4346

44-
bluetooth = Bluetooth()
45-
bluetooth.set_advertisement(name='LoPy', service_uuid=b'1234567890123456')
46-
4747
def conn_cb (bt_o):
4848
events = bt_o.events()
4949
if events & Bluetooth.CLIENT_CONNECTED:
5050
print("Client connected")
5151
elif events & Bluetooth.CLIENT_DISCONNECTED:
5252
print("Client disconnected")
5353

54-
bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb)
54+
def char1_cb_handler(chr, data):
55+
56+
# The data is a tuple containing the triggering event and the value if the event is a WRITE event.
57+
# We recommend fetching the event and value from the input parameter, and not via characteristic.event() and characteristic.value()
58+
events, value = data
59+
if events & Bluetooth.CHAR_WRITE_EVENT:
60+
print("Write request with value = {}".format(value))
61+
else:
62+
print('Read request on char 1')
5563

64+
def char2_cb_handler(chr, data):
65+
# The value is not used in this callback as the WRITE events are not processed.
66+
events, value = data
67+
if events & Bluetooth.CHAR_READ_EVENT:
68+
print('Read request on char 2')
69+
70+
bluetooth = Bluetooth()
71+
bluetooth.set_advertisement(name='LoPy', service_uuid=b'1234567890123456')
72+
bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb)
5673
bluetooth.advertise(True)
5774

5875
srv1 = bluetooth.service(uuid=b'1234567890123456', isprimary=True)
59-
6076
chr1 = srv1.characteristic(uuid=b'ab34567890123456', value=5)
61-
62-
char1_read_counter = 0
63-
def char1_cb_handler(chr):
64-
global char1_read_counter
65-
char1_read_counter += 1
66-
67-
events = chr.events()
68-
if events & Bluetooth.CHAR_WRITE_EVENT:
69-
print("Write request with value = {}".format(chr.value()))
70-
else:
71-
if char1_read_counter < 3:
72-
print('Read request on char 1')
73-
else:
74-
return 'ABC DEF'
75-
7677
char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT | Bluetooth.CHAR_READ_EVENT, handler=char1_cb_handler)
7778

7879
srv2 = bluetooth.service(uuid=1234, isprimary=True)
79-
8080
chr2 = srv2.characteristic(uuid=4567, value=0x1234)
81-
char2_read_counter = 0xF0
82-
def char2_cb_handler(chr):
83-
global char2_read_counter
84-
char2_read_counter += 1
85-
if char2_read_counter > 0xF1:
86-
return char2_read_counter
87-
8881
char2_cb = chr2.callback(trigger=Bluetooth.CHAR_READ_EVENT, handler=char2_cb_handler)
8982
```
9083

content/firmwareapi/pycom/network/bluetooth/gattsservice.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,11 @@ Stops the service if previously started.
2727
Creates a new characteristic on the service. Returns an object of the class `GATTSCharacteristic`. The arguments are:
2828

2929
* `uuid` is the UUID of the service. Can take an integer or a 16 byte long string or bytes object.
30-
* `permissions` configures the permissions of the characteristic. Takes an integer with a combination of the flags.
30+
* `permissions` configures the permissions of the characteristic. Takes an integer with a combination of the flags. When bluetooth object is initialized with PIN, read and write permissions are set to encrypted. Setting PIN later with set_pin() call does not affect the permissions of the already existing characteristics, thus they will remain not secured.
3131
* `properties` sets the properties. Takes an integer with an OR-ed combination of the flags.
3232
* `value` sets the initial value. Can take an integer, a string or a bytes object.
3333

3434
```python
3535

3636
service.characteristic('temp', value=25)
3737
```
38-

0 commit comments

Comments
 (0)