Refine _bleio

This PR refines the _bleio API. It was originally motivated by
the addition of a new CircuitPython service that enables reading
and modifying files on the device. Moving the BLE lifecycle outside
of the VM motivated a number of changes to remove heap allocations
in some APIs.

It also motivated unifying connection initiation to the Adapter class
rather than the Central and Peripheral classes which have been removed.
Adapter now handles the GAP portion of BLE including advertising, which
has moved but is largely unchanged, and scanning, which has been enhanced
to return an iterator of filtered results.

Once a connection is created (either by us (aka Central) or a remote
device (aka Peripheral)) it is represented by a new Connection class.
This class knows the current connection state and can discover and
instantiate remote Services along with their Characteristics and
Descriptors.

Relates to #586
crypto-aes
Scott Shawcroft 3 years ago
parent 84c0d6cdf8
commit ae30a1e5aa
No known key found for this signature in database
GPG Key ID: 9349BC7E64B1921E
  1. 2
      lib/utils/interrupt_char.c
  2. 13
      main.c
  3. 7
      ports/nrf/background.c
  4. 28
      ports/nrf/bluetooth/ble_drv.c
  5. 7
      ports/nrf/bluetooth/ble_drv.h
  6. 9
      ports/nrf/boards/adafruit_nrf52840_s140_v6.ld
  7. 525
      ports/nrf/common-hal/_bleio/Adapter.c
  8. 20
      ports/nrf/common-hal/_bleio/Adapter.h
  9. 145
      ports/nrf/common-hal/_bleio/Central.c
  10. 126
      ports/nrf/common-hal/_bleio/Characteristic.c
  11. 5
      ports/nrf/common-hal/_bleio/Characteristic.h
  12. 12
      ports/nrf/common-hal/_bleio/CharacteristicBuffer.c
  13. 629
      ports/nrf/common-hal/_bleio/Connection.c
  14. 38
      ports/nrf/common-hal/_bleio/Connection.h
  15. 58
      ports/nrf/common-hal/_bleio/Descriptor.c
  16. 9
      ports/nrf/common-hal/_bleio/Descriptor.h
  17. 361
      ports/nrf/common-hal/_bleio/Peripheral.c
  18. 105
      ports/nrf/common-hal/_bleio/Scanner.c
  19. 48
      ports/nrf/common-hal/_bleio/Service.c
  20. 12
      ports/nrf/common-hal/_bleio/Service.h
  21. 23
      ports/nrf/common-hal/_bleio/UUID.c
  22. 489
      ports/nrf/common-hal/_bleio/__init__.c
  23. 5
      ports/nrf/common-hal/_bleio/__init__.h
  24. 5
      py/circuitpy_defns.mk
  25. 7
      py/ringbuf.h
  26. 2
      py/vm.c
  27. 300
      shared-bindings/_bleio/Adapter.c
  28. 28
      shared-bindings/_bleio/Adapter.h
  29. 30
      shared-bindings/_bleio/Address.c
  30. 207
      shared-bindings/_bleio/Central.c
  31. 43
      shared-bindings/_bleio/Central.h
  32. 33
      shared-bindings/_bleio/Characteristic.c
  33. 6
      shared-bindings/_bleio/Characteristic.h
  34. 171
      shared-bindings/_bleio/Connection.c
  35. 19
      shared-bindings/_bleio/Connection.h
  36. 9
      shared-bindings/_bleio/Descriptor.c
  37. 2
      shared-bindings/_bleio/Descriptor.h
  38. 325
      shared-bindings/_bleio/Peripheral.c
  39. 48
      shared-bindings/_bleio/Peripheral.h
  40. 74
      shared-bindings/_bleio/ScanEntry.c
  41. 3
      shared-bindings/_bleio/ScanEntry.h
  42. 72
      shared-bindings/_bleio/ScanResults.c
  43. 17
      shared-bindings/_bleio/ScanResults.h
  44. 129
      shared-bindings/_bleio/Scanner.c
  45. 74
      shared-bindings/_bleio/Service.c
  46. 14
      shared-bindings/_bleio/Service.h
  47. 51
      shared-bindings/_bleio/UUID.c
  48. 5
      shared-bindings/_bleio/UUID.h
  49. 19
      shared-bindings/_bleio/__init__.c
  50. 18
      shared-bindings/_bleio/__init__.h
  51. 43
      shared-module/_bleio/ScanEntry.c
  52. 7
      shared-module/_bleio/ScanEntry.h
  53. 138
      shared-module/_bleio/ScanResults.c
  54. 64
      shared-module/_bleio/ScanResults.h
  55. 8
      supervisor/shared/autoreload.c
  56. 2
      supervisor/shared/autoreload.h
  57. 341
      supervisor/shared/bluetooth.c
  58. 24
      supervisor/shared/bluetooth.h
  59. 3
      supervisor/shared/safe_mode.h
  60. 5
      supervisor/supervisor.mk

@ -49,7 +49,7 @@ void mp_keyboard_interrupt(void) {
// Check to see if we've been CTRL-C'ed by autoreload or the user.
bool mp_hal_is_interrupted(void) {
return MP_STATE_VM(mp_pending_exception) == MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_kbd_exception));
return MP_STATE_VM(mp_pending_exception) != NULL;
}
#endif

@ -69,6 +69,11 @@
#include "shared-module/board/__init__.h"
#endif
#if CIRCUITPY_BLEIO
#include "shared-bindings/_bleio/__init__.h"
#include "supervisor/shared/bluetooth.h"
#endif
void do_str(const char *src, mp_parse_input_kind_t input_kind) {
mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, src, strlen(src), 0);
if (lex == NULL) {
@ -439,6 +444,10 @@ int __attribute__((used)) main(void) {
// Start serial and HID after giving boot.py a chance to tweak behavior.
serial_init();
#if CIRCUITPY_BLEIO
supervisor_start_bluetooth();
#endif
// Boot script is finished, so now go into REPL/main mode.
int exit_code = PYEXEC_FORCED_EXIT;
bool skip_repl = true;
@ -475,6 +484,10 @@ void gc_collect(void) {
displayio_gc_collect();
#endif
#if CIRCUITPY_BLEIO
common_hal_bleio_gc_collect();
#endif
// This naively collects all object references from an approximate stack
// range.
gc_collect_root((void**)sp, ((uint32_t)port_stack_get_top() - sp) / sizeof(uint32_t));

@ -41,6 +41,10 @@
#include "common-hal/audiopwmio/PWMAudioOut.h"
#endif
#if CIRCUITPY_BLEIO
#include "supervisor/shared/bluetooth.h"
#endif
static bool running_background_tasks = false;
void background_tasks_reset(void) {
@ -62,6 +66,9 @@ void run_background_tasks(void) {
i2s_background();
#endif
#if CIRCUITPY_BLEIO
supervisor_bluetooth_background();
#endif
#if CIRCUITPY_DISPLAYIO
displayio_background();

@ -38,6 +38,8 @@
#include "py/misc.h"
#include "py/mpstate.h"
#include "supervisor/shared/bluetooth.h"
nrf_nvic_state_t nrf_nvic_state = { 0 };
// Flag indicating progress of internal flash operation.
@ -52,6 +54,14 @@ void ble_drv_reset() {
sd_flash_operation_status = SD_FLASH_OPERATION_DONE;
}
void ble_drv_add_event_handler_entry(ble_drv_evt_handler_entry_t* entry, ble_drv_evt_handler_t func, void *param) {
entry->next = MP_STATE_VM(ble_drv_evt_handler_entries);
entry->param = param;
entry->func = func;
MP_STATE_VM(ble_drv_evt_handler_entries) = entry;
}
void ble_drv_add_event_handler(ble_drv_evt_handler_t func, void *param) {
ble_drv_evt_handler_entry_t *it = MP_STATE_VM(ble_drv_evt_handler_entries);
while (it != NULL) {
@ -64,11 +74,7 @@ void ble_drv_add_event_handler(ble_drv_evt_handler_t func, void *param) {
// Add a new handler to the front of the list
ble_drv_evt_handler_entry_t *handler = m_new_ll(ble_drv_evt_handler_entry_t, 1);
handler->next = MP_STATE_VM(ble_drv_evt_handler_entries);
handler->param = param;
handler->func = func;
MP_STATE_VM(ble_drv_evt_handler_entries) = handler;
ble_drv_add_event_handler_entry(handler, func, param);
}
void ble_drv_remove_event_handler(ble_drv_evt_handler_t func, void *param) {
@ -127,10 +133,20 @@ void SD_EVT_IRQHandler(void) {
break;
}
ble_evt_t* event = (ble_evt_t *)m_ble_evt_buf;
if (supervisor_bluetooth_hook(event)) {
continue;
}
ble_drv_evt_handler_entry_t *it = MP_STATE_VM(ble_drv_evt_handler_entries);
bool done = false;
while (it != NULL) {
it->func((ble_evt_t *)m_ble_evt_buf, it->param);
done = it->func(event, it->param) || done;
it = it->next;
}
if (!done) {
//mp_printf(&mp_plat_print, "Unhandled ble event: 0x%04x\n", event->header.evt_id);
}
}
}

@ -29,6 +29,8 @@
#ifndef MICROPY_INCLUDED_NRF_BLUETOOTH_BLE_DRV_H
#define MICROPY_INCLUDED_NRF_BLUETOOTH_BLE_DRV_H
#include <stdbool.h>
#include "ble.h"
#define MAX_TX_IN_PROGRESS 10
@ -48,7 +50,7 @@
#define UNIT_1_25_MS (1250)
#define UNIT_10_MS (10000)
typedef void (*ble_drv_evt_handler_t)(ble_evt_t*, void*);
typedef bool (*ble_drv_evt_handler_t)(ble_evt_t*, void*);
typedef enum {
SD_FLASH_OPERATION_DONE,
@ -69,4 +71,7 @@ void ble_drv_reset(void);
void ble_drv_add_event_handler(ble_drv_evt_handler_t func, void *param);
void ble_drv_remove_event_handler(ble_drv_evt_handler_t func, void *param);
// Allow for user provided entries to prevent allocations outside the VM.
void ble_drv_add_event_handler_entry(ble_drv_evt_handler_entry_t* entry, ble_drv_evt_handler_t func, void *param);
#endif // MICROPY_INCLUDED_NRF_BLUETOOTH_BLE_DRV_H

@ -16,6 +16,7 @@
0x00000000..0x00000FFF (4KB) Master Boot Record
*/
/* Specify the memory areas (S140 6.x.x) */
MEMORY
{
@ -26,7 +27,10 @@ MEMORY
FLASH_FATFS (r) : ORIGIN = 0x000AD000, LENGTH = 0x040000
/* 0x2000000 - RAM:ORIGIN is reserved for Softdevice */
RAM (xrw) : ORIGIN = 0x20004000, LENGTH = 0x20040000 - 0x20004000
/* SoftDevice 6.1.0 takes 0x1628 bytes (5.54 kb) minimum. */
/* To measure the minimum required amount of memory for given configuration, set this number
high enough to work and then check the mutation of the value done by sd_ble_enable. */
RAM (xrw) : ORIGIN = 0x20000000 + 16K, LENGTH = 256K - 16K
}
/* produce a link error if there is not this amount of RAM for these sections */
@ -38,7 +42,8 @@ _minimum_heap_size = 0;
/*_stack_end = ORIGIN(RAM) + LENGTH(RAM);*/
_estack = ORIGIN(RAM) + LENGTH(RAM);
/* RAM extents for the garbage collector */
/* RAM extents for the garbage collector and soft device init */
_ram_start = ORIGIN(RAM);
_ram_end = ORIGIN(RAM) + LENGTH(RAM);
_heap_end = 0x20020000; /* tunable */

@ -26,6 +26,7 @@
* THE SOFTWARE.
*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
@ -34,11 +35,18 @@
#include "nrfx_power.h"
#include "nrf_nvic.h"
#include "nrf_sdm.h"
#include "tick.h"
#include "py/gc.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "supervisor/shared/safe_mode.h"
#include "supervisor/usb.h"
#include "shared-bindings/_bleio/__init__.h"
#include "shared-bindings/_bleio/Adapter.h"
#include "shared-bindings/_bleio/Address.h"
#include "shared-bindings/_bleio/Connection.h"
#include "shared-bindings/_bleio/ScanEntry.h"
#include "shared-bindings/time/__init__.h"
#define BLE_MIN_CONN_INTERVAL MSEC_TO_UNITS(15, UNIT_0_625_MS)
#define BLE_MAX_CONN_INTERVAL MSEC_TO_UNITS(15, UNIT_0_625_MS)
@ -46,10 +54,13 @@
#define BLE_CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS)
STATIC void softdevice_assert_handler(uint32_t id, uint32_t pc, uint32_t info) {
mp_raise_msg_varg(&mp_type_AssertionError,
translate("Soft device assert, id: 0x%08lX, pc: 0x%08lX"), id, pc);
reset_into_safe_mode(NORDIC_SOFT_DEVICE_ASSERT);
}
bleio_connection_internal_t connections[BLEIO_TOTAL_CONNECTION_COUNT];
// Linker script provided ram start.
extern uint32_t _ram_start;
STATIC uint32_t ble_stack_enable(void) {
nrf_clock_lf_cfg_t clock_config = {
#if BOARD_HAS_32KHZ_XTAL
@ -78,34 +89,56 @@ STATIC uint32_t ble_stack_enable(void) {
// Start with no event handlers, etc.
ble_drv_reset();
uint32_t app_ram_start;
app_ram_start = 0x20004000;
// Set everything up to have one persistent code editing connection and one user managed
// connection. In the future we could move .data and .bss to the other side of the stack and
// dynamically adjust for different memory requirements of the SD based on boot.py
// configuration.
uint32_t app_ram_start = (uint32_t) &_ram_start;
ble_cfg_t ble_conf;
ble_conf.conn_cfg.conn_cfg_tag = BLE_CONN_CFG_TAG_CUSTOM;
ble_conf.conn_cfg.params.gap_conn_cfg.conn_count = BLE_GAP_CONN_COUNT_DEFAULT;
ble_conf.conn_cfg.params.gap_conn_cfg.conn_count = BLEIO_TOTAL_CONNECTION_COUNT;
// Event length here can influence throughput so perhaps make multiple connection profiles
// available.
ble_conf.conn_cfg.params.gap_conn_cfg.event_length = BLE_GAP_EVENT_LENGTH_DEFAULT;
err_code = sd_ble_cfg_set(BLE_CONN_CFG_GAP, &ble_conf, app_ram_start);
if (err_code != NRF_SUCCESS)
if (err_code != NRF_SUCCESS) {
return err_code;
}
memset(&ble_conf, 0, sizeof(ble_conf));
ble_conf.gap_cfg.role_count_cfg.periph_role_count = 1;
ble_conf.gap_cfg.role_count_cfg.adv_set_count = 1;
ble_conf.gap_cfg.role_count_cfg.periph_role_count = 2;
ble_conf.gap_cfg.role_count_cfg.central_role_count = 1;
err_code = sd_ble_cfg_set(BLE_GAP_CFG_ROLE_COUNT, &ble_conf, app_ram_start);
if (err_code != NRF_SUCCESS)
if (err_code != NRF_SUCCESS) {
return err_code;
}
memset(&ble_conf, 0, sizeof(ble_conf));
ble_conf.conn_cfg.conn_cfg_tag = BLE_CONN_CFG_TAG_CUSTOM;
ble_conf.conn_cfg.params.gatts_conn_cfg.hvn_tx_queue_size = MAX_TX_IN_PROGRESS;
err_code = sd_ble_cfg_set(BLE_CONN_CFG_GATTS, &ble_conf, app_ram_start);
if (err_code != NRF_SUCCESS)
if (err_code != NRF_SUCCESS) {
return err_code;
}
// Double the GATT Server attribute size to accomodate both the CircuitPython built-in service
// and anything the user does.
memset(&ble_conf, 0, sizeof(ble_conf));
ble_conf.gatts_cfg.attr_tab_size.attr_tab_size = BLE_GATTS_ATTR_TAB_SIZE_DEFAULT * 3;
err_code = sd_ble_cfg_set(BLE_GATTS_CFG_ATTR_TAB_SIZE, &ble_conf, app_ram_start);
if (err_code != NRF_SUCCESS) {
return err_code;
}
// TODO set ATT_MTU so that the maximum MTU we can negotiate is higher than the default.
// This sets app_ram_start to the minimum value needed for the settings set above.
err_code = sd_ble_enable(&app_ram_start);
if (err_code != NRF_SUCCESS)
if (err_code != NRF_SUCCESS) {
return err_code;
}
ble_gap_conn_params_t gap_conn_params = {
.min_conn_interval = BLE_MIN_CONN_INTERVAL,
@ -122,11 +155,108 @@ STATIC uint32_t ble_stack_enable(void) {
return err_code;
}
void common_hal_bleio_adapter_set_enabled(bool enabled) {
const bool is_enabled = common_hal_bleio_adapter_get_enabled();
STATIC bool adapter_on_ble_evt(ble_evt_t *ble_evt, void *self_in) {
bleio_adapter_obj_t *self = (bleio_adapter_obj_t*)self_in;
// For debugging.
// mp_printf(&mp_plat_print, "Adapter event: 0x%04x\n", ble_evt->header.evt_id);
switch (ble_evt->header.evt_id) {
case BLE_GAP_EVT_CONNECTED: {
// Find an empty connection
bleio_connection_internal_t *connection;
for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) {
connection = &connections[i];
if (connection->conn_handle == BLE_CONN_HANDLE_INVALID) {
break;
}
}
// Central has connected.
ble_gap_evt_connected_t* connected = &ble_evt->evt.gap_evt.params.connected;
connection->conn_handle = ble_evt->evt.gap_evt.conn_handle;
connection->connection_obj = mp_const_none;
ble_drv_add_event_handler_entry(&connection->handler_entry, connection_on_ble_evt, connection);
self->connection_objs = NULL;
// See if connection interval set by Central is out of range.
// If so, negotiate our preferred range.
ble_gap_conn_params_t conn_params;
sd_ble_gap_ppcp_get(&conn_params);
if (conn_params.min_conn_interval < connected->conn_params.min_conn_interval ||
conn_params.min_conn_interval > connected->conn_params.max_conn_interval) {
sd_ble_gap_conn_param_update(ble_evt->evt.gap_evt.conn_handle, &conn_params);
}
self->current_advertising_data = NULL;
break;
}
case BLE_GAP_EVT_DISCONNECTED: {
// Find the connection that was disconnected.
bleio_connection_internal_t *connection;
for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) {
connection = &connections[i];
if (connection->conn_handle == ble_evt->evt.gap_evt.conn_handle) {
break;
}
}
ble_drv_remove_event_handler(connection_on_ble_evt, connection);
connection->conn_handle = BLE_CONN_HANDLE_INVALID;
if (connection->connection_obj != mp_const_none) {
bleio_connection_obj_t* obj = connection->connection_obj;
obj->connection = NULL;
obj->disconnect_reason = ble_evt->evt.gap_evt.params.disconnected.reason;
}
self->connection_objs = NULL;
break;
}
case BLE_GAP_EVT_ADV_SET_TERMINATED:
self->current_advertising_data = NULL;
break;
default:
// For debugging.
// mp_printf(&mp_plat_print, "Unhandled adapter event: 0x%04x\n", ble_evt->header.evt_id);
return false;
break;
}
return true;
}
STATIC void get_address(bleio_adapter_obj_t *self, ble_gap_addr_t *address) {
uint32_t err_code;
err_code = sd_ble_gap_addr_get(address);
if (err_code != NRF_SUCCESS) {
mp_raise_OSError_msg(translate("Failed to get local address"));
}
}
char default_ble_name[] = { 'C', 'I', 'R', 'C', 'U', 'I', 'T', 'P', 'Y', 0, 0, 0, 0 , 0};
STATIC void bleio_adapter_reset_name(bleio_adapter_obj_t *self) {
uint8_t len = sizeof(default_ble_name) - 1;
ble_gap_addr_t local_address;
get_address(self, &local_address);
default_ble_name[len - 4] = nibble_to_hex_lower[local_address.addr[1] >> 4 & 0xf];
default_ble_name[len - 3] = nibble_to_hex_lower[local_address.addr[1] & 0xf];
default_ble_name[len - 2] = nibble_to_hex_lower[local_address.addr[0] >> 4 & 0xf];
default_ble_name[len - 1] = nibble_to_hex_lower[local_address.addr[0] & 0xf];
default_ble_name[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
common_hal_bleio_adapter_set_name(self, (char*) default_ble_name);
}
void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enabled) {
const bool is_enabled = common_hal_bleio_adapter_get_enabled(self);
// Don't enable or disable twice
if ((is_enabled && enabled) || (!is_enabled && !enabled)) {
if (is_enabled == enabled) {
return;
}
@ -137,22 +267,34 @@ void common_hal_bleio_adapter_set_enabled(bool enabled) {
nrfx_power_uninit();
err_code = ble_stack_enable();
// Re-init USB hardware
init_usb_hardware();
} else {
err_code = sd_softdevice_disable();
// Re-init USB hardware
init_usb_hardware();
}
// Re-init USB hardware
init_usb_hardware();
if (err_code != NRF_SUCCESS) {
mp_raise_OSError_msg(translate("Failed to change softdevice state"));
mp_raise_OSError_msg_varg(translate("Failed to change softdevice state, NRF_ERROR_%q"), MP_OBJ_QSTR_VALUE(base_error_messages[err_code - NRF_ERROR_BASE_NUM]));
}
// Add a handler for incoming peripheral connections.
if (enabled) {
for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) {
bleio_connection_internal_t *connection = &connections[i];
connection->conn_handle = BLE_CONN_HANDLE_INVALID;
}
bleio_adapter_reset_name(self);
ble_drv_add_event_handler_entry(&self->handler_entry, adapter_on_ble_evt, self);
} else {
ble_drv_reset();
self->scan_results = NULL;
self->current_advertising_data = NULL;
self->advertising_data = NULL;
self->scan_response_data = NULL;
}
}
bool common_hal_bleio_adapter_get_enabled(void) {
bool common_hal_bleio_adapter_get_enabled(bleio_adapter_obj_t *self) {
uint8_t is_enabled;
const uint32_t err_code = sd_softdevice_is_enabled(&is_enabled);
@ -163,42 +305,339 @@ bool common_hal_bleio_adapter_get_enabled(void) {
return is_enabled;
}
void get_address(ble_gap_addr_t *address) {
bleio_address_obj_t *common_hal_bleio_adapter_get_address(bleio_adapter_obj_t *self) {
common_hal_bleio_adapter_set_enabled(self, true);
ble_gap_addr_t local_address;
get_address(self, &local_address);
bleio_address_obj_t *address = m_new_obj(bleio_address_obj_t);
address->base.type = &bleio_address_type;
common_hal_bleio_address_construct(address, local_address.addr, local_address.addr_type);
return address;
}
mp_obj_str_t* common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) {
uint16_t len = 0;
sd_ble_gap_device_name_get(NULL, &len);
uint8_t buf[len];
uint32_t err_code = sd_ble_gap_device_name_get(buf, &len);
if (err_code != NRF_SUCCESS) {
return NULL;
}
return mp_obj_new_str((char*) buf, len);
}
void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char* name) {
ble_gap_conn_sec_mode_t sec;
sec.lv = 0;
sec.sm = 0;
sd_ble_gap_device_name_set(&sec, (const uint8_t*) name, strlen(name));
}
STATIC bool scan_on_ble_evt(ble_evt_t *ble_evt, void *scan_results_in) {
bleio_scanresults_obj_t *scan_results = (bleio_scanresults_obj_t*)scan_results_in;
if (ble_evt->header.evt_id == BLE_GAP_EVT_TIMEOUT &&
ble_evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_SCAN) {
shared_module_bleio_scanresults_set_done(scan_results, true);
ble_drv_remove_event_handler(scan_on_ble_evt, scan_results);
return true;
}
if (ble_evt->header.evt_id != BLE_GAP_EVT_ADV_REPORT) {
return false;
}
ble_gap_evt_adv_report_t *report = &ble_evt->evt.gap_evt.params.adv_report;
shared_module_bleio_scanresults_append(scan_results,
ticks_ms,
report->type.connectable,
report->type.scan_response,
report->rssi,
report->peer_addr.addr,
report->peer_addr.addr_type,
report->data.p_data,
report->data.len);
const uint32_t err_code = sd_ble_gap_scan_start(NULL, scan_results->common_hal_data);
if (err_code != NRF_SUCCESS) {
// TODO: Pass the error into the scan results so it can throw an exception.
scan_results->done = true;
}
return true;
}
mp_obj_t common_hal_bleio_adapter_start_scan(bleio_adapter_obj_t *self, uint8_t* prefixes, uint8_t prefix_length, bool extended, mp_int_t buffer_size, mp_float_t timeout, mp_float_t interval, mp_float_t window, mp_int_t minimum_rssi, bool active) {
if (self->scan_results != NULL) {
if (!shared_module_bleio_scanresults_get_done(self->scan_results)) {
mp_raise_RuntimeError(translate("Scan already in progess. Stop with stop_scan."));
}
self->scan_results = NULL;
}
self->scan_results = shared_module_bleio_new_scanresults(buffer_size, prefixes, prefix_length, minimum_rssi);
size_t max_packet_size = extended ? BLE_GAP_SCAN_BUFFER_EXTENDED_MAX_SUPPORTED : BLE_GAP_SCAN_BUFFER_MAX;
uint8_t *raw_data = m_malloc(sizeof(ble_data_t) + max_packet_size, false);
ble_data_t * sd_data = (ble_data_t *) raw_data;
self->scan_results->common_hal_data = sd_data;
sd_data->len = max_packet_size;
sd_data->p_data = raw_data + sizeof(ble_data_t);
ble_drv_add_event_handler(scan_on_ble_evt, self->scan_results);
uint32_t nrf_timeout = SEC_TO_UNITS(timeout, UNIT_10_MS);
if (timeout <= 0.0001) {
nrf_timeout = BLE_GAP_SCAN_TIMEOUT_UNLIMITED;
}
ble_gap_scan_params_t scan_params = {
.extended = extended,
.interval = SEC_TO_UNITS(interval, UNIT_0_625_MS),
.timeout = nrf_timeout,
.window = SEC_TO_UNITS(window, UNIT_0_625_MS),
.scan_phys = BLE_GAP_PHY_1MBPS,
.active = active
};
uint32_t err_code;
err_code = sd_ble_gap_scan_start(&scan_params, sd_data);
common_hal_bleio_adapter_set_enabled(true);
err_code = sd_ble_gap_addr_get(address);
if (err_code != NRF_SUCCESS) {
self->scan_results = NULL;
ble_drv_remove_event_handler(scan_on_ble_evt, self->scan_results);
mp_raise_OSError_msg_varg(translate("Failed to start scanning, err 0x%04x"), err_code);
}
return MP_OBJ_FROM_PTR(self->scan_results);
}
void common_hal_bleio_adapter_stop_scan(bleio_adapter_obj_t *self) {
sd_ble_gap_scan_stop();
shared_module_bleio_scanresults_set_done(self->scan_results, true);
ble_drv_remove_event_handler(scan_on_ble_evt, self->scan_results);
self->scan_results = NULL;
}
typedef struct {
uint16_t conn_handle;
volatile bool done;
} connect_info_t;
STATIC bool connect_on_ble_evt(ble_evt_t *ble_evt, void *info_in) {
connect_info_t *info = (connect_info_t*)info_in;
switch (ble_evt->header.evt_id) {
case BLE_GAP_EVT_CONNECTED:
info->conn_handle = ble_evt->evt.gap_evt.conn_handle;
info->done = true;
break;
case BLE_GAP_EVT_TIMEOUT:
// Handle will be invalid.
info->done = true;
break;
default:
// For debugging.
// mp_printf(&mp_plat_print, "Unhandled central event: 0x%04x\n", ble_evt->header.evt_id);
return false;
break;
}
return true;
}
mp_obj_t common_hal_bleio_adapter_connect(bleio_adapter_obj_t *self, bleio_address_obj_t *address, mp_float_t timeout, bool pair) {
ble_gap_addr_t addr;
addr.addr_type = address->type;
mp_buffer_info_t address_buf_info;
mp_get_buffer_raise(address->bytes, &address_buf_info, MP_BUFFER_READ);
memcpy(addr.addr, (uint8_t *) address_buf_info.buf, NUM_BLEIO_ADDRESS_BYTES);
ble_gap_scan_params_t scan_params = {
.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS),
.window = MSEC_TO_UNITS(100, UNIT_0_625_MS),
.scan_phys = BLE_GAP_PHY_1MBPS,
// timeout of 0 means no timeout
.timeout = SEC_TO_UNITS(timeout, UNIT_10_MS),
};
ble_gap_conn_params_t conn_params = {
.conn_sup_timeout = MSEC_TO_UNITS(4000, UNIT_10_MS),
.min_conn_interval = MSEC_TO_UNITS(15, UNIT_1_25_MS),
.max_conn_interval = MSEC_TO_UNITS(300, UNIT_1_25_MS),
.slave_latency = 0, // number of conn events
};
connect_info_t event_info;
ble_drv_add_event_handler(connect_on_ble_evt, &event_info);
event_info.done = false;
uint32_t err_code = sd_ble_gap_connect(&addr, &scan_params, &conn_params, BLE_CONN_CFG_TAG_CUSTOM);
if (err_code != NRF_SUCCESS) {
mp_raise_OSError_msg(translate("Failed to get local address"));
ble_drv_remove_event_handler(connect_on_ble_evt, &event_info);
mp_raise_OSError_msg_varg(translate("Failed to start connecting, error 0x%04x"), err_code);
}
while (!event_info.done) {
RUN_BACKGROUND_TASKS;
}
ble_drv_remove_event_handler(connect_on_ble_evt, &event_info);
if (event_info.conn_handle == BLE_CONN_HANDLE_INVALID) {
mp_raise_OSError_msg(translate("Failed to connect: timeout"));
}
// Make the connection object and return it.
for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) {
bleio_connection_internal_t *connection = &connections[i];
if (connection->conn_handle == event_info.conn_handle) {
return bleio_connection_new_from_internal(connection);
}
}
mp_raise_OSError_msg(translate("Failed to connect: internal error"));
return mp_const_none;
}
bleio_address_obj_t *common_hal_bleio_adapter_get_address(void) {
common_hal_bleio_adapter_set_enabled(true);
// The nRF SD 6.1.0 can only do one concurrent advertisement so share the advertising handle.
uint8_t adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET;
ble_gap_addr_t local_address;
get_address(&local_address);
STATIC void check_data_fit(size_t data_len) {
if (data_len > BLE_GAP_ADV_SET_DATA_SIZE_MAX) {
mp_raise_ValueError(translate("Data too large for advertisement packet"));
}
}
bleio_address_obj_t *address = m_new_obj(bleio_address_obj_t);
address->base.type = &bleio_address_type;
uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool connectable, float interval, uint8_t *advertising_data, uint16_t advertising_data_len, uint8_t *scan_response_data, uint16_t scan_response_data_len) {
if (self->current_advertising_data != NULL && self->current_advertising_data == self->advertising_data) {
return NRF_ERROR_BUSY;
}
common_hal_bleio_address_construct(address, local_address.addr, local_address.addr_type);
return address;
// If the current advertising data isn't owned by the adapter then it must be an internal
// advertisement that we should stop.
if (self->current_advertising_data != NULL) {
common_hal_bleio_adapter_stop_advertising(self);
}
uint32_t err_code;
ble_gap_adv_params_t adv_params = {
.interval = SEC_TO_UNITS(interval, UNIT_0_625_MS),
.properties.type = connectable ? BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED
: BLE_GAP_ADV_TYPE_NONCONNECTABLE_NONSCANNABLE_UNDIRECTED,
.duration = BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED,
.filter_policy = BLE_GAP_ADV_FP_ANY,
.primary_phy = BLE_GAP_PHY_1MBPS,
};
const ble_gap_adv_data_t ble_gap_adv_data = {
.adv_data.p_data = advertising_data,
.adv_data.len = advertising_data_len,
.scan_rsp_data.p_data = scan_response_data_len > 0 ? scan_response_data : NULL,
.scan_rsp_data.len = scan_response_data_len,
};
err_code = sd_ble_gap_adv_set_configure(&adv_handle, &ble_gap_adv_data, &adv_params);
if (err_code != NRF_SUCCESS) {
return err_code;
}
err_code = sd_ble_gap_adv_start(adv_handle, BLE_CONN_CFG_TAG_CUSTOM);
if (err_code != NRF_SUCCESS) {
return err_code;
}
self->current_advertising_data = advertising_data;
return NRF_SUCCESS;
}
mp_obj_t common_hal_bleio_adapter_get_default_name(void) {
common_hal_bleio_adapter_set_enabled(true);
ble_gap_addr_t local_address;
get_address(&local_address);
void common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool connectable, mp_float_t interval, mp_buffer_info_t *advertising_data_bufinfo, mp_buffer_info_t *scan_response_data_bufinfo) {
if (self->current_advertising_data != NULL && self->current_advertising_data == self->advertising_data) {
mp_raise_OSError_msg(translate("Already advertising."));
}
// interval value has already been validated.
uint32_t err_code;
check_data_fit(advertising_data_bufinfo->len);
check_data_fit(scan_response_data_bufinfo->len);
// The advertising data buffers must not move, because the SoftDevice depends on them.
// So make them long-lived and reuse them onwards.
if (self->advertising_data == NULL) {
self->advertising_data = (uint8_t *) gc_alloc(BLE_GAP_ADV_SET_DATA_SIZE_MAX * sizeof(uint8_t), false, true);
}
if (self->scan_response_data == NULL) {
self->scan_response_data = (uint8_t *) gc_alloc(BLE_GAP_ADV_SET_DATA_SIZE_MAX * sizeof(uint8_t), false, true);
}
memcpy(self->advertising_data, advertising_data_bufinfo->buf, advertising_data_bufinfo->len);
memcpy(self->scan_response_data, scan_response_data_bufinfo->buf, scan_response_data_bufinfo->len);
err_code = _common_hal_bleio_adapter_start_advertising(self, connectable, interval, self->advertising_data, advertising_data_bufinfo->len, self->scan_response_data, scan_response_data_bufinfo->len);
char name[] = { 'C', 'I', 'R', 'C', 'U', 'I', 'T', 'P', 'Y', 0, 0, 0, 0 };
if (err_code != NRF_SUCCESS) {
mp_raise_OSError_msg_varg(translate("Failed to start advertising, NRF_ERROR_%q"), MP_OBJ_QSTR_VALUE(base_error_messages[err_code - NRF_ERROR_BASE_NUM]));
}
}
void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self) {
if (adv_handle == BLE_GAP_ADV_SET_HANDLE_NOT_SET)
return;
// TODO: Don't actually stop. Switch to advertising CircuitPython if we don't already have a connection.
const uint32_t err_code = sd_ble_gap_adv_stop(adv_handle);
self->current_advertising_data = NULL;
if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_INVALID_STATE)) {
mp_raise_OSError_msg_varg(translate("Failed to stop advertising, NRF_ERROR_%q"), MP_OBJ_QSTR_VALUE(base_error_messages[err_code - NRF_ERROR_BASE_NUM]));
}
}
name[sizeof(name) - 4] = nibble_to_hex_lower[local_address.addr[1] >> 4 & 0xf];
name[sizeof(name) - 3] = nibble_to_hex_lower[local_address.addr[1] & 0xf];
name[sizeof(name) - 2] = nibble_to_hex_lower[local_address.addr[0] >> 4 & 0xf];
name[sizeof(name) - 1] = nibble_to_hex_lower[local_address.addr[0] & 0xf];
bool common_hal_bleio_adapter_get_connected(bleio_adapter_obj_t *self) {
for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) {
bleio_connection_internal_t *connection = &connections[i];
if (connection->conn_handle != BLE_CONN_HANDLE_INVALID) {
return true;
}
}
return false;
}
return mp_obj_new_str(name, sizeof(name));
mp_obj_t common_hal_bleio_adapter_get_connections(bleio_adapter_obj_t *self) {
if (self->connection_objs != NULL) {
return self->connection_objs;
}
size_t total_connected = 0;
mp_obj_t items[BLEIO_TOTAL_CONNECTION_COUNT];
for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) {
bleio_connection_internal_t *connection = &connections[i];
if (connection->conn_handle != BLE_CONN_HANDLE_INVALID) {
if (connection->connection_obj == mp_const_none) {
connection->connection_obj = bleio_connection_new_from_internal(connection);
}
items[total_connected] = connection->connection_obj;
total_connected++;
}
}
self->connection_objs = mp_obj_new_tuple(total_connected, items);
return self->connection_objs;
}
void bleio_adapter_gc_collect(bleio_adapter_obj_t* adapter) {
gc_collect_root((void**)adapter, sizeof(bleio_adapter_obj_t) / sizeof(size_t));
gc_collect_root((void**)connections, sizeof(connections) / sizeof(size_t));
}
void bleio_adapter_reset(bleio_adapter_obj_t* adapter) {
common_hal_bleio_adapter_stop_scan(adapter);
common_hal_bleio_adapter_stop_advertising(adapter);
adapter->connection_objs = NULL;
for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) {
bleio_connection_internal_t *connection = &connections[i];
connection->connection_obj = mp_const_none;
}
}

@ -30,9 +30,27 @@
#define MICROPY_INCLUDED_NRF_COMMON_HAL_BLEIO_ADAPTER_H
#include "py/obj.h"
#include "py/objtuple.h"
#include "shared-bindings/_bleio/Connection.h"
#include "shared-bindings/_bleio/ScanResults.h"
#define BLEIO_TOTAL_CONNECTION_COUNT 2
extern bleio_connection_internal_t connections[BLEIO_TOTAL_CONNECTION_COUNT];
typedef struct {
mp_obj_base_t base;
} super_adapter_obj_t;
uint8_t* advertising_data;
uint8_t* scan_response_data;
uint8_t* current_advertising_data;
bleio_scanresults_obj_t* scan_results;
mp_obj_t name;
mp_obj_tuple_t *connection_objs;
ble_drv_evt_handler_entry_t handler_entry;
} bleio_adapter_obj_t;
void bleio_adapter_gc_collect(bleio_adapter_obj_t* adapter);
void bleio_adapter_reset(bleio_adapter_obj_t* adapter);
#endif // MICROPY_INCLUDED_NRF_COMMON_HAL_BLEIO_ADAPTER_H

@ -1,145 +0,0 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Dan Halbert for Adafruit Industries
* Copyright (c) 2018 Artur Pacholec
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <string.h>
#include <stdio.h>
#include "ble.h"
#include "ble_drv.h"
#include "ble_hci.h"
#include "nrf_soc.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "shared-bindings/_bleio/__init__.h"
#include "shared-bindings/_bleio/Adapter.h"
#include "shared-bindings/_bleio/Central.h"
STATIC void central_on_ble_evt(ble_evt_t *ble_evt, void *central_in) {
bleio_central_obj_t *central = (bleio_central_obj_t*)central_in;
switch (ble_evt->header.evt_id) {
case BLE_GAP_EVT_CONNECTED:
central->conn_handle = ble_evt->evt.gap_evt.conn_handle;
central->waiting_to_connect = false;
break;
case BLE_GAP_EVT_TIMEOUT:
// Handle will be invalid.
central->waiting_to_connect = false;
break;
case BLE_GAP_EVT_DISCONNECTED:
central->conn_handle = BLE_CONN_HANDLE_INVALID;
break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
sd_ble_gap_sec_params_reply(central->conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
break;
case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST: {
ble_gap_evt_conn_param_update_request_t *request =
&ble_evt->evt.gap_evt.params.conn_param_update_request;
sd_ble_gap_conn_param_update(central->conn_handle, &request->conn_params);
break;
}
default:
// For debugging.
// mp_printf(&mp_plat_print, "Unhandled central event: 0x%04x\n", ble_evt->header.evt_id);
break;
}
}
void common_hal_bleio_central_construct(bleio_central_obj_t *self) {
common_hal_bleio_adapter_set_enabled(true);
self->remote_service_list = mp_obj_new_list(0, NULL);
self->conn_handle = BLE_CONN_HANDLE_INVALID;
}
void common_hal_bleio_central_connect(bleio_central_obj_t *self, bleio_address_obj_t *address, mp_float_t timeout) {
common_hal_bleio_adapter_set_enabled(true);
ble_drv_add_event_handler(central_on_ble_evt, self);
ble_gap_addr_t addr;
addr.addr_type = address->type;
mp_buffer_info_t address_buf_info;
mp_get_buffer_raise(address->bytes, &address_buf_info, MP_BUFFER_READ);
memcpy(addr.addr, (uint8_t *) address_buf_info.buf, NUM_BLEIO_ADDRESS_BYTES);
ble_gap_scan_params_t scan_params = {
.interval = MSEC_TO_UNITS(100, UNIT_0_625_MS),
.window = MSEC_TO_UNITS(100, UNIT_0_625_MS),
.scan_phys = BLE_GAP_PHY_1MBPS,
// timeout of 0 means no timeout
.timeout = SEC_TO_UNITS(timeout, UNIT_10_MS),
};
ble_gap_conn_params_t conn_params = {
.conn_sup_timeout = MSEC_TO_UNITS(4000, UNIT_10_MS),
.min_conn_interval = MSEC_TO_UNITS(15, UNIT_1_25_MS),
.max_conn_interval = MSEC_TO_UNITS(300, UNIT_1_25_MS),
.slave_latency = 0, // number of conn events
};
self->waiting_to_connect = true;
uint32_t err_code = sd_ble_gap_connect(&addr, &scan_params, &conn_params, BLE_CONN_CFG_TAG_CUSTOM);
if (err_code != NRF_SUCCESS) {
mp_raise_OSError_msg_varg(translate("Failed to start connecting, error 0x%04x"), err_code);
}
while (self->waiting_to_connect) {
RUN_BACKGROUND_TASKS;
}
if (self->conn_handle == BLE_CONN_HANDLE_INVALID) {
mp_raise_OSError_msg(translate("Failed to connect: timeout"));
}
}
void common_hal_bleio_central_disconnect(bleio_central_obj_t *self) {
sd_ble_gap_disconnect(self->conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
}
bool common_hal_bleio_central_get_connected(bleio_central_obj_t *self) {
return self->conn_handle != BLE_CONN_HANDLE_INVALID;
}
mp_obj_tuple_t *common_hal_bleio_central_discover_remote_services(bleio_central_obj_t *self, mp_obj_t service_uuids_whitelist) {
common_hal_bleio_device_discover_remote_services(MP_OBJ_FROM_PTR(self), service_uuids_whitelist);
// Convert to a tuple and then clear the list so the callee will take ownership.
mp_obj_tuple_t *services_tuple = mp_obj_new_tuple(self->remote_service_list->len,
self->remote_service_list->items);
mp_obj_list_clear(self->remote_service_list);
return services_tuple;
}
mp_obj_list_t *common_hal_bleio_central_get_remote_services(bleio_central_obj_t *self) {
return self->remote_service_list;
}

@ -32,7 +32,7 @@
#include "shared-bindings/_bleio/Descriptor.h"
#include "shared-bindings/_bleio/Service.h"
static volatile bleio_characteristic_obj_t *m_read_characteristic;
#include "common-hal/_bleio/Adapter.h"
STATIC uint16_t characteristic_get_cccd(uint16_t cccd_handle, uint16_t conn_handle) {
uint16_t cccd;
@ -53,27 +53,6 @@ STATIC uint16_t characteristic_get_cccd(uint16_t cccd_handle, uint16_t conn_hand
return cccd;
}
STATIC void characteristic_on_gattc_read_rsp_evt(ble_evt_t *ble_evt, void *param) {
switch (ble_evt->header.evt_id) {
// More events may be handled later, so keep this as a switch.
case BLE_GATTC_EVT_READ_RSP: {
ble_gattc_evt_read_rsp_t *response = &ble_evt->evt.gattc_evt.params.read_rsp;
if (m_read_characteristic) {
m_read_characteristic->value = mp_obj_new_bytearray(response->len, response->data);
}
// Indicate to busy-wait loop that we've read the attribute value.
m_read_characteristic = NULL;
break;
}
default:
// For debugging.
// mp_printf(&mp_plat_print, "Unhandled characteristic event: 0x%04x\n", ble_evt->header.evt_id);
break;
}
}
STATIC void characteristic_gatts_notify_indicate(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo, uint16_t hvx_type) {
uint16_t hvx_len = bufinfo->len;
@ -103,35 +82,14 @@ STATIC void characteristic_gatts_notify_indicate(uint16_t handle, uint16_t conn_
}
}
STATIC void characteristic_gattc_read(bleio_characteristic_obj_t *characteristic) {
const uint16_t conn_handle = common_hal_bleio_device_get_conn_handle(characteristic->service->device);
common_hal_bleio_check_connected(conn_handle);
// Set to NULL in event loop after event.
m_read_characteristic = characteristic;
ble_drv_add_event_handler(characteristic_on_gattc_read_rsp_evt, characteristic);
const uint32_t err_code = sd_ble_gattc_read(conn_handle, characteristic->handle, 0);
if (err_code != NRF_SUCCESS) {
mp_raise_OSError_msg_varg(translate("Failed to read attribute value, err 0x%04x"), err_code);
}
while (m_read_characteristic != NULL) {
RUN_BACKGROUND_TASKS;
}
ble_drv_remove_event_handler(characteristic_on_gattc_read_rsp_evt, characteristic);
}
void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, bleio_service_obj_t *service, bleio_uuid_obj_t *uuid, bleio_characteristic_properties_t props, bleio_attribute_security_mode_t read_perm, bleio_attribute_security_mode_t write_perm, mp_int_t max_length, bool fixed_length, mp_buffer_info_t *initial_value_bufinfo) {
void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, bleio_service_obj_t *service, uint16_t handle, bleio_uuid_obj_t *uuid, bleio_characteristic_properties_t props, bleio_attribute_security_mode_t read_perm, bleio_attribute_security_mode_t write_perm, mp_int_t max_length, bool fixed_length, mp_buffer_info_t *initial_value_bufinfo) {
self->service = service;
self->uuid = uuid;
self->handle = BLE_GATT_HANDLE_INVALID;
self->props = props;
self->read_perm = read_perm;
self->write_perm = write_perm;
self->descriptor_list = mp_obj_new_list(0, NULL);
self->descriptor_list = NULL;
const mp_int_t max_length_max = fixed_length ? BLE_GATTS_FIX_ATTR_LEN_MAX : BLE_GATTS_VAR_ATTR_LEN_MAX;
if (max_length < 0 || max_length > max_length_max) {
@ -141,10 +99,18 @@ void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self,
self->max_length = max_length;
self->fixed_length = fixed_length;
common_hal_bleio_characteristic_set_value(self, initial_value_bufinfo);
if (service->is_remote) {
self->handle = handle;
} else {
common_hal_bleio_service_add_characteristic(self->service, self, initial_value_bufinfo);
}
if (initial_value_bufinfo != NULL) {
common_hal_bleio_characteristic_set_value(self, initial_value_bufinfo);
}
}
mp_obj_list_t *common_hal_bleio_characteristic_get_descriptor_list(bleio_characteristic_obj_t *self) {
bleio_descriptor_obj_t *common_hal_bleio_characteristic_get_descriptor_list(bleio_characteristic_obj_t *self) {
return self->descriptor_list;
}
@ -152,19 +118,19 @@ bleio_service_obj_t *common_hal_bleio_characteristic_get_service(bleio_character
return self->service;
}
mp_obj_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self) {
size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t* buf, size_t len) {
// Do GATT operations only if this characteristic has been added to a registered service.
if (self->handle != BLE_GATT_HANDLE_INVALID) {
uint16_t conn_handle = common_hal_bleio_device_get_conn_handle(self->service->device);
uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection);
if (common_hal_bleio_service_get_is_remote(self->service)) {
// self->value is set by evt handler.
characteristic_gattc_read(self);
return common_hal_bleio_gattc_read(self->handle, conn_handle, buf, len);
} else {
self->value = common_hal_bleio_gatts_read(self->handle, conn_handle);
return common_hal_bleio_gatts_read(self->handle, conn_handle, buf, len);
}
}
return self->value;
return 0;
}
void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, mp_buffer_info_t *bufinfo) {
@ -175,39 +141,40 @@ void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self,
mp_raise_ValueError(translate("Value length > max_length"));
}
self->value = mp_obj_new_bytes(bufinfo->buf, bufinfo->len);
// Do GATT operations only if this characteristic has been added to a registered service.
if (self->handle != BLE_GATT_HANDLE_INVALID) {
uint16_t conn_handle = common_hal_bleio_device_get_conn_handle(self->service->device);
if (common_hal_bleio_service_get_is_remote(self->service)) {
uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection);
// Last argument is true if write-no-reponse desired.
common_hal_bleio_gattc_write(self->handle, conn_handle, bufinfo,
(self->props & CHAR_PROP_WRITE_NO_RESPONSE));
} else {
bool sent = false;
uint16_t cccd = 0;
const bool notify = self->props & CHAR_PROP_NOTIFY;
const bool indicate = self->props & CHAR_PROP_INDICATE;
if (notify | indicate) {
cccd = characteristic_get_cccd(self->cccd_handle, conn_handle);
}
// It's possible that both notify and indicate are set.
if (notify && (cccd & BLE_GATT_HVX_NOTIFICATION)) {
characteristic_gatts_notify_indicate(self->handle, conn_handle, bufinfo, BLE_GATT_HVX_NOTIFICATION);
sent = true;
}
if (indicate && (cccd & BLE_GATT_HVX_INDICATION)) {
characteristic_gatts_notify_indicate(self->handle, conn_handle, bufinfo, BLE_GATT_HVX_INDICATION);
sent = true;
}
if (!sent) {
common_hal_bleio_gatts_write(self->handle, conn_handle, bufinfo);
// Always write the value locally even if no connections are active.
common_hal_bleio_gatts_write(self->handle, BLE_CONN_HANDLE_INVALID, bufinfo);
// Check to see if we need to notify or indicate any active connections.
for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) {
bleio_connection_internal_t *connection = &connections[i];
uint16_t conn_handle = connection->conn_handle;
if (connection->conn_handle == BLE_CONN_HANDLE_INVALID) {
continue;
}
uint16_t cccd = 0;
const bool notify = self->props & CHAR_PROP_NOTIFY;
const bool indicate = self->props & CHAR_PROP_INDICATE;
if (notify | indicate) {
cccd = characteristic_get_cccd(self->cccd_handle, conn_handle);
}
// It's possible that both notify and indicate are set.
if (notify && (cccd & BLE_GATT_HVX_NOTIFICATION)) {
characteristic_gatts_notify_indicate(self->handle, conn_handle, bufinfo, BLE_GATT_HVX_NOTIFICATION);
}
if (indicate && (cccd & BLE_GATT_HVX_INDICATION)) {
characteristic_gatts_notify_indicate(self->handle, conn_handle, bufinfo, BLE_GATT_HVX_INDICATION);
}
}
}
}
@ -252,7 +219,8 @@ void common_hal_bleio_characteristic_add_descriptor(bleio_characteristic_obj_t *
mp_raise_OSError_msg_varg(translate("Failed to add descriptor, err 0x%04x"), err_code);
}
mp_obj_list_append(self->descriptor_list, MP_OBJ_FROM_PTR(descriptor));
descriptor->next = self->descriptor_list;
self->descriptor_list = descriptor;
}
void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, bool notify, bool indicate) {
@ -264,7 +232,7 @@ void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self,
mp_raise_ValueError(translate("Can't set CCCD on local Characteristic"));
}
const uint16_t conn_handle = common_hal_bleio_device_get_conn_handle(self->service->device);
const uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection);
common_hal_bleio_check_connected(conn_handle);
uint16_t cccd_value =

@ -29,11 +29,12 @@
#define MICROPY_INCLUDED_NRF_COMMON_HAL_BLEIO_CHARACTERISTIC_H
#include "shared-bindings/_bleio/Attribute.h"
#include "common-hal/_bleio/Descriptor.h"
#include "shared-module/_bleio/Characteristic.h"
#include "common-hal/_bleio/Service.h"
#include "common-hal/_bleio/UUID.h"
typedef struct {
typedef struct _bleio_characteristic_obj {
mp_obj_base_t base;
// Will be MP_OBJ_NULL before being assigned to a Service.
bleio_service_obj_t *service;
@ -45,7 +46,7 @@ typedef struct {
bleio_characteristic_properties_t props;
bleio_attribute_security_mode_t read_perm;
bleio_attribute_security_mode_t write_perm;
mp_obj_list_t *descriptor_list;
bleio_descriptor_obj_t *descriptor_list;
uint16_t user_desc_handle;
uint16_t cccd_handle;
uint16_t sccd_handle;

@ -38,6 +38,7 @@
#include "tick.h"
#include "shared-bindings/_bleio/__init__.h"
#include "shared-bindings/_bleio/Connection.h"
#include "common-hal/_bleio/CharacteristicBuffer.h"
STATIC void write_to_ringbuf(bleio_characteristic_buffer_obj_t *self, uint8_t *data, uint16_t len) {
@ -50,7 +51,7 @@ STATIC void write_to_ringbuf(bleio_characteristic_buffer_obj_t *self, uint8_t *d
sd_nvic_critical_region_exit(is_nested_critical_region);
}
STATIC void characteristic_buffer_on_ble_evt(ble_evt_t *ble_evt, void *param) {
STATIC bool characteristic_buffer_on_ble_evt(ble_evt_t *ble_evt, void *param) {
bleio_characteristic_buffer_obj_t *self = (bleio_characteristic_buffer_obj_t *) param;
switch (ble_evt->header.evt_id) {
case BLE_GATTS_EVT_WRITE: {
@ -75,7 +76,11 @@ STATIC void characteristic_buffer_on_ble_evt(ble_evt_t *ble_evt, void *param) {
}
break;
}
default:
return false;
break;
}
return true;
}
// Assumes that timeout and buffer_size have been validated before call.
@ -150,6 +155,7 @@ void common_hal_bleio_characteristic_buffer_deinit(bleio_characteristic_buffer_o
bool common_hal_bleio_characteristic_buffer_connected(bleio_characteristic_buffer_obj_t *self) {
return self->characteristic != NULL &&
self->characteristic->service != NULL &&
self->characteristic->service->device != NULL &&
common_hal_bleio_device_get_conn_handle(self->characteristic->service->device) != BLE_CONN_HANDLE_INVALID;
(!self->characteristic->service->is_remote ||
(self->characteristic->service->connection != MP_OBJ_NULL &&
common_hal_bleio_connection_get_connected(self->characteristic->service->connection)));
}

@ -0,0 +1,629 @@
/*
* This file is part of the MicroPython project, http://micropython.org/